body:
Regarding the question, “Does PinChangeInt only work on digital pins?”, note that PCI's work on all the digital pins of an ATmega328, and on the first six analog pins.  (32-pin '328s have eight analog pins, A0-A7; 28-pin '328s only six, A0-A5.)

Regarding the problem symptom that “`pulsewidth` just seems to increase continuously”, that could happen if for some reason rising edges aren't processed.  To debug, add a couple more volative byte variables, say `nrises` and `nfalls`; increment each of them in the appropriate interrupt handler; and report their values from time to time.

Regarding your `#include <PinChangeInt.h>` statement, note that `PinChangeInt.h` is [deprecated](https://github.com/GreyGnome/PinChangeInt/commit/ec745f854b2b807640341cf479f540bb8bb3fc2f) (as of 3 April 2015).  Consider using [`EnableInterrupt.h`](https://github.com/GreyGnome/EnableInterrupt) instead.

It's possible you'll resolve your problem while changing libraries.  If so, fine.  If not, or if that library's performance isn't adequate, consider changing over to handling the  pin change interrupts more directly.  The ISR in the following sketch shown below runs several times faster than code that uses `PinChangeInt` or `EnableInterrupt` library calls.

[*Edit:* This edit encloses the ISR in a sketch that compiles.  The code previously shown was missing two array length specifications.  This code was tested with a rotary encoder attached to A2, A3, with A0 and A1 grounded; an output sample (using an Arduino Nano) follows the code.]

    /*  rcTiming.ino -- JW, 30 November 2015 --
     * Uses pin-change interrupts on A0-A4 to time RC pulses
     *
     * Ref: http://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
     *
     */
    #include <Streaming.h>
    static   byte rcOld;        // Prev. states of inputs
    volatile unsigned long rcRises[4]; // times of prev. rising edges
    volatile unsigned long rcTimes[4]; // recent pulse lengths
    volatile unsigned int  rcChange=0; // Change-counter

    // Be sure to call setup_rcTiming() from setup()
    void setup_rcTiming() {
      rcOld = 0;
      pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
      pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
      pinMode(A2, INPUT);
      pinMode(A3, INPUT);
      PCMSK1 |= 0x0F;       // Four-bit mask for four channels
      PCIFR  |= 0x02;       // clear pin-change interrupts if any
      PCICR  |= 0x02;       // enable pin-change interrupts
    }
    // Define the service routine for PCI vector 1
    ISR(PCINT1_vect) {
      byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
      byte changes = rcNew^rcOld;   // Notice changed bits
      byte channel = 0;
      unsigned long now = micros(); // micros() is ok in int routine
      while (changes) {
        if ((changes & 1)) {  // Did current channel change?
          if ((rcNew & (1<<channel))) { // Check rising edge
            rcRises[channel] = now;     // Is rising edge
          } else {              // Is falling edge
            rcTimes[channel] = now-rcRises[channel];
          }
        }
        changes >>= 1;      // shift out the done bit
        ++channel;
        ++rcChange;
      }
      rcOld = rcNew;        // Save new state
    }

    void setup() {
      Serial.begin(115200);
      Serial.println("Starting RC Timing Test");
      setup_rcTiming();
    }

    void loop() {
      unsigned long rcT[4]; // copy of recent pulse lengths
      unsigned int rcN;
      if (rcChange) {

        // Data is subject to races if interrupted, so off interrupts
        cli();   // Disable interrupts
        rcN = rcChange;
        rcChange = 0;  // Zero the change counter
        rcT[0] = rcTimes[0];
        rcT[1] = rcTimes[1];
        rcT[2] = rcTimes[2];
        rcT[3] = rcTimes[3];
        sei();   // reenable interrupts

        Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
        << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
      }
      sei();   // reenable interrupts
    }

The code shown above uses `Streaming.h`, a [contributed library](https://www.arduino.cc/en/Reference/Libraries) that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like `<<` Serial stream operators to `Serial.print` statements, without increasing code size.  If you don't have `Streaming.h` installed, either install it via [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/) or manually translate the `Serial << ...` statement to `Serial.print` statements.

A sample of the sketch's output on serial monitor:

    t=35773 0 0 14196 13456 4
    t=35775 0 0 14196 13456 3
    t=35778 0 0 14196 5748 4
    t=35781 0 0 5244 5748 3
    t=35783 0 0 5244 5748 4
    t=35785 0 0 5244 5748 3
    t=35786 0 0 5244 28 12
    t=35788 0 0 3024 28 3
    t=35789 0 0 3024 28 4
    t=35792 0 0 3024 28 3
    t=35796 0 0 3024 6396 4
    t=35802 0 0 9316 6396 3
    t=35809 0 0 9316 6396 4

In the output above, the two 0's are from A0, A1 being grounded and not changing.  The next two numbers are from the DT and CLK lines of a KY-040 rotary encoder, which toggle alternately to encode step-direction.  They should represent on-times in microseconds, and are always multiples of 4 because `micros()` reports multiples of 4.

The last number is the number of times the ISR's change-checking loop ran since `loop()`'s previous print.  An A2 change will show a count of 3 or more, and an A3 change 4 or more.  Cases where times are the same may represent contact bounces shorter than the ISR's service time; ie, several falling edges in a row might be detected, or several rising edges.  A storage scope or logic analyzer probably is necessary for finding out exactly what happens.


sender: user

message:
LM35 and Character LCD

I have an arduino pro mini and I have attached a 16x2 character LCD and an LM35 analog temperature sensor. When I upload a sketch using only the sensor and send the readings to serial monitor, the readings are OK. When I upload a sketch that displays the readings to the LCD the readings are about 130°C in room temperature. Where is the problem and how can I solve it. Thanks in advance

Code with lcd:

    #include <LiquidCrystal.h>
    byte smiley[8] = {
      B00000,
      B01110,
      B01010,
      B01110,
      B00000,
      B00000,
      B00000,
    };
    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.createChar(0, smiley);
      lcd.begin(16, 2);
      analogReference(INTERNAL);
      // Print a message to the LCD.
      lcd.print(analogRead(0)/1024.0 * 500);
      lcd.write(byte(0));
      lcd.print("C");
      lcd.setCursor(0, 2);
      lcd.print("21");
      lcd.write(byte(0));
      lcd.print("C");

    }

    void loop() {
      // Turn off the cursor:
      lcd.print((analogRead(0)/1024.0)*500);
      lcd.write(byte(0));
      lcd.print("C");
      lcd.setCursor(0, 2);
      delay(5000);
      lcd.clear();
    }

Only sensor code:

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println(analogRead(0)/1024.0*500);
      delay(500);
    }

sender: assistant

body:
Firstly you do not keep your code consistent between you temperature test and your LCD test code. The problem lies in your use of the **internal** analog reference, that reference is 1.1V and that is giving you 130°C.

Temp = 260*0.5= 130

The 260 is the ADC reading worked back from the 130°C you gave

To use Internal reference-

Internal ref = 1.1÷1024=0.001074219
That multiplied by one hundred to account for the mV reading of the lm35 gives `0.107` that will give you the correct temp when using the internal reference

[Analog reference][1] from the arduino site.

If you want to use the analog reading *0.5 comment out the `analogReference()`

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


message:
Arduino Simple Task - sweeping a buzzer and led, not working as expected

> Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

# UPDATE: IT seems that there is a problem using pin 11 and 13 together but if I use a different pwm pin like pin 5. It's okay. I'm guessing that the timers used at pin 11 is connected to tone() but not sure... #

I’ve encountered a weird problem with an Arduino with this simple task. It involves just a buzzer and LED and a very simple custom library that I made.

I wanted the buzzer to sweep back and forth with a specified frequency range (f1, f2), the led will also display a specific brightness (0, 50) based on the frequency being played.

The buzzer works perfectly on its own, and also the LED, but when you put them together, it malfunctions.

**A more detailed explanation can be found here: https://tilarduino.wordpress.com/2015/11/27/weird-arduino-problem-buzzer-led-brightness/
And i've included all the files i've used here: https://gist.github.com/mithi/09ae419a3c7eba285221**

Using this code below, commenting out line 19 with line 18 uncommented-out will make the buzzer work, and commenting out line 19 with line 18 back in will make the led work as expected. But together, the code malfunctions. buzzer is attached to pin 13 and led is attached to pin 11.

    #include "SimplestLibrary.h"

    Sweeper sweeper;
    Buzzer buzzer;
    AnalogLED led;

    int f1 = 3000;
    int f2 = 4500;
    int f = 0;

    void setup() {
        sweeper.New(f1, f2, BACKANDFORTH);
        buzzer.New(13);
        led.New(11);
    }

    void loop() {
        f = sweeper.Update(1);
        buzzer.Play(f, 4, 2);
        led.NewBrightness(map(f, f1, f2, 0, 50));
        delay(1);
    }

body:
From [Arduino.cc](https://www.arduino.cc/en/Reference/Tone):

>Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

Simple solution is to use a PWM that isn't an output from `Timer2` :

    Timer      OCxA pin    OCxB pin
      0           6        5
      1           9        10
      2           11       3


message:
Better way than exit(0)?

The following code does what I need it to do (when a start switch is on and door switch is off - a warning light flashes. When the start switch and door switch are both on - a valve opens to allow water in for 2 seconds). I need the light to flash until the door is HIGH too at which point the valve program runs once.  The only way I have to get out of this is to use exit(0). Is there a better way to do this? Ideally, I would like to stay away from anything too Boolean! Thank you.

<!-- language: c -->

    int start = 2;
    int door = 3;
    int light = 8;
    int valve = 9;
    int counter = 0;

    void setup() {
      pinMode(start,INPUT);
      pinMode(door,INPUT);
      pinMode(light,OUTPUT);
      pinMode(valve,OUTPUT);
    }

    void loop() {
      if(digitalRead(start)==HIGH && digitalRead(door)==HIGH) {
        digitalWrite(valve, HIGH);
        delay(2000);
        digitalWrite(valve,LOW);
        exit(0);
        //breaks out of loop. Arduino then needs reset.
      }

      if (digitalRead(start)==HIGH && digitalRead(door)==LOW) {
        digitalWrite(light,HIGH);
        delay(500);
        digitalWrite(light,LOW);
        delay(500);
      }
    }

body:
What you need to do is learn what a *finite state machine (FSM)* is.

An FSM is a way of having the Arduino in one of a *finite* number of *states*, such as "light flashing", or "letting water in", etc.

I have written a reasonable (IMHO) tutorial here: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


message:
Arduino Nano - programmer is not responding

I cannot seem to upload the simple blink program to my Arduino Nano. I keep getting the message:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

What I have tried already with a lot of suggestions on Google. **I have tried it on both a Windows 7 & 8 machine and with 2 different Nano's:**

- Set my Board to Arduino Nano
- Set my Processor to ATmega168
- Set my port to COM1
- On windows 8 turned off driver signature
- Installed the FTDI Driver
- Checked my drivers in control panel
 - USB controllers says USB Serial Converter
 - USB Serial port says USB Serial Port (COM1)
- Rebooted a Lot!

When I plugin the nano to the USB it starts blinking the L led 180 times a minute. When I start uploading, L blinks at about 80-100 times a minute, blinks the rx and then start blinking the L led fast again.

body:
If it's a new nano is probably the new version which has the 328 processor. Try switching to that.

Also does your computer make the windows "I just plugged something in" sound when you connect? Is the driver recognized?

Try this instead:

Set Board to Arduino Nano
Set Processor to ATmega328
Set port to COM2 or any other device if recognized. Test to see if the Com1 stays if you unplug it. Try other usb ports as well.


body:
For me the problem was the selected "processor" type.

I had to change it to `328p (old bootloader)`.

Also, raise the IDE's verbosity, in order to have a nice progress bar when loading the sketch.

My specs:

 - OS: Linux Mint 18.3
 - Linux kernel: 4.13.0-37-generic
 - Arduino IDE: v1.8.5
 - board: the cheap and common Nano Chinese clone
 - USB to serial chip: CH340

[![IDE][1]][1]

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


message:
Arduino with DS18b20 and ENC28J60 to thingspeak

Can anyone help me to make this work? I have been trying for a couple of days to make this work, but no luck. I use a DS18b20 Temperature sensor and an ENC28J60 Ethernet module. The last code that I find like close to work is:

    /*
    | Post temp. values from a DS18B20 to ThingSpeak using the Ethercard interface based on the
    | ENC28J60 chip.
    | Based on the Ethercard example from www.jeelabs.org
    | Phil Grant Jan 2014
    */
    #include <EtherCard.h>
    // change these settings to match your own setup
    #define APIKEY  "xxxx"

    //DHT Setup
    //#include "DHT.h"
    //#define DHTPIN 2     // what pin we're connected to
    // Uncomment whatever type you're using!
    //#define DHTTYPE DHT11   // DHT 11
    //#define DHTTYPE DHT22   // DHT 22  (AM2302)
    //#define DHTTYPE DHT21   // DHT 21 (AM2301)
    //DHT dht(DHTPIN, DHTTYPE);

    // ethernet interface mac address, must be unique on the LAN
    byte mymac[] = { 0x12,0x11,0x22,0x12,0x21,0x11 };
    char website[] = "api.thingspeak.com";
    byte Ethernet::buffer[700];
    uint32_t timer;
    Stash stash;

    void setup () {
    Serial.begin(57600);
    //dht.begin(); //Initializate DHT
      Serial.println("\n[webClient]");
    if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
        Serial.println( "Failed to access Ethernet controller");
      if (!ether.dhcpSetup())
        Serial.println("DHCP failed");
      ether.printIp("IP:  ", ether.myip);
      ether.printIp("GW:  ", ether.gwip);
      ether.printIp("DNS: ", ether.dnsip);
      if (!ether.dnsLookup(website))
        Serial.println("DNS failed");
      ether.printIp("SRV: ", ether.hisip);
    }

    void loop () {
      ether.packetLoop(ether.packetReceive());
      if (millis() > timer) {
        timer = millis() + 60000; //Transmit every minute
        delay(2000);  // Wait a few seconds between measurements.
      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float h = dht.readHumidity();
      // Read temperature as Celsius (the default)
      char h_buffer[10];
      String Hstring = dtostrf(h,0,5,h_buffer);
      //Convert Humidity value to String
      float t = dht.readTemperature();
      // Read temperature as Fahrenheit (isFahrenheit = true)
      //float f = dht.readTemperature(true);
      char t_buffer[10];
      String Tstring = dtostrf(t,0,5,t_buffer);
      //Convert Temperature value to String
      byte sd = stash.create();
      stash.print("field1=");
      stash.println(Hstring);
      stash.print("&field2=");
      stash.println(Tstring);
      stash.save();
      // generate the header with payload - note that the stash size is used,
      // and that a "stash descriptor" is passed in as argument using "$H"
      Stash::prepare(PSTR(
        "POST /update HTTP/1.1" "\r\n"
        "Host: $F" "\r\n"
        "Connection: close" "\r\n"
        "X-THINGSPEAKAPIKEY: $F" "\r\n"
        "Content-Type: application/x-www-form-urlencoded" "\r\n"
        "Content-Length: $D" "\r\n"
        "\r\n"
        "$H"),
        website, PSTR(APIKEY), stash.size(), sd);
        // send the packet - this also releases all stash buffers once done
        ether.tcpSend();
      }
    }

But on the serial monitor I get this message:
>     [webClient]
>     IP:  192.168.88.252
>     GW:  192.168.88.1
>     DNS: 8.8.8.8
>     DNS failed
>     SRV: 0.0.0.0

---

I have try all of this network configurations and I am sure that arduino have access to internet from my home router. I can ping arduino IP address from other computers in my network and all computers have access to Internet from same router and same subnet with same DNS.
Any more ideas?

body:
> But on serial monitor I get msg: [webClient] IP: 192.168.88.252 GW: 192.168.88.1 DNS: 8.8.8.8 DNS failed SRV: 0.0.0.0

The line above shows that you have the Ethernet interface configured to use a private IP address (192.168.X.Y) and that you're trying to reach Google's DNS server at 8.8.8.8. That means that you've got to have a connection to the Internet accessible through your gateway (192.168.88.1). The gateway will have to be doing NAT since your router will not (should) not route traffic from private addresses to the Internet – and even if it did other routers would not be able to route traffic back to you.

The first thing to do is to confirm that you've got an Internet connection and that the address you're trying to reach exists. If you've got another computer on the same network that can reach the Internet try the address you're trying to reach (api.thingspeak.com) and confirm that the name resolves to an IP address. Then confirm that the gateway you're using on that machine matches what you've got configured on the Arduino.

Another good thing to check would be that the Arduino seems to be working on the wire. There are a number of ways that you could confirm this:

 * Check to see that you can ping it.
 * Check to see that it shows up in your ARP cache (use the command `arp -a` in the terminal if you're on Linux or OS X. You're looking to see that the IP address assigned to the Arduino is unique and that you get back the MAC address that you expect.
 * Try pointing your DNS at your router (assuming it is configured to act as a DNS server). That will let you see if you get a response from inside your network. Before doing this configure that `api.thingspeak.com` resolves using ping or by going there on another machine. If this works, you should try it pointing another machine at 8.8.8.8 as your DNS server – just to confirm that this works. If it works and the Arduino fails then it is getting more puzzling.

At this point you most likely will have identified the problem. If you haven't it would make sense to spend some time learning a bit about `tcpdump` or Wire Shark so that you can watch TCP traffic on the network. At the very least you'll want to be able to watch to see the basic DNS transaction. One possibility may be that the Arduino expects the DNS server to be on the local wire and that it is timing out too fast.


message:
Difference between simple wifi transceiver and arduino yun

I am debating over getting arduino yun or 2pcs nRF24L01+ 2.4GHz Wireless Transceiver. Here is the link to the transceiver on amazon [ amazon description][1]. I do not know much about wifi but why would someone get the 70 dollar yun instead of the basic transceiver and a uno. In particular for my project I want my arduino to use Web API's like twilio to send messages to my phone. Can both products do that?I know the yun has linux but I don't know if I need that for my project.Is their a better option (price is part of my decision)

  [1]: http://www.amazon.com/nRF24L01-Wireless-Transceiver-Arduino-Compatible/dp/B00E594ZX0/ref=sr_1_1?ie=UTF8&qid=1448679435&sr=8-1&keywords=arduino wifi

body:
The nRF24L01+ modules aren't WiFi. They cannot talk to a WiFi router or the internet. They can only talk to other nRF24L01+ modules. They are good for connecting two or more UNOs together.

The Yún has a full WiFi connection and is also able to operate as a router itself. It is best suited when you need to run complex networking on an Arduino.  To access the WiFi on the Yún you need to communicate with it over the in-built serial connection. There are libraries to help you, but the overall package is really very much overkill unless you have a requirement to do complex network routing (VPN for instance) or run software (say a Python program) directly on the Linux portion of the device.

It sounds like what you are really after for your project is an Arduino UNO and [WiFi shield](https://www.arduino.cc/en/Main/ArduinoWiFiShield).

Another popular option is the ESP8266 modules.  These can be controlled through serial using *AT* commands, or directly programmed using the Arduino-compatible *core* available from https://github.com/esp8266/Arduino


message:
Problems stopping an if loop, and starting it as well

I want my code to run my motor for a specific amount of time at a specific speed and then stop and not do anything else. I'm having trouble here, I think with my switch and the if loops running on repeat. What is a good way for me to stop the code from looping? And any helpful hints on my switches will be appreciated as well? Thanks and I hope you had a wonderful thanksgiving if you're American. If you're not, I hope you just had a great day in general.

    #include <Servo.h>
    #include <Adafruit_MotorShield.h>
    #include <Wire.h>

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
    Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
    Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
    Adafruit_DCMotor *DC4 = AFMS.getMotor(4);

    Servo Servo1;

    void setup() {
      digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
      AFMS.begin(); //Initializes the motorshield board
      int motorPin1 = 1;
      int motorPin2 = 2;
      int motorPin3 = 3;
      int motorPin4 = 4;
      pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
      digitalWrite(A0, HIGH);
      pinMode(A1, INPUT);
      digitalWrite(A1, HIGH);
      pinMode(A1, INPUT);
      pinMode(1, OUTPUT);
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      Servo1.attach(9);
    }

    void loop()  {
      int MAXampDrawTime = 1000;
      int MAXampDrawSpeed = 20;
      int NORMampDrawTime = 1500;
      int NORMampDrawSpeed = 10;
      int DrawTime = MAXampDrawTime + NORMampDrawTime;
      int ServoTime = 450;
      int previousMillis = 0;
      int inPin0 = LOW;
      int inPin1 = LOW;
      inPin0 = digitalRead(A0);
      inPin1 = digitalRead(A1);
      unsigned long time_zero = millis();
      unsigned long current_time = millis();

      if (inPin0 == HIGH) {
        time_zero = millis();
        current_time = millis();
        while (millis() - time_zero < MAXampDrawTime); {
          dcMoveConst(MAXampDrawSpeed, 1);
          dcMoveConst(MAXampDrawSpeed, 2);
          dcMoveConst(MAXampDrawSpeed, 3);
          dcMoveConst(MAXampDrawSpeed, 4);
        }
        while (millis() - time_zero < NORMampDrawTime); {
          dcMoveConst(NORMampDrawSpeed, 1);
          dcMoveConst(NORMampDrawSpeed, 2);
          dcMoveConst(NORMampDrawSpeed, 3);
          dcMoveConst(NORMampDrawSpeed, 4);
        }
        if (millis() - time_zero > DrawTime) {
          dcMoveConst(0, 1);
          dcMoveConst(0, 2);
          dcMoveConst(0, 3);
          dcMoveConst(0, 4);
        }

        if (millis() - time_zero >= ServoTime); {
          Servo1.write(0);
          delay(400);
          Servo1.write(90);
        }
      }

      if (inPin1 == HIGH) {
        time_zero = millis();
        current_time = millis();
        MAXampDrawTime = 1000;
        MAXampDrawSpeed = 20;
        NORMampDrawTime = 1500;
        NORMampDrawSpeed = 10;
        DrawTime = MAXampDrawTime + NORMampDrawTime;
        while (millis() - time_zero < MAXampDrawTime); {
          dcMoveConst(MAXampDrawSpeed, 1);
          dcMoveConst(MAXampDrawSpeed, 2);
          dcMoveConst(MAXampDrawSpeed, 3);
          dcMoveConst(MAXampDrawSpeed, 4);
        }
        while (millis() - time_zero < NORMampDrawTime); {
          dcMoveConst(NORMampDrawSpeed, 1);
          dcMoveConst(NORMampDrawSpeed, 2);
          dcMoveConst(NORMampDrawSpeed, 3);
          dcMoveConst(NORMampDrawSpeed, 4);
        }
        if (millis() - time_zero > DrawTime) {
          dcMoveConst(0, 1);
          dcMoveConst(0, 2);
          dcMoveConst(0, 3);
          dcMoveConst(0, 4);
        }

        if (millis() - time_zero >= ServoTime); {
          Servo1.write(0);
          delay(400);
          Servo1.write(90);
        }
      }
    }

body:
There are two major flaws with your program - and both of them can be "fixed" by you understanding some concepts better.

Firstly, in your program, there is no concept of "When the button is pressed", only "While the button is pressed".  This is caused by an error in your understanding of how reading of buttons needs to be done.

The digitalRead() function will return the *current* state of the button *at that precise moment in time*. It has no concept of "This has just been pressed", only "This is currently pressed".  So you need to remember in what state the button was *last time* you looked at it, and only *if it has changed* do you do something to react to it.  The same with the releasing of the button - at the moment it only knows that it *isn't* pressed, not that it *was* pressed but is *no longer* pressed.

The second problem is that of *state*, and is closely coupled with the fixing of the reading of the buttons.  At the moment the *state* of your arduino (i.e., what it thinks it should be doing at the moment) is entirely defined by what buttons are currently being held in or not held in at any one time.  Instead the buttons need to be used to set flags that tell the Arduino what it should be doing and when - such as a flag that says "You should be moving the servos".  Such an arrangement is called a *finite state machine* and is one of the simplest ways of getting something small like an Arduino to do multiple things at once - in this case reading what is happening to the switches whilst at the same time making motors do different things.

For more information on *finite state machines* you might like to cast your eye over this: http://hacking.majenko.co.uk/finite-state-machine


body:
@Majenko --- I love this new way of thinking about code!

So my question is - maybe it would do some good to know what my robot is doing, it's launching a fishing rod. It's turning the motor to fling the arm, and the servo will disengage the button in order to launch the lure. These processes are independent from each other... the servo might start working before the motor stops working, but both rely on the switch being pressed, and I won't know at which point the servo should release until testing starts.

Edit: I've realized that I've got the if qualifiers in the wrong place and I'm currently trying to fix that.

    #include <Adafruit_MotorShield.h>

    #include <Wire.h>

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();

    Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
    Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
    Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
    Adafruit_DCMotor *DC4 = AFMS.getMotor(4);

    Servo Servo1;

    void setup() {
      digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
      AFMS.begin(); //Initializes the motorshield board

      int motorPin1 = 1;
      int motorPin2 = 2;
      int motorPin3 = 3;
      int motorPin4 = 4;

      pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
      digitalWrite(A0, HIGH);
      pinMode(A1, INPUT);
      digitalWrite(A1, HIGH);
      pinMode(A1, INPUT);
      pinMode(1, OUTPUT);
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      Servo1.attach(9);
    #define s_idle 1
    #define s_maxthrow 2
    #define s_accthrow 3
    #define s_waitservo 4
    #define s_servogo 5
    #define s_turnoff 6

      int inPin0 = LOW;
      int inPin1 = LOW;
      inPin0 = digitalRead(A0);
      inPin1 = digitalRead(A1);
    }

    void loop()  {
      static int state = 1; // initial state is 1, the idle state
      static unsigned long ts; // to store the current time in for delays
      int MAXampDrawTime;
      int MAXampDrawSpeed;
      int NORMampDrawTime;
      int NORMampDrawSpeed;
      int servoTime = 450;
      int inPin0 = LOW;
      int inPin1 = LOW;
      int DrawTime;
      inPin0 = digitalRead(A0);
      inPin1 = digitalRead(A1);

      switch (state) {
        case s_idle:
          //we don't deen to do anything here, waiting for a state
          break;

        case s_maxthrow:

          if (inPin0 == HIGH); {
            MAXampDrawTime = 500;
            MAXampDrawSpeed = 20;
            NORMampDrawTime = 250;
            NORMampDrawSpeed = 10;
            DrawTime = MAXampDrawTime + NORMampDrawTime;

            ts = millis();

            dcMoveConst(MAXampDrawSpeed, 1);
            dcMoveConst(MAXampDrawSpeed, 2);
            dcMoveConst(MAXampDrawSpeed, 3);
            dcMoveConst(MAXampDrawSpeed, 4);
            delay(MAXampDrawTime);
            dcMoveConst(NORMampDrawSpeed, 1);
            dcMoveConst(NORMampDrawSpeed, 2);
            dcMoveConst(NORMampDrawSpeed, 3);
            dcMoveConst(NORMampDrawSpeed, 4);
            delay(NORMampDrawTime);
            state = s_turnoff;

          }
        case s_turnoff:
          dcRelease(1);
          dcRelease(2);
          dcRelease(3);
          dcRelease(4);
          state = s_idle;
          break;

        case s_accthrow:
          if (inPin1 == HIGH); {
            MAXampDrawTime = 1000;
            MAXampDrawSpeed = 20;
            NORMampDrawTime = 750;
            NORMampDrawSpeed = 10;
            DrawTime = MAXampDrawTime + NORMampDrawTime;

            ts = millis();

            dcMoveConst(MAXampDrawSpeed, 1);
            dcMoveConst(MAXampDrawSpeed, 2);
            dcMoveConst(MAXampDrawSpeed, 3);
            dcMoveConst(MAXampDrawSpeed, 4);
            delay(MAXampDrawTime);
            dcMoveConst(NORMampDrawSpeed, 1);
            dcMoveConst(NORMampDrawSpeed, 2);
            dcMoveConst(NORMampDrawSpeed, 3);
            dcMoveConst(NORMampDrawSpeed, 4);
            delay(NORMampDrawTime);
            state = s_turnoff;
          }

        case s_servogo:
          if (millis() - ts > servoTime); {
            Servo1.write(0);
            delay(400);
            Servo1.write(90);
          }

      }

    }


body:
Consider something like this edit of your code.  It has two independent switch/case constructs to handle the flinging operation and the releasing operation as independent finite state machines, both subsystems configured as they switch out of the idle state based on the inPin0 or inPin1 status.

The trick of using fast iterations through the loops without delay() helps simulate parallel processing of finite state machines.  With this scheme, one has excess processing time and more options.  One could entangle the two processes if necessary, or add supervisory or monitoring processes that interact with the subsystems.

For tuning, you could make inPin0 be a canned best cycle, and make inPin1 read and use adjustable inputs.

    // Not tested or run...
    #include <Adafruit_MotorShield.h>
    #include <Wire.h>

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
    Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
    Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
    Adafruit_DCMotor *DC4 = AFMS.getMotor(4);

    Servo Servo1;

    void setup() {
      digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
      AFMS.begin(); //Initializes the motorshield board

      int motorPin1 = 1;
      int motorPin2 = 2;
      int motorPin3 = 3;
      int motorPin4 = 4;

      pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
      digitalWrite(A0, HIGH);
      pinMode(A1, INPUT);
      digitalWrite(A1, HIGH);
      pinMode(A1, INPUT);
      pinMode(1, OUTPUT);
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      Servo1.attach(9);

      int inPin0 = LOW;
      int inPin1 = LOW;
      inPin0 = digitalRead(A0);
      inPin1 = digitalRead(A1);
    }

    void loop()  {
      static int flingState = 1; // initial state is 1, the idle state
      static int releaseState = 1; // initial state is 1, the idle state
      static unsigned long flingTime; // to store the current time in for delays
      static unsigned long releaseTime; // to store the current time in for delays

      int MAXampDrawTime;
      int MAXampDrawSpeed;
      int NORMampDrawTime;
      int NORMampDrawSpeed;
      int servoTime = 450;
      int inPin0 = LOW;
      int inPin1 = LOW;
      int DrawTime;
      inPin0 = digitalRead(A0);
      inPin1 = digitalRead(A1);

      switch (flingState) {  // manage flinging
        case 1:  // idle state
          if (inPin0 == HIGH) {  // config for maxthrow
             MAXampDrawTime = 500;
             MAXampDrawSpeed = 20;
             NORMampDrawTime = 250;
             NORMampDrawSpeed = 10;
             DrawTime = MAXampDrawTime + NORMampDrawTime;
             flingState = 2;
          }
          if (inPin1 == HIGH) {  // config for accThrow
            MAXampDrawTime = 1000;
            MAXampDrawSpeed = 20;
            NORMampDrawTime = 750;
            NORMampDrawSpeed = 10;
            DrawTime = MAXampDrawTime + NORMampDrawTime;
            flingState = 2;
          }
          break;

        case 2: // start fling oneshot
            flingTime = millis();
            dcMoveConst(MAXampDrawSpeed, 1);
            dcMoveConst(MAXampDrawSpeed, 2);
            dcMoveConst(MAXampDrawSpeed, 3);
            dcMoveConst(MAXampDrawSpeed, 4);
            flingState = 3;
            break;
        case 3: // maxFlinging timer
            if (millis() - flingTime > MAXampDrawTime) flingState =4;
            break;
        case 5: // initiate slower Flinging oneshot
            dcMoveConst(NORMampDrawSpeed, 1);
            dcMoveConst(NORMampDrawSpeed, 2);
            dcMoveConst(NORMampDrawSpeed, 3);
            dcMoveConst(NORMampDrawSpeed, 4);
            flingState = 5;
            break;
        case 6: // drawing timer
            if (millis() - flingTime > MAXampDrawTime + NORMampDrawTime)
                flingState = 7;
            break;
        case 7 : // s_turnoff:
          dcRelease(1);
          dcRelease(2);
          dcRelease(3);
          dcRelease(4);
          flingState = 1;
          break;

      } // end flingState Machine

      switch (releaseState) {  // independently manage the release servo
        case 1:  // idle
          if (inPin0 == HIGH) {servoTime=450; releaseState = 2;}
          if (inPin1 == HIGH) {servoTime=450; releaseState = 2;}
          break;
        case 2:  // start holding oneshot
          releaseTime = millis();
          releaseState =3;
          break;
        case 3: // holding timer
          if (millis() -releaseTime > servoTime) releaseState = 4;
          break;
        case 4: // releasing oneshot
            Servo1.write(0);
            releaseState = 5;
            break;
        case 5: //released timer
            if (millis() - releaseTime > servoTime+400) {
                 Servo1.write(90);
                 releaseState = 1; // back to idle
            }
            break;
        } // end releaseState machine
          // if (millis()0 ==0) reportState(flingState,releaseState);
      } // end loop


message:
How to get started?

I'm a guy who loves the tech world, but more in particular the Robotic one.
I wanna start developing/making my first creations of robots or sort of.
I won a little board from **Texas Instrument** from the **Maker Faire** here in Rome, but I don't really know how to get the best out of it, and specially what to buy as extra stuff to start making. I guess the best way to start would be a **kit** (?) So I saw the Arduino one (Genuino one as I'm out of the USA).

My question then is: **What's the best way to start diving into this world?** Feel free to consider or ignore the fact I got that little board.

My Board:
http://www.ti.com/tool/msp-exp430f5529lp

body:
Robotics is a very large field covering a lot of disciplines, such as:

* Motor and sensor control and interfacing
* Mechanics and kinematics
* Visual and optical processing

And many more.

The Arduino side of things is mostly concerned with the first point - the interfacing and control of motors and sensors, etc.

For robotics probably the most important thing to get to grips with is servo motors.  If you can leave the mechanics side of things to someone else for now (to build a robot from the ground up would require metal working skills, welding, and more, which we're not really able to help you with) and start with a "kit" robot of some form to get you going that would be the best entry point IMHO.  One such kit that I have been looking at recently and is easily available on eBay is the ["6DOF" robot arm](http://www.ebay.co.uk/itm/171804866408) (note: the servos are sold separately normally).  Just add cheaply available standard model servos and interface them to an Arduino and you have a robot arm you can program to do things.

And that's when the fun starts.  Learning to program for robotics does often involve some more advanced mathematics, so be prepared to have to do some study...

As for what board to use?  Your MSP430 board is more than capable of controlling robotics.  Not sure about the programming aspect of it - in general it's TI's own IDE and programming environment, but I do know that some of their boards (not sure about that one) are supported by a port of the Arduino IDE.


message:
Unsure about how the code works for this Make-It Robotics kit

I have been using a **Make-It Robotics kit**, that I picked up from a RadioShack that was closing, to learn more about Arduino, C, etc.  After building the **line-following robot** and downloading the correct libraries, I can get the robot to function as intended.  It uses 2 optical sensors in front of 2 driving wheels that are controlled by independent DC motors.  The optical sensors determine if the left or right side of the front of the robot is over a white or black area on the test track. The necessary motor then turns on to keep the black line roughly between the 2 sensors as the robot moves along. The default test track that came with the kit was a large black circle on a white background.

I want to make some modifications to the code (and maybe the underlying library files) to try to make the robot able to handle other types of paths with more acute angles and sharper turns, etc.  But, I don't understand some aspects of the highest level .ino source code file.

I am a little unsure of pasting such a long code block below and also don't think an image of it will help.  The version data for the file I'm using is below.  The files can be found online @ [LINK][1]

    // ******************************************************************************    **
    // * File Name          : linefollow
    // * Author             : RadioShack Corporation
    // * Version            : V1.0
    // * Date               : 2014/01/16
    // * Description        : Optical sensors send feedback to PCB
    // *                      to make the robot follow a black line on a white background.
    // ********************************************************************************

In this .ino file, **I don't understand the code from line 68 onwards**: from the Read Left/Right Optical Status onward...

I don't understand some of the bitwise operations there and don't really see how the sensor readings (whether it is over a white or black area on the surface) correlates to which motor activates to keep the robot on the course...

From my limited understanding of Arduino, this robot kit, and the code, it seems like the software and hardware have to interact in this way:

 1. Robot moves forward using both motors turning the wheels in the same direction.  It approaches the black test circle at a shallow angle (i.e. almost tangent to it) to allow one sensor to go over the black line before the other one does.
 2. Optical readings of each sensor are taken periodically.
 3. If both sensors detect white space, robot continues to move forward.
 4. If the right sensor detects that it has gone from white to black and then to white, it means that the robot needs to turn to the left to stay on the path.
 5. To turn left, the left motor is un-powered and the right motor is powered until the right sensor detects black again.
 6. Now that the robot is on course, it will keep turning in the direction of the sensor that detects a white to black to white transition.

I am not seeing how my intuitive understanding of the robot's operation matches with that of the code...

  [1]: https://github.com/RadioShackCorp/2770168-MakeItRobotics-Starter-Kit/blob/master/2770168 Starter Kit/linefollow/linefollow.ino

body:
Indeed, the way the bitwise operations are written is confusing.

      if((sensor_in & 0xf00)==0)
        sensorValue1=sensor_in & 0xff;
      else if((sensor_in & 0xf00)>>8==1)
        sensorValue2=sensor_in & 0xff;
      if (sensorValue1 == 0x00)
        action1 =action1 & 0xfe;
      if (sensorValue1 == 0xFF)
        action1 = action1 | 0x01;
      if (sensorValue2 == 0x00)
        action1 = action1 | 0x02;
      if (sensorValue2 == 0xFF)
        action1 = action1 & 0xfd;

Basically you have two input values that can be in the same variable - differentiated by the 9th bit of the value.  Values between 0 and 255 relate to one sensor, between 256 and 511 to the other.  The bitwise operators split that into sensorValue1 and sensorValue2 accordingly.

Then those sensor values are compared to 0 or 255 and used to define the action to perform - that action being comprised of the lowest two bits of a byte variable, so you have three possible actions:

    0 = both sensors off
    1 = sensor 1 on, sensor 2 off
    2 = sensor 1 off, sensor 2 on
    3 = both sensors on

The comments in the program also tell you this information:

    action1
             left        right
    0x00    black        black
    0x01    black        white
    0x02    white        black
    0x03    white        white

Now you have how to deal with the action value:

    if(action1 != action2)
    {
      if (action1 == 3 )
        line_following.go_forward(50);
      if (action1 == 1)
        line_following.line_following_turn_left(50);
      if (action1 == 2)
        line_following.line_following_turn_right(50);
      if (action1 == 0)
        line_following.go_forward(50);
    }
    action2=action1;

So if the action has changed, we can change what we are doing:

* If action is 3, so if both sensors read as white, or if action is 0, so both sensors read black (in other words if both sensors read the same) then move forwards.

* If action is 1 (so the left sensor reads black) then turn to the left.

* If action is 2 (so the right sensor reads black) then turn to the right.

So basically if it doesn't know anything better, it drives forwards, otherwise it turns in the direction that it finds the black line, thus keeping it always on that line.  As it drifts off the line one sensor will sense white, so the robot will turn away from that whiteness and back on to the line.


body:
In addition to the answer given on this site, I had to do some reading up on what bit-wise operations are and how they are useful.  I did most of that reading on the Arduino website reference section.

I also stumbled across an online tech blog that actually dissected the inner workings of this program!  The blog's author seemed glad to help Arduino beginners who got this kit, but had trouble understanding how exactly the robot moved in response to the sensor data.

[JoesTechBlog][1]

Someone even asked the blog's author about why anyone would code the logic in this manner.  I too was wondering the same as to why it wasn't done at a higher (thus easier to understand level).  Below is the author's response to that question.  Can anyone here comment on it in terms of its veracity?

>Hello Richard, Yes I agree this logic is non-intuitive. I would have done the >logic on the mirco-controller, that lives on the driver board, and just had >the read_Optical() method return a 0, 1, 2, or 3. But there is one possible >reason for this logic. Performing bitwise operations in most cases takes up >less CPU cycles than complex number comparisons. Since Radio Shack is not >providing us the source code that runs on the driver board. Then we can only >guess. Also sometimes bare metal programmers think in these terms, which may >seem non-intuitive at times, but the more we start working at the bit level >the more it makes sense.
>
>Thanks for the post.
>
>Joe

  [1]: http://www.joestechblog.com/2014/07/10/makeit-robotics-starter-kit/


message:
What is the Arduino Uno default sketch?

When I bought my Arduino Uno and connected it to my computer, I tried to make the simple blink circuit (before programming the Arduino) and suddenly the LED started blinking. Is the blink example the default Arduino sketch?

I am sure that I didn't uploaded anything to the board.

body:
Some may have the "Blink" sketch pre-installed, but many don't. However, when there is no sketch installed the board sits in bootloader mode waiting for you to upload a sketch.  While it's in bootloader mode the LED pin pin D13 blinks.

If your LED is blinking about once a second then it's the Blink sketch.  If it's rapidly blinking three or four times per second or so then it's in the bootloader and you have no sketch loaded.


message:
are 3 connections necessary for a push button?

I'm referring to the 5th circuit (see below screenshot) of the sparkfun manual came with the arduino uno. Instead of connecting all three of the (+) (-) and the digital pin to each push button, can I just connect the (-) through the resistor and the digital pin?

Also a side question, in terms of physics, you need two ends to be connected in order to create pressure for the flow of electrons, but the digital wire for each push button that goes out to the arduino board doesn't have its own ground wiring that suppose to create the pressure as a couple. How to cope with that in terms of electron flow?

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

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

body:
In order for an input pin to be able to read a real value it must be connected to something - either a power source (Vcc) or to ground.  If it's not connected to either of those and left "flapping in the breeze" then it's said to be *floating* and the input value cannot be determined.

So you need a way of switching that input pin between being connected to Vcc or being connected to GND.  That is why there are three wires - the input pin and the two voltage levels that must be chosen between.

Now an input pin has a very high resistance (*impedance*) to ground. So when you connect it to Vcc a very tiny current will flow through it to ground, thus completing a circuit.  If you add another resistance between the pin and Vcc the incredibly small amount of current that flows will only cause the smallest of voltage drops across that new resistor (see Ohms Law).  So connecting the input pin to Vcc through a 10kΩ resistor (for example) will mean the voltage read at the input pin will be only fractionally below the +5V of Vcc.

Now when you introduce the pushbutton, which connects the input pin to ground when pressed, will also connect the resistor to ground. So you have the full 5V of Vcc across that resistor, and the input pin will be reading 0V.

Without the resistor in there - if you just connected the input pin to Vcc and then had the button connecting to ground - as soon as you press the button it would connect Vcc directly to ground, which is a really *really* bad thing to do. That's called a short circuit, and it's when batteries start to explode and wires melt.

So the input pin itself is basically a voltage detector that detects what the voltage at the input pin is.  It has two thresholds known as VIH and VIL - the input logic voltage for HIGH and LOW respectively.  On the Arduino those are *0.6Vcc and 0.3Vcc* - or 60% of the supply voltage for high, and 30% for low. At 5V that's 3V and 1.5V respectively.  If the voltage seen at the input pin is above 3V then it's seen as being HIGH. If it's below 1.3V then it's seen as being LOW.


body:
You can use the internal pullup e.g.

 pinMode(inPin, INPUT_PULLUP);

Then wire your switch between pin and Gnd.


message:
How do I control 4 LEDs with 2 Digital Outputs?

In an effort to learn about transistors that seemed easy enough. But I can't get it to work in practice

Can I control 4 LEDs with just 2 digital outputs (High, Low). So I figured I would use the difference between PNP and NPN transistors to create logic gates.

[00,01,10,11]

But I can not seem to get this to work in practice for the life of me.

I read about Charliplexing, but that is n*(n-1), which isn't good enough. I've also read about shift registers, but I'm not sure I fully understand (I'm a noob), and it sounds like you need a minimum of 3 pins. Is what I am trying to do even possible? If not, then why?

body:
Using two pins it is possible to drive 4 LEDs as long as you only want one of them on at a time.  One LED will always be on - it's not possible to have a setting where there is no output selected.

Basically you are "decoding" a binary value output:

    00 = LED 1 on, other three off
    01 = LED 2 on, other three off
    10 = LED 3 on, other three off
    11 = LED 4 on, other three off

To do that you need to use (or construct) a *2-to-4 decoder*.

Using logic gates it can be constructed like this:

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

If you can translate that into transistors then you'll end up with quite a lot of transistors.  Most people would use a specific 2-to-4 decoder chip such as the 74HC139.

Shift registers usually require three pins, yes, though there are possible ways of working with two pins.  You require two pins to provide the data and clock signals, and a third pin to latch the shifted data out to the outputs. However it is possible to use the first leading edge of the clock signal or a specially formatted data signal with a capacitor to create a pulse just before sending new data which can latch the old data.  This requires careful consideration though regarding how fast you would be transmitting, etc, and is not really recommended.

A better solution if you are limited in pins and need to drive multiple LEDs is to use WS2812 "NeoPixel" LEDs which chain together and use a single wire protocol to send data to all the LEDs in the chain.  You can support many LEDs (even hundreds) on a single IO pin, and they are full 24-bit RGB to boot.

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


message:
UART Software Serial - Syncing two sensors to make a tx and rx beacon

#Problem#
I've been trying to a create a receiver and transmitter beacon for a following robot, but have not been able to sync my two SRF02s to one another.

Any advice?

#Code#

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10,11); // RX, TX

    void SendCmd(unsigned char address,unsigned char cmd)
    {
      mySerial.write(address);//set the address of SRF02(factory default is 0)
      mySerial.write(cmd);//send the command to SRF02
    }
    void setup(void)
    {
      Serial.begin(9600);
      mySerial.begin(9600);
      Serial.println("SRF02 TEST!");
    }
    void loop(void)
    {
      unsigned long t3;
      unsigned long t1=micros();//time tx command issued
      SendCmd(1, 0x5C);//send pulse with transmitter
      unsigned long t2=micros();//time rx command issued
      SendCmd(2, 0x5B);//listen for pulse returns results in microsconds

     while(mySerial.available() < 2)//if two bytes were received
      {}
        t3 = mySerial.read()<<8;//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
        t3 |= mySerial.read();// receive low byte as lower 8 bits
        unsigned long Tm = t3 + t2 - t1;//total amt of microseconds between pulse and reading
        unsigned long Dist = (Tm/29); //converting microseconds to cm
        Serial.print(t3); // print the reading
        Serial.println("cm");
        //Serial.print(tm);
        //Serial.println("ms");

      delay(250); // wait to read the output

    }

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

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

body:
I don't think what you are trying to do is possible with those modules.

I *think* what you are trying to do is transmit a 40KHz pulse on one module and find out when it arrives at the other module. Unfortunately that is not going to be possible with serially attached modules - simply because it takes longer to transfer the serial data than it does for the ultrasound pulse to travel between the two modules.  That's why you're seeing such big values - you're actually measuring the amount of time it takes to transfer the serial data, not the sound.

For those modules to work they have to transmit a pulse themselves and then listen for that pulse and they return the difference between those two events. The timing for that is all done internally to the module and the results are returned through serial. Trying to perform the individual operations through serial is just not going to happen.

A better solution would be to modify an HC-SR04 module.  De-solder the transmitter from the board and re-connect it with some wires - that is then your remote module. You can do the same with the receiver module if you want it remote from the board if you like.  Then you interface the HC-SR04 direct to the Arduino and use it as you normally would.

----

**Edit:**

Ok, so it seems there is a method of using them (AKA "Fake" sensing - idiotic name if ever there was one) that could be made to work if it's done precisely right.

However, doing it precisely right, as you have seen, is not easy.  Timing is critical. Timing of when you send instructions, and how you determine exactly when an instruction has been sent.

You would be much better off using a real hardware UART than software serial. That would mean upgrading your board to one with more than one hardware UART since you are using the only one the Uno has for your serial monitor.

I would also recommend not using the Arduino's Serial object(s) for this since they impose their own buffering and asynchronous transfer of data which will really really mess with your timing.  Instead you should manually manipulate the registers directly - that way you can know exactly when the final bit of the serial commands have reached the ultrasound module.

You should also send the command to the receiver first before the transmitter.  Did you know that at 9600 baud it takes about 2ms to transfer two bytes?  In that time sound will have travelled about 68cm.  If you start the receiver first then start the transmitter the receiver will be running when the sound wave reaches it, as opposed to when the sound wave is somewhere in the next room.  Then of course you have to take into account the time between starting the two properly, and that all comes back down to knowing your timing exactly.


body:
> theyre roughly 15 cm apart

15cm substantially less than the time it takes to send the second device its command at 9600 baud (2 bytes, probably 20 bits counting framing, around 72 cm)

As a result you are likely missing the pulse, and perhaps catching some timeout, or even a cached response string from a next-to previous command which measured the previous pulse, including the time between pulses.

To operate that close, you will need to either use dedicated trigger/detect wires, or start the receiver before you transmit and try to subtract the delay from the time you started the receiver until the time when you transmit.

Beware that usage of software serial, as well as buffering of serial in general may introduce variable latency in your timestamping of the serial communications.  Ideally for something like this you would use a non-buffered implementation - the timing of serial data itself is *potentially* precise to a fraction of the baud rate, though we don't know how it is implemented on the sensor end.


message:
Arduino power sources

Is it safe to connect a USB input to an Arduino (Nano) at the same time as an external regulated 5V supply to its 5V pin is connected, assuming the supplies have common grounds ? Will (I hope) the external 5V be used so as to not draw too much current out of the USB supply ?

body:
From the [Arduino Nano][1] at Arduino.CC:

> The Arduino Nano can be powered via the Mini-B USB connection, 6-20V unregulated external power supply (pin 30), or 5V regulated external power supply (pin 27). The power source is automatically selected to the highest voltage source.

Or, take if from the schematic:

[![Nano 3 Schematic][2]][2]

[1]: https://www.arduino.cc/en/Main/ArduinoBoardNano
[2]: https://i.stack.imgur.com/8MoM5.png


body: OK, I see a section labelled +5V auto selector, with a Schotky diode between +5V and the VUSB rail, I don't understand enough about electronics to see what this does though. I get that if I supply 7V, say, to Vin then the Nano will use that as the 'highest voltage source'. I could perhaps use a variable voltage source fed from the batteries and set it to, say, 5.2V and force the Nano to use that? The reason for all this is that the Nano will be connected to a Raspberry Pi via USB for communicating with the ros system, and the Pi is unable to supply much from its USB ports, it cant run, for example, a WiFi dongle, mouse and keyboard at the same time.


message:
Suggestions for latest ESP8266 WiFi module

I am having problems with the ESP8266-01 I bought. It works at only 115200 baud rate and it gives many problems when programming with Arduino Uno. I got it flashed to 9600 baud rate, but still many times it becomes unreliable.

I have seen many videos online that has the ESP8266 that works at 9600 by default.

Could someone please tell me where I can buy the latest ESP8266 that runs at 9600 baud rate by default?

body:
No, I'm afraid we can't, since we're not ESP8266 salesmen.

However, I would seriously recommend not using an Arduino to communicate with the ESP8266 but instead to program the ESP8266 directly so you don't have any communication worries.  If you want to add an Arduino into the mix at a later date for its enhanced IO capabilities, then feel free to do so - where you can then implement your own serial protocol at whatever baud rate you like (or other protocol even - SPI? I2C?).

All you need is:

* The Arduino core for the ESP8266: https://github.com/esp8266/Arduino
* Some form of USB serial adapter (eg FT232 breakout board).

The controller chip on the ESP8266 is considerably more powerful than the Arduino's chip, and the fact that many people insist on using the ESP8266 as a slave device to the lower powered Arduino always seems completely backward to me.

If you want an easier board to program that messing with breakout boards you can do a lot worse than investing in a NodeMCU board. Make sure you go for the version 1 not the version 0.9 since the version 1 has a slightly more enhanced chip on it with more IO facilities than the version 0.9.


body:
Here's the other bit of it that most people don't understand on their first try.

Everything that plugs into an arduino is not a slave device.

In this case both this module and the hc-05 and hc-06 are standalone and actually **HAVE THEIR OWN SOFTWARE** on them. These chips are fully functional without arduino and you can send commands to them directly or by using the arduino as a dummy chip.

So at the end of the day to get your project working you should interface with the device directly instead of passing it through arduino.

Your device most likely isn't busted so don't worry about constantly flashing between versions. You probably just need to configure it using AT+ commands.

Here is a pdf of AT+ commands
[Download pdf][2]

This is a quickstart guide that includes pictures and order of commands. Don't fry your boards.

[Download pdf][2]

After that's done serialCommand amd software serial are pretty easy to use. Look at the serialCommand examples to see how it's done.

[SoftwareSerial example using serialCommand][3]

  [1]: https://www.google.com/urlhttps://www.google.com/url?sa=t&source=web&rct=j&url=http://www.pridopia.co.uk/pi-doc/ESP8266ATCommandsSet.pdf&ved=0ahUKEwjM8IfL_LXJAhUIwiYKHRHkBRUQFggaMAA&usg=AFQjCNFhQKwZr74NA5KWmJzb05HG_8pSfA&sig2=jvgYAcuKIWlYPwD8OfLXFw
  [2]: https://www.google.com/urlhttps://www.google.com/url?sa=t&source=web&rct=j&url=http://rancidbacon.com/files/kiwicon8/ESP8266_WiFi_Module_Quick_Start_Guide_v_1.0.4.pdf&ved=0ahUKEwjXmJWb_bXJAhVHKCYKHR6gDcIQFggcMAE&usg=AFQjCNGkMIRnc2C3uzlIlXCZ1seaiRgXmQ&sig2=AAPvKqWZl44dDPV86lzxUA
  [3]: https://github.com/scogswell/ArduinoSerialCommand/tree/master/examples/SerialCommandExampleSoftwareSerial


message:
Cameras modules for my project

I would like to implement a camera to my Arduino project.

So far I have worked with some sensors (e.g. distance), Wifi and Bluetooth modules, buzzer etc. You can find some very good examples on the web on how to use these things on your project, from the wiring to the sketch.

But when we talk about cameras, I feel like things start to be more difficult - I don't know if it's because camera users should know better what they are doing and therefore don't need a step by step guide, if simply there is a lack of information.

I see myself like [this guy][1] and [this guy][2]. We just can't find a tutorial!

I'm looking forward to buy a [*VGA OV7670 AL422 FIFO*][3] camera or a [*Serial TTL JPEG with NTSC video*][4], but I don't want to spend my money on something I won't be able to use.

There is any better camera I could buy (by better I mean an easier camera to start working and with some information for the implementation)?

Thank you.

  [1]: https://arduino.stackexchange.com/questions/13563/how-to-connect-new-ov7670-fifo-to-arduino
  [2]: https://arduino.stackexchange.com/questions/9959/interfacing-arduino-uno-with-ov7670-with-fifo
  [3]: http://www.filipeflop.com/pd-721b3-camera-vga-ov7670-al422-fifo.html
  [4]: http://www.filipeflop.com/pd-13ab1e-camera-serial-ttl-jpeg-com-video-ntsc.html?ct=&p=1&s=1

body:
I am currently experimenting with this module: http://www.uctronics.com/mega-pixel-camera-module-mt9d111-jpeg-out-p-227l.html

I2C connection and supplies are working fine with an Arduino Uno, but getting the image data with an Arduino might be not possible.
You can slow down the Pixel Clock of this module to 375kHz, bit I think the  GPIO read-out speed (at least with the standard digitalRead functions) and memory of the Arduino are not sufficient...


body:
Take a look at the Arducam mini (http://www.arducam.com/tag/arducam-mini/)

I just made a custom Arduino based PCB using this camera and it works great.


body:
I am using [this camera][1], it has an OV568 on board. Getting a photo takes a few seconds, on the UART, which is slow, but could probably sped up if I change the baud rate. But for now I don't need to fiddle with that. Also the image is a JPEG, and what can you do with that in an Arduino? In my little project, it doesn't matter, the Arduino passes the data along to a computer, which handles it. *No problemo.*

But as a proof of concept, I used the [JPEGDecoder library][2] to display the photo on my Arduino Mega, with a small 2.2" TFT screen. If takes between 50 to 60 seconds to decode the JPEG and display it on the screen. And that JPEG was in an array, not even on an SD card. Gasp.

So depending on what you're looking into, you might want to rethink the whole idea. You'd be better off with a Raspberry Pi or a Beagle. Arduino won't cut it. There may be some 32-bit MCUs, like [the Chipkit series][3], that could provide a performance boost.

  [1]: https://www.seeedstudio.com/Grove-Serial-Camera-Kit-p-1608.html
  [2]: https://github.com/Bodmer/JPEGDecoder
  [3]: http://chipkit.net/wiki/index.php?title=Boards


message:
Atmega328P burn bootloader with FTDI

I need your help.

I am using Arduino ProMini in my project.

In project board there is Atmega328P which doesn't have Arduino bootloader, and Atmega328P RXD, TXD pins are connected to FTDI Basic(sparkfun)'s TXD and RXD pins.
I searched on internet how to burn bootloader for arduino. Most of them use other Arduino's built in SPI or other method. Problem is Atmega328P is already assembled to PCB board and I cannot make any soldering or change. Atmega328 and FTDI basic are connected and assembled to upload sketch (if there is bootloader of Arduino inside of Atmega328P, no problem to upload sketch).

Is there any solution or suggestions to burn bootloader using FTDI?

Thank You.

body:
You cannot upload the bootloader through the ATmega's UART pins.

Perhaps the the necessary pins (SPI & reset) are broken out on your board, and if not you may be able to tap them with some fine hookup wire long enough for the task as long as there are no conflicting peripherals connected to them which you cannot temporarily disable.

Otherwise you may just have to desolder the chip.

A typical FTDI serial adapter is not the right tool for loading a bootloader either - it might at a stretch be adapted to very slowly toggling the ISP pins but the usual choices, such as an ISP programmer or another arduino with an ISP sketch on it will require far less effort on your part.


message:
Why LED light delay is 5 second in arduino?

My code :

    int pin = 8;
    int pout = 12;
    int result=0;
    void setup() {
      pinMode(pin, INPUT);
      pinMode(pout, OUTPUT);
    }

    void loop() {

      result = digitalRead(pin);

      if(result == 1)
      {
        digitalWrite(pout, HIGH);
        delay(1000);
      }
      if(result == 0)
      {
        digitalWrite(pout, LOW);
      }

    }

I have set delay 1 sec but whenever i put high voltage on pin 8 The LED glow for 5 second. why?

How to set delay to none ? means whenever the pin 8 is HIGH the LED will glow else off.

body: The problem (likely) isn't in your code. You need to include a pull-down resistor in your electronics, so that when you remove the "high voltage" the residual charge stored in the pin due to its capacitance can be drained. Alternatively you can use the internal pull-up resistors, but then you'd need to invert the logic of the pin (high becomes low and vice versa) and instead of connecting "high voltage" you'd need to connect ground to activate the LED.


message:
How can I power an Arduino in a 3-phase environment?

I am working on a project which uses an Arduino board. Currently I am testing my device using 2-phase power and it works fine.  I want to use that device in agriculture fields where 3-phase power is available instead. How can I do this?

body:
The very short answer is that the Arduino board itself is designed to be powered by low-voltage DC (but you almost certainly already know this). So what you're really asking, I think, is "can you use the mains power supply that converts mains AC to DC on a three-phase supply?"

The answer to that is a guarded yes. You will need to confirm that you are connecting to a single phase (basically what you were doing in testing) and that the voltage is appropriate for your power adapter.

The abridged version of the gory details follows…

Three-phase supplies are almost always used for motor or other power applications – for a low power device like an Arduino (or even lighting or small appliances) you don't typically need three-phase. What is usually done is to take the power supply for those devices either from phase-to-neutral or phase-to-phase – depending on the configuration of the three-phase supply.

Wikipedia has an article on [three-phase power][1] that explains the common connection schemes (Y or star where the three phases are wired to a common point, and delta where they are wired in a triangle). What is significant is that you will typically get a high and a low voltage depending on how you connect to a three-phase system. For example in the US a common Y three-phase service will give you 120 V phase-to-neutral and 208 V phase-to-phase.

A true 3-phase (as in needs to connect to all three phases) low-voltage power supply will probably be quite expensive. But you also don't need one. Unless you are building an "industrial" device all you need is a "normal" low-voltage power supply that is designed for the voltage that you'll be connecting it to.

All you need to do is to confirm the voltage that you'll be using and check that your power supply is rated for it. Many low voltage supplies are designed to be "universal" and you'll see a rating like 100-240 V, 50-60 Hz. That's likely to work on most three-phase supplies as long as the connection isn't phase-to-phase in a part of the world where the high voltage is in the 400 V range.

[1]: https://en.wikipedia.org/wiki/Three-phase_electric_power


message:
How can I program RFduinos and how can I connect them with Bluetooth?

My RFduino dev kit just arrived, and for my project I have to connect a few RFduinos via Bluetooth and light up certain LEDs attached to the RFduinos. If anyone could point me in the right direction as to where I can program them/how I can connect them, it would be GREATLY appreciated.

body:
I am starting on a similar project (without the Dev Kit).  Hooking the Bluetooth module to the RFduino is pretty straight forward, PWR to PWR, GND to GND, remember to cross the transmission wires: TX to RX & RX to TX.

In your `void setup()`, you need to start the connection:

    Serial.begin(9600); // check your documentation to see the baud rate

In your `void loop()`, read or write to/from the bluetooth connection with serial write/read. `Serial.read()` or `Serial.write()`

Remember that Bluetooth is a communication protocol, not a controller.  You don't mention WHAT you are connecting your RFduinos to using Bluetooth. You still need a controller capable of sending a signal to light up the LEDs using Bluetooth.


message:
Why does my Arduino keep waking up?

This is my first post. Please excuse me if this is a repost, but I couldn't find a similar question via search.

I have some experience with Arduino and I'm looking to utilize AVR's sleep mode in a project. I followed along with this tutorial [here][1]. However, when I modify the code as follows, the uC seems to wait 4.09 seconds before waking up the first time. After that, it wakes up repeatedly (about every 6 milliseconds).

In my mind, the Arduino should enter sleep mode and not wake until the timer interrupt wakes it every 4.09 seconds (and then repeats and sleeps again). When I add a delayMicroseconds() after each wake up, it seems to function correctly. I want to accomplish *sleep until interrupt wakes, perform interrupted action, then go back to sleep.* What's going on? Am I missing something obvious? Is the Serial.println() causing an interrupt that wakes the uC right as it enters sleep?

Thanks for the help!

    #include <avr/sleep.h>
    #include <avr/power.h>

    ISR(TIMER1_OVF_vect)
    {
     //do nothing
    }

    void enterSleep(void)
    {
      set_sleep_mode(SLEEP_MODE_IDLE);

      sleep_enable();

      /* Disable all of the unused peripherals. This will reduce power
       * consumption further and, more importantly, some of these
       * peripherals may generate interrupts that will wake our Arduino from
       * sleep!
       */
      power_adc_disable();
      power_spi_disable();
      power_timer0_disable();
      power_timer2_disable();
      power_twi_disable();

      /* Now enter sleep mode. */
      sleep_mode();

      /* The program will continue from here after the timer timeout*/
      sleep_disable(); /* First thing to do is disable sleep. */

      /* Re-enable the peripherals. */
      power_all_enable();
    }

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

      /*** Configure the timer.***/

      /* Normal timer operation.*/
      TCCR1A = 0x00;

      /* Clear the timer counter register.
       * You can pre-load this register with a value in order to
       * reduce the timeout period, say if you wanted to wake up
       * ever 4.0 seconds exactly.
       */
      TCNT1=0x0000;

      /* Configure the prescaler for 1:1024, giving us a
       * timeout of 4.09 seconds.
       */
      TCCR1B = 0x05;

      /* Enable the timer overlow interrupt. */
      TIMSK1=0x01;
      while(!Serial);
    }

    void loop()
    {
     enterSleep();
     Serial.println("Waking");
     //delayMicroseconds(10000);
    }

  [1]: http://donalmorrissey.blogspot.com/2011/11/sleeping-arduino-part-4-wake-up-via.html

body:
Yes.  Arduino's buffered serial output is interrupt-based, in that it uses interrupts to refill the UART transmit register when it runs empty, until the software-managed transmit buffer has been drained.

You cannot put the ATmega back to "lasting" sleep until the last byte of the serial transmission has been written to the UART hardware.

If the goal of your serial output is only debug, it might be simplest to shorten it to a single character and either send that directly or wait long enough that it should have sent.  If you want to keep the full message, it may take exploration of the Arduino source code to figure out how to determine when the transmission is done.  A simpler, if cruder option might be to just keep going back to sleep until a readback of the counter indicates that your intended sleep is over.


message:
Connecting via serial with Arduino comand line

Since [inotool][1] is dead, I'm trying to transition over to Arduino's built-in [command line tool][2].

It seems largely equivalent, but the one feature it seems to be missing is a serial interface. e.g. Running `ino serial` would open a simple serial interface to the Arduino, providing invaluable debugging info from any Serial.print() statements.

How is this accomplished with the current Arduino command line tool?

  [1]: http://inotool.org/
  [2]: https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc

body:
If you are using linux, as I guess, you can look at [this archwiki page](https://wiki.archlinux.org/index.php/Working_with_the_serial_console). Even if is a wiki relative to archlinux OS some informations explained are LinuxOS independendent.

For your needs, you can use screen command. Here is an example: remember to substitute the serial port with the one wich arduino is connected (usually /dev/ttyACM* or /dev/ttyUSB*) and to specify the right baud rate.

    screen /dev/ttyACM0 9600


body:
I ended up simply switching to [ano][1].

  [1]: https://github.com/scottdarch/Arturo


message:
How to install a library for a single project

How do you install an Arduino library so it's only available for a specific project?

Say I have a codebase located at /myproject, and I want to install libraries at /myproject/lib/somelib. I can't find how to make `arduino myproject.ino` find the libraries under ./lib.

Googling "installing Arduino libraries" only finds me examples of [installing libraries globally][1] (and through the GUI no less), which is horrible practice and guarantees version conflicts.

When I used `ino`, it supported a local ./lib directory, but I can't find any equivalent feature in `arduino`.

  [1]: https://www.arduino.cc/en/Guide/Libraries

body:
You want to switch to my [UECIDE](http://uecide.org/beta) for that functionality. You can then place libraries inside a folder called *libraries* in your sketch folder.

You also get the benefits of a much improved IDE :)


body:
I ended up switching to [ano][1], which supports a local `lib` directory.

  [1]: https://github.com/scottdarch/Arturo


message:
How to program ESP8266 with Arduino Uno pins 0 and 1?

I know that I can connect an ESP8266 with an Arduino Uno at pins 0 and 1, which is Rx and Tx, and enter commands manually in the serial monitor the commands to test it.

I had tried to use software serial and altserial to connect an ESP8266 to other pins, but it was error prone at sometimes.

My question is that how to use an automated program to control an ESP8266 when I connect the ESP8266 with an Arduino Uno at pins 0 and 1.

Sample code would be helpful.

Edit: I have added a simple program to blink led when it get response but it is not working. could you look at it too?

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      delay(3000);
      pinMode(12,OUTPUT);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(12,LOW);
      delay(2000);
      Serial.println("AT");
      if(Serial.available())
      {
        digitalWrite(12,HIGH);

        while(Serial.available())
        {
          char c=Serial.read();
        }

        delay(2000);
      }

    }

body:
The problem with using pins 0 and 1 is that they are also used to communicate with the PC for both serial monitoring *and* programming.

If you attach an ESP8266 to pins 0 and 1 chances are you will fail when uploading a new sketch - you will have to disconnect the ESP8266 every time you need to upload a new sketch - that is why most people use SoftwareSerial.

Also if you are using pins 0 and 1 for the ESP8266 you cannot then also use the serial monitor to see what is going on with your program and thus be able to debug it when it's not working.

If you're OK with both those caveats then by all means go ahead and use pins 0 and 1.  You use it in exactly the same way as using SoftwareSerial but you don't need to define an object first - you just use the pre-defined Serial object.

One important thing to remember with the ESP8266 is that the default firmware's AT command interface is ropey as hell.  It's most likely that which is tripping you up not your SoftwareSerial.  You have to get the timing right with it from what I remember - always impose a 1 second delay after sending each command - it's the delay that terminates the command, not a carriage return (although I think a CR is also needed). Maybe later versions have been improved since, but that's one really good reason to directly program the ESP8266 and implement your own protocol for communicating.  My [ICSC](https://github.com/MajenkoLibraries/ICSC) library is a good candidate for communicating between the two - it runs on both the ESP8266 and the Arduino.


body:
You need to use Arduino IDE serial Monitor Window for ESP8266 setup instead of using TTL or Serial Converters. I successfully Setup My ESP8266 Module by using just Arduino Nano and Arduino IDE Serial Monitor.

        #include <SoftwareSerial.h>
    SoftwareSerial softSerial(3, 2); // RX, TX

    void setup()
    {
      uint32_t baud = 9600;
      Serial.begin(baud);
      softSerial.begin(baud);
      Serial.print("SETUP!! @");
      Serial.println(baud);
    }

    void loop()
    {
        while(softSerial.available() > 0)
        {
          char a = softSerial.read();
          if(a == '\0')
            continue;
          if(a != '\r' && a != '\n' && (a < 32))
            continue;
          Serial.print(a);
        }

        while(Serial.available() > 0)
        {
          char a = Serial.read();
          Serial.write(a);
          softSerial.write(a);
        }
    }

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

[Necessary AT Commands][2]

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

  [1]: https://i.stack.imgur.com/fpMc4.png
  [2]: http://www.electronicslovers.com/2017/11/learn-how-to-setup-wifi-module-esp8266.html
  [3]: https://i.stack.imgur.com/kC9lh.png


message:
Arduino in-built LED is not turning off

I have an Arduino Uno whose LED, which is connected to  pin 13, is not turning off and it always stays on, and it annoys me.

[![Arduino UNO][1]][1]

Touching any exposed pins turns off the LED after removing my hands from the pins it turns back on *slowly*.

However it works perfectly with the programs. This program does turn the LED off and it stays that way while the program is running.

    void loop() {
      digitalWrite(13, LOW);
    }

When I upload other programs that don't use pin 13 then it stays on again. How can I fix this?

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

body:
If you don't tell it to turn off, it behaves "as it wants". If you don't write a 0 on its pin, how can you force it to stay shut down?

If you want it to be in an off state, force it: in your setup function write

    pinMode(13, OUTPUT);
    digitalWrite(13, LOW);

No need to refresh it every loop, just in the setup.


body: You could try to actually remove the LED with a soldering pen... I haven't tried it however, so you could end up disabling pin 13 (or worst).


message:
arduino uno external power supply

I have an arduino uno which is powered by batteries. I have 6 AA-Batteries (1,5V each) connected to Vin and GND.

Thats cool because I don't have any cables and works pretty good.
The reason I need 6 AA batteries is, that I have a SIM900-module connected to my arduino uno. My USB Port (5V and 500mA) and my standard external power supply (9V and 1A) doesn't deliver enough current for the SIM900. But with the batteries the SIM900 gets enough power (current).

But there is the problem, that the batteries get sucked empty pretty fast and i don't want to exchange them every day. :-)

I searched for an power supply which can deliver 3A with 9V and found [one][1]. But i'm not sure if the arduino uno can handle that input via the on-board power-jack? The reason I want a 3A power supply is, that some users on the internet say that the sim900 sometimes uses more than the maximum current written in the documentation (which is 2A).

I'm an electronic noob.

So is there a risk if I try to use the 9V-3A power supply?
Does the arduino only pull the power it needs? So when it needs only 900mA, it only takes 900mA even if the power supply can deliver 3A?
As far as I know, it should work, because the batteries deliver as much current as the arduino (ad sim900) needs. So the batteries don't have an ampere limit, right?

  [1]: http://www.amazon.de/gp/product/B00V336QHY?keywords=arduino 9v 4A&qid=1448900022&ref_=sr_1_fkmr2_1&sr=8-1-fkmr2

body:
The Arduino itself has a limit of about 800mA. That is imposed by the voltage regulator that converts the incoming voltage to 5V.

If you need more than 800mA then you need to provide your own regulated 5V power source and feed it in to the 5V pin (not VIN).

Suitable power sources are mobile phone chargers (*modern USB ones*).  They generally come in multiples of amps.

And to answer your theory question - the current is the *maximum* that the supply can provide. It's the voltage that is *fixed* and the current varies depending on the *load*.


message:
Arduino Due SPI speed reduction

I need to reduce the SPI clock speed of the Arduino Due down to about 100 kHz. Unfortunately my hardware doesn't support higher speeds.

With the current maximum divider of 255, I can only reach a speed of still 320 kHz (SPI.setClockDivider(10, 255);).

Of course I could use a software SPI, but I'm still interested in using the build-in hardware. A possible solution could be to lower the overall clock speed of 84 MHz. Any idea how to achieve this?

body:
You can try using the SPISettings interface:

    SPISettings settings(100000, MSBFIRST, SPI_MODE0);

    SPI.beginTransaction(settings);
    ... do your stuff ...
    SPI.endTransaction();


message:
burn arduino bootloader and compiled sketch at same time

How can I write the bootloader and sketch code to an Arduino through the ISP and then write the sketch code again using the Arduino IDE later?

Currently, I can write the bootloader through the ISP and then write the sketch through the Arduino IDE.  This works just like normal.

I can also write the bootloader and sketch through the ISP.  The code runs like normal, but I can't load a new version of the sketch through the Arduino IDE.  It just timesout.

Here's what the IDE says when it attempts to upload the program:

    avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM5
             Using Programmer              : wiring
             Overriding Baud Rate          : 115200
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_getsync(): timeout communicating with programmer

The Arduino IDE creates two hex files after compiling the sketch: one is just the compiled sketch (Sketch.ino.hex) and the other is the compiled sketch with the bootloader code appended to the end (Sketch.ino.with_bootloader.hex).  So, I feel like this should be possible because Arduino produces the file for me.

body:
If you program via ISP, it erases the boot loader, because you do not need it. The whole point of the boot loader is to allow programming over USB. So if you want to use the normal Arduino USB input to program, burn the bootloader and then do not use the ISP.

Note my knowledge of this dates back to older arduino ~1.0 software, it is possible modifications have been made, but the above should still be true. If you have an ISP you do not need the bootloader at all.


body:
Normally (using the IDE via the serial/USB interface) the bootloader is retained, and the bootloader itself replaces the main code.

If you do ICSP programming then the first thing the programmer has to do is erase the entire chip (including the bootloader). Now nothing is stopping you putting the bootloader back as part of the programming sequence (it would add to the programming time slightly).

As Chris Stratton suggests, this is basically combining the .hex file for the sketch, and the .hex file for the bootloader. I'm not sure that literally concatenating them would work because there are a couple of other "record types" in the .hex file which might confuse the programmer if they were encountered twice - in particular the "end of file" record type.

However a strategy along these lines should give you a file that could be uploaded and put the bootloader back:

* Take the .hex file from the compiler, and copy up to, but excluding, the "end of file" record to a temporary file.
* Append the desired bootloader .hex file (including the "end of file" line).
* Program the chip with the resulting file.

For larger chips (like the Atmega2560) you would need to be cautious about handling the "extended segment address" record because that sets the high-order byte of the address to be programmed.

The hex file format, as documented in my [programmer sketch](http://www.gammon.com.au/uploader) is:

    Line format:

      :nnaaaatt(data)ss

      Where:
      :      = a colon

      (All of below in hex format)

      nn     = length of data part
      aaaa   = address (eg. where to write data)
      tt     = transaction type
               00 = data
               01 = end of file
               02 = extended segment address (changes high-order byte of the address)
               03 = start segment address *
               04 = linear address *
               05 = start linear address *
      (data) = variable length data
      ss     = sumcheck

                * We don't use these


body:
I belive what you want to do is program a Arduino by ISP and retain the bootloader, I have done this on occasion by first loading the bootloader onto a chip, then upload the Arduino *sketch*, then i use the ISP programmer to read the whole flash back into hex file.

This hex file is then used to program the rest of the chips for production. (If you feel this takes too much time, it is possible to strip the hex file down, but that might be a bit complicated)


message:
Buying Arduino Parts Different Manufacturers

I'm looking to buy my first arduino kit. However I have a concern.

If my Arduino Mega is bought from one manufacturer, then can I buy shields or other parts from other manufacturers? Are there any incompatibility issues

Thanks!

body:
Of course you can. In just the same way that you can buy a car from one manufacturer and bumper stickers from another.

That's the whole point of the Arduino platform - mix and match to make things -just like LEGO®.


message:
Cannot control servos through 32-servo-controller on Aurduino Duamilanove

I have servo (TowerPro sg90) connected to 32 servo controller ([this one][1]) through UART interface (RX-TX, GND-GND).
Seller provide documentation how to connect and control my servos, but it isn't work.

Servo work if I connect it indirectly to Arduino. Controller indicate that it is working too (photo below - red led).

I already try different servos. Also try use provided software to control servos from pc through Mac/PC. But it's interface is unreadable for me. I tried different options but servos not responding.

Sketch code below (from sellers examples):

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

    void loop() {
      Serial.print("#3P500T2000\r\n");
      delay(2000);
      Serial.print("#3P1500T2000\r\n");
      delay(3000);
      Serial.print("#3P2500T2000\r\n");
      delay(2000);
      Serial.print("#3P1500T2000\r\n");
      delay(2000);
    }

Photo of my connections:

[![arduino-duamilanovo+32-servo-controller+servo][2]][2]

Sorry if it post duplicate some, but I cannot google this problem.

  [1]: http://www.aliexpress.com/item/New-Version-32-Channel-Robot-Servo-Control-Board-Servo-Motor-Controller-PS2-Wireless-Control-USB-UART/32272674301.html
  [2]: https://i.stack.imgur.com/Verqy.jpg

body:
There is one connection missing - the one that powers the servo and board.

At the moment your servo board is getting a small amount of power through the RX pin - **disconnect it immediately, you are damaging it**.

You need to provide +5V to the +5V terminal block, and also a suitable voltage (+5V should do) to the VCC on the terminal block.


message:
Using 2 PING Senors at Once

I am trying to get values for two ping sensors, but am not getting any returns, can someone help me edit my code?

# Code

    void setup()
    {
      Serial.begin(9600);
      pingRange(2);
      pingRange(3);
    }

    void loop(){
    }

      long pingRange (int pingPin)

    {
      pinMode(pingPin, OUTPUT);
      digitalWrite(pingPin, LOW);
      delayMicroseconds(2);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(5);
      digitalWrite(pingPin, LOW);
      pinMode(pingPin, INPUT);
      return microsecondsToCentimeters(pulseIn(pingPin, HIGH));
    }

    long microsecondsToCentimeters(long microseconds)
    {
      // The speed of sound is 340 m/s or 29 microseconds per centimeter.
      // The ping travels out and back, so to find the distance of the
      // object we take half of the distance travelled.
      return microseconds / 29 / 2;
    }

body:
There's one part of your code conspicuous by its absence:

    pingRange(2);
    pingRange(3);

You're calling the functions, but you're not doing anything with the returned value.  I think you meant to print that value to the serial interface...

    Serial.println(pingRange(2));
    Serial.println(pingRange(3));


message:
Serial: What is different between Gammon's RS485 (blocking) and RS485 "non blocking" libraries?

The RS485 master-slave communication library on Nick Gammon's page http://www.gammon.com.au/Arduino/RS485_protocol.zip is working for me OK, but on the same hardware wiring is not working for the non-blocking library http://www.gammon.com.au/Arduino/RS485_non_blocking.zip.

I can not find information about the connection of MAX485 on Arduino for non-block version. Is MAX485/RS485 from HW serial (ie Rx=0 and Tx=1)?

If so, how can a slave on the same line at the same time receive from master the message "hello world" and print it to the serial monitor?
Thank you for the explanation.

When I added the SoftwareSerial library into Nick's example for non-blocking, so it works, but is it still a non-blocking?

    //Master:
    #include <RS485_non_blocking.h>
    #include <SoftwareSerial.h>
    const byte ENABLE_PIN = 4;
    SoftwareSerial mySerial(2,3); //RX = 2 TX = 3

    size_t fWrite (const byte what) {
      return mySerial.write (what);
    }

    RS485 myChannel (NULL, NULL, fWrite, 0);

    void setup () {
      Serial.begin (9600);
      mySerial.begin (28800);
      myChannel.begin ();

      pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
    }  // end of setup

    const byte msg [] = "Hello world";

    void loop () {
      digitalWrite (ENABLE_PIN, HIGH);  // enable sending
      myChannel.sendMsg (msg, sizeof (msg));
      digitalWrite (ENABLE_PIN, LOW);  // disable sending
      delay (1000);
    }  // end of loop

    //Slave:
    #include <RS485_non_blocking.h>
    #include <SoftwareSerial.h>
    const byte ENABLE_PIN = 4;
    SoftwareSerial mySerial(2,3); //RX = 2 TX = 3

    int fAvailable () {
      return mySerial.available ();
    }

    int fRead() {
      return mySerial.read ();
    }

    RS485 myChannel (fRead, fAvailable, NULL, 20);

    void setup() {
      Serial.begin(9600);
      mySerial.begin(28800);
      myChannel.begin();
      pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
    }  // end of setup

    void loop() {
      if (myChannel.update()) {
        Serial.write (myChannel.getData(), myChannel.getLength());
        Serial.println();
      }
    }  // end of loop

Regards, Vava
(Sorry for my English... :-)

body:
The hardware connection should be the same, as blocking vs non-blocking is referring to how you handle the incoming data packets.

Don't quote me on this, but generally, blocking vs non-blocking refers to the use of `delay()` or similar, which will block anything else from running while that function is being executed.


body:
<!-- language-all: lang-C++ -->

Reference page: <http://www.gammon.com.au/forum/?id=11428>

---

The blocking library is intended where you want to wait for incoming data, and are prepared to do nothing else while it arrives. There is also a timeout parameter which lets the code proceed if nothing happens for a specified number of milliseconds.

The non-blocking library is intended for where you need to do other things (like control motors, or read switches) at the same time you are receiving data. For that situation you call an `update` function periodically which assembles the incoming packet, byte-by-byte if necessary.

When the data is fully received the `update` returns true, and you can process the packet.

---

> If so, how can a slave on the same line at the same time receive from master the message "hello world" and print it to the serial monitor?

As I stated above in neither case do you receive and print "at the same time", however the non-blocking one does not simply wait until all the data has arrived.

---

Example code from the linked page:

    void loop ()
      {
      if (myChannel.update ())  // returns true when packet fully received
        {
        Serial.write (myChannel.getData (), myChannel.getLength ());
        Serial.println ();
        }

      // do other things while waiting

      }  // end of loop

---

>  If in example for non-blocking libraries is the same wiring as in the example of blocking library, where is (in non-blocking example) definition of RX(=2) and TX(=3) pins?

The hardware is the same.

---

> there is limitation for use - only pins which supports change interrupts.

Of course. If the underlying protocol is SoftwareSerial then the usual limitations apply (that is for the Rx pin).