# Question
Title: Rename device name (ch340 usb to serial) Mac OS
Can't upload sketches to Arduino Nano clone with USB to serial chip ch340.

After installing drivers and plugging in, device has the name `cu/tty.wch ch341 USB=>RS232 fa130` (with spaces), but Arduino can't recognize the full name (only `tty.wch`).

Is it possible to rename device in Mac OS or change device identifier?

UPDATE: `ch340` new driver http://www.wch.cn/downloads.php?name=pro&proid=178

# Answer
> 4 votes
I used a terminal command:

```
sudo ln -s /dev/tty.wch\ ch341\ USB\=\>RS232\ 1450 /dev/tty.USB0

```

where `/dev/tty.wch\ ch341\ USB\=\>RS232\ 1450` is the original name not recognized by Arduino; and `/dev/tty.USB0` is the new port name.

# Answer
> 6 votes
*I am Antonis from codebender and we recently released drivers for the Mac.*

If you want to overcome this problem, without disabling your computer's security settings, maybe I can help you with this! Codebender just released their Mac drivers package, which includes a new driver that supports the CH340G chip, on Yosemite and all other versions of OS X for Mac.

This will help you to install these drivers securely, and all you have to do is to download and install them.

You can find more information about the drivers in the codebender blog.

# Answer
> 5 votes
I send email about this issue to WCH, and they change drivers to the latest version on their website, this is direct link http://www.wch.cn/downloads.php?name=pro&proid=178 (driver works and device has proper name in `dev/`)

# Answer
> 3 votes
For Yosemite you seem to need to run this command in the Terminal and then restart the computer to get it to work.

```
sudo nvram boot-args="kext-dev-mode=1"

```

# Answer
> 1 votes
I was having the same problem. installed the latest drivers, I'm using yosemite, installed the Arduino IDE, and tried the board in windows 7 and it worked in windows, so board and cable are working.

In mac OS 10.10 in system report now they show as USB 2.0 Serial in arduino IDE it appears the port now (only after I used the SUDO command that sjunnesson posted) /dev/cu.wchusbserialalpha1310

so, use the sudo command if you are in yosemite

# Answer
> 1 votes
once you have installed the driver, you should be able to use it with any IDE or program

but I doubt anyone would prefer the Arduino IDE to codebender

---
Tags: osx
---


# Question
Title: Is there any way to flash sketches using custom firmware?
I am using HIDUINO as my firmware (flashing via dfu-programmer), and to upload sketch I need to re-flash original firmware, upload sketch and then flash HIDUINO again.

Is there a way to flash sketches without reflashing original firmware?

# Answer
> 1 votes
I assume you mean you are reprogramming the USB interface chip, which means you no longer have a UART pathway through to the ATMega328P. If so then yes, you can provide your own USB interface in parallel by connecting an FT232 (or similar) breakout board direct to the ATMega328P chip just like you would on a breadboard Arduino:

* FTDI TX -\> Arduino RX (Yellow)
* FTDI RX -\> Arduino TX (Blue)
* FTDI DTR -\> 100nF Capacitor -\> Arduino RESET (Green)
* FTDI GND -\> Arduino GND (Black)

The capacitor is required with later versions of `avrdude` and newer versions of the Arduino IDE since the DTR signal is now held LOW rather than being pulsed as it used to be. This is to combat a change in the FTDI drivers that meant that the DTR stopped being driven at all and broke the auto-reset facility. So now we need a capacitor to convert a constant LOW into a short low-going pulse to initiate a reset without locking it all up.

---
Tags: flash, firmware
---


# Question
Title: Updated Arduino IDE and Arduino not working
I've had the 1.0.5 IDE on my PC, which worked great. Now I've just decided to update to 1.6.6. After some stupid Java errors and trial and error, I got it to work.

I recompiled my project. Massive errors. Fixed the errors and compiled again.

It stated "Uploading..." That took much longer than before, but I saw the "This takes xxx memory and xxx bytes on the device" yadi yadi ya.

I decided to unplug the Arduino, swap some jumpers and reconnect it (as I've always done). Only this time - I hear 3 beeps from my PC (the sound you hear with broken USB devices). The COM port is no longer recognized.

How do I fix this? Did that IDE upgrade just brick my Arduino?

# Answer
> 0 votes
Allright, seems to be fixed. After a 3rd reinstall it seems like its fixed. I reinstalled the whole package, including the drivers, and now it seems to recognize the device again.

Also the compiling now stops properly when done and shows "upload complete".

---
Tags: arduino-uno
---


# Question
Title: Best practise when dynamically updating sketch
I am currently working on a project that uses an Arduino Mega 2560 board along with the Arduino GSM shield to connect to the internet and send/receive SMS messages.

As part of my project, I want to be able to update the software that I am running dynamically. At a high level, I want to connect to my server, check if there is an update, if there is, download it and then overwrite the current sketch to run the new downloaded binary if the checksum of the downloaded binary is as expected (to avoid corruption).

Now, I am new to Arduino programming, so I figured I would ask a community of people with experience to determine the best method.

My current ideas are as follows:

* **Writing a custom bootloader** \- The sketch will have an update routine that downloads the new binary to a known location, and then performs a system reset. The bootloader will then overwrite the current sketch with the downloaded binary and then run the sketch.
* **Overwriting the sketch whilst running** \- I'm not sure of the viability of this method, but the overall method would be to write an update routine to the end of flash memory, and in this code simply overwrite all of the non-bootloader code with the new sketch.

Are these methods both viable, if so, is there one that would be preferable to another? If not, are there any known solutions to this problem?

# Answer
> 1 votes
You won't be able to download the whole binary and test its checksum before flashing because RAM is so much smaller than flash. To do that, you'd need an external storage device to hold the new binary, and a custom bootloader to install it from the device.

Otherwise you'll have to load-and-flash, testing the checksum on the fly, and retry if you need to until you get a good reload. Can your device and its environment tolerate stopping for however long a couple of retry cycles might take? You can't recover if the process is interrupted once you start flashing; you can only move forward. Can it tolerate a conceivably long outage if communication goes down once the reload process has started?

---
Tags: uploading, bootloader
---


title: I don't have "Process" header

text:
# Question
Title: I don't have "Process" header
I'd like to run an application on my system after pushing a button on an Arduino shield. I've read that I need to use the `runShellCommand()` function, which can be accessed from a Process header. However when I add the `#include <Process.h>` line to my program I'm getting this error:

```
.build/uno/src/sketch.cpp:2:21: fatal error: Process.h: No such file or directory
 #include <Process.h>

```

I'm using Ubuntu 14.04 and I've installed Arduino software from repositories.

# Answer
That only works on an Arduino Yún (as described in this tutorial).
> 1 votes

---
Tags: arduino-uno, linux
---


title: Multiple RGB LEDs

text:
# Question
Title: Multiple RGB LEDs
I'm quite new to these things and I need some help. I'm building a computer shelf with plexiglass and RGB LEDs (one per length) and I need some help to sketch up a data sheet of some sort for this.

I'm thinking of using an Arduino Uno, but will it be able to run 12+ LEDs?

# Answer
> 1 votes
If your RGB LEDs are WS2812-style, 5050-size units, it is no problem to control dozens of them using an Arduino Uno or several other models of Arduinos. \[For ATtiny systems, other libraries than Adafruit's NeoPixel may be needed; the NeoPixel library keeps several bytes of state data per pixel, which some other libs don't.\]

WS2812-style LEDs typically are arranged in serial strings, driven by a single IO pin from an Arduino.

If you have more than half a dozen WS2812s in the string, power for them should come from an external power supply, rather than via an Arduino's built-in 5V regulator.

For more information, see related questions like *Arduino with WS2812 using Adafruit NeoPixel library fade in/out different patterns*, and *Arduino and WS2812 RGB LED Strip "freezing"*, and *fading colors on a ws2812 strip*; also see Google search Arduino Stackexchange for WS2812.

---
Tags: led
---


title: How to confirm a pin is fried

text:
# Question
Title: How to confirm a pin is fried
How do you confirm a pin has been damaged and is unable to work as a digital input?

I tried detecting a pushbutton (connecting ground to pin 11 with a pullup resistor enabled) on a fresh Arduino Uno and digitalRead() always registers 0, regardless of the pushbutton state.

To confirm it wasn't my pushbutton's wiring, I tested it on some other pins, and they register the button press perfectly. I then tested pin 11 as an output, and it was able to blink and LED just fine.

The Arduino's pretty new, and I don't remember doing anything with it that would have damaged anything, much less pin 11, but is it fair to say that pin has somehow been damaged? As far as I can tell, everything else on the Arduino works perfectly.

# Answer
> 1 votes
Yes, it sounds like that pin is fried.

You seem to have done all the things I would recommend:

1. Try your circuit on a different pin (works fine)
2. Try your circuit on the same (faulty) pin on a different microcontroller (works fine)

If you get different results between two chips that should be the same with the same code running on them then one of them is most likely faulty in some way, or has some other setting in it (fuse setting) that could be affecting it. I am not aware of any settings like that on the '328P, certainly none that you would change without knowing you had changed them.

---
Tags: arduino-uno, wires, digital-in
---


# Question
Title: How does this eBay relay board connect to the Arduino
I bought a single channel relay on eBay and besides the NC/COM/NO, it has six pins and a jumper.

It is not possible to see the labels on the image, but the labels are:

```
X  X--X  X  X  X
VCC   -IN+   GND

```

The default jumper position is shown above with a `-` mark.

Which pins should I use for VCC, GND and ARDUINO? Is the jumper on the correct position?

# Answer
Your module consists of both an optocoupler (large black rectangular device) and a P-channel MOSFET driver circuit for the relay.

VCC and GND are used to power the MOSFET and relay, and so should be connected to a power source suitable for driving the relay (if it's a 5V relay then the +5V and GND pins of the Arduino - if it's a 12V relay then a 12V power supply).

The interface to the Arduino is through the optocoupler. The Arduino sees that as just an LED, so you can wire it up just like any other LED. The circuit contains a current limiting resistor already, so you don't need to worry about that at all. So you connect the - of the input to GND and the + to an IO pin, or connect the + to +5V and the - to the IO pin, depending on which polarity of drive you want to have.

The jumper is optional to allow you to create one of those two links on the board - say connecting - to GND or connecting + to VCC so you don't need the extra wire.
> 2 votes

# Answer
You should do a bit of testing. The Vcc and GND pins will go to power and ground respectively. They are powering the circuitry on the board that protects the Arduino from the relay coil. Then it looks like the IN pins allow you to operate the relay either from an active high or an active low signal.

If you have a DMM check the connections of the pins (see if any of them are common). The thing that is puzzling to me is the jumper, but it may be set up so that you can use only two wires to control the relay by using the IN terminal to also supply either Vcc or ground.

So start out by hooking up to power and ground, and then test by jumping the IN pins to ground and power in turn. I would expect the relay to operate when the IN+ goes to Vcc or when the IN- goes to GND.
> 0 votes

---
Tags: arduino-mega, relay
---


title: Problems with Draw Loop using u8glib

text:
# Question
Title: Problems with Draw Loop using u8glib
I am using an Arduino Mega and a 12864ZW LCD with the u8glib library and the following code to draw to the LCD:

```
U8GLIB_ST7920_128X64 Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);

void loop(){
   Draw();
}

void Draw(){
   Display.firstPage();

   do{
      Display.setPrintPos(10, 10);
      Display.print("This is a test");
   }while(Display.nextPage());
}

```

The problem is that the display is constantly redrawing itself. When I used LCD displays in the past, they usually only required to write to the LCD once unless you wipe the display. When I adjusted the code to:

```
U8GLIB_ST7920_128X64 Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);
bool needsUpdate = true;

void loop(){
   Draw();
}

void Draw(){
   if (needsUpdate){
       Display.firstPage();
       do{
          Display.setPrintPos(10, 10);
          Display.print("This is a test");
       }while(Display.nextPage());
       needsUpdate = false;
   }
}

```

I do not get anything drawn on the LCD. Is there a parameter that needs to be set so I only have to redraw the LCD if something changes? Am I using an outdated library? Is there a better library I should be using?

**EDIT**

I think the main problem I have with using this library is does the Draw loop need to be executed continuously to display on the LCD or is there a way to only draw the screen once until it is needed to be drawn again?

# Answer
> 1 votes
You haven't shown us all the code – in particular, the call to `Draw()` from `loop()` is missing – so this answer is speculative, based on the assumption your `loop()` is as follows.

```
void loop(void) {
    Draw();
}

```

If so, your first bit of code will constantly redraw because `loop()` runs repeatedly without delay. Try adding a `delay(1000);` after `Draw()` in that case.

Your second bit of code will begin by drawing your image once, and in that `Draw()` call it will set `needsUpdate` to false. Then `loop()` runs again, and the `firstPage()` call erases the screen. Since `needsUpdate` now is false and remains false, subsequent calls don't draw an image.

Rather than putting your picture loop into `Draw()`, perhaps use `Draw()` just to draw primitives, and keep your controls in `loop()`:

```
void loop(void) {
  Display.firstPage();
  do {     // picture loop
    Draw();
  } while( Display.nextPage() );
  delay(1000); // delay before next picture
}

```

If you still get repeated fast redraws, for troubleshooting comment out the `do` and `} while` lines.

# Answer
> 1 votes
Much thanks to jwpat7 for getting me on the right track with this. So I found out how this LCD should really be setup. I am not sure why the examples I was able to find online and even on the u8glib wiki showed the usage like my question but I was able to get this library functioning right.

First thing is the .firstPage() and .nextPage() functions. The .firstPage() function actually clears the screen and the .nextPage() function displays what is waiting in the queue (thanks jwpat7). When the .nextPage() finishes there is no need to write to the LCD again until you need a refresh. I put together a very simple code example that uses a input to change the text without having to continuously update the LCD.

```
U8GLIB_ST7920_128X64 Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);
bool redraw = true;
String strOut = "This is a test...";

void loop() {

    if (redraw){
        Display.firstPage();  //Clear the LCD

        //Main Difference while the LCD needs drawing will return 1
        while(Display.nextPage()){
            Display.setFont(u8g_font_04b_03b);
            Display.setPrintPos(20, 20);
            Display.print(strOut);
        }

        redraw = false;  //Clear flag to redraw
    }

    //check if any of the pins in PINA have been pressed
    if (~PINA & 0xff){
        strOut = "Of the emergency broadcast ...";

        redraw = true; //Set flag to redraw the screen
    }
}

```

---
Tags: programming, arduino-mega, library, lcd, u8glib
---


title: Multiple servos noise

text:
# Question
Title: Multiple servos noise
I'm building an application that uses 20 servo motors, and i control then with an Arduino Mega. The servos are having some instability, to the point where they make small random swings. Im powering then from a 7.4V LiPo battery and I drop the voltage to around 6V with 2 series diodes. I've made some research and found 4 things that may help stabilize the servos.

* Put a 1000uF eletrolitic capacitor between the battery VCC and GND pins.
* Put a 470uF eletrolitic capacitor between each servo VCC and GND pins.
* Put a 100nF ceramic capacitor between each servo SIGNAL and GND pins.
* Put a 10k pull-up resistor on each servo SIGNAL pin.

My question is, how to make the right decision here. It is better for the project if I take all this designs into account, or I shouldn't be making some combination of this, or one in particular?

# Answer
You can use the old software serial library from mikal heart. that one does not die interupts. You can do a google search on it.

here is a forum topic about it: http://forum.arduino.cc/index.php?topic=82596.0
> -1 votes

---
Tags: arduino-mega, servo
---


# Question
Title: Does ATmega328 on Uno need to be burned?
I'm new to the Arduino world so please bear with me. I'm not sure whether the ATmega328 bootloader needs to be burned. What I'm reading is all that needs to be done is plug the board into the computer by USB cable. Then burning the 328 is also mentioned. I appreciate any help.

# Answer
> 1 votes
If you bought an Arduino Uno the bootloader comes pre-programmed.

"The ATmega328 on the Uno comes preprogrammed with a bootloader that allows you to upload new code to it without the use of an external hardware programmer. It communicates using the original STK500 protocol (reference, C header files)." - from the oficial page.

Might want to take a look at this discussion if you're confused.

# Answer
> 1 votes
You only ever need to burn a bootloader if:

1. You are building your own "breadboard" Arduino
2. You have somehow erased the bootloader that is on your Arduino
3. You have replaced the original chip on the Arduino

The chip that came already inserted into the Arduino board already has the bootloader installed into it.

# Answer
> 1 votes
It depends. If you bought the arduino from most places, it will be already be burned. However, some less reputable sources might not burn it. If the LED on pin 13 blinks when you power on the arduino, that means the bootloader is installed.

---
Tags: bootloader
---


title: Interface pressure Sensor

text:
# Question
Title: Interface pressure Sensor
Hello folks, I am using G1/4 Pressure Transmitter Sensor 0-1.2 MPa sensor can you guide for programming part.The conversion from bar to pascal or bar to Mpa or pascal to psi.Though I am new to it. Plz guide me .

# Answer
I'm assuming you mean that you want to pull a voltage number off of an input pin and convert it to a meaningful number.

To do this find the range of the incoming voltage.

Find the range of the sensor.

After that you need to split the voltage up to show what parts of the range convert to how much psi.

Here is an example of a temperature gauge that has the same principle.

Temp sensor
> 1 votes

# Answer
One thing that I would add to this is that if you need good accuracy you may want to apply a voltage equal to your full scale output to the AREF pin. The value on AREF does not have to be equal to the full range of the sensor – just to the maximum value you will get – if you will never see readings at the extremes of the sensor's range you can set your AREF below the maximum value and get higher resolution.

Tronixstuff has a good tutorial on the AREF pin that goes into considerable detail about how to configure the pin and use the `analogReference()` function.
> 0 votes

---
Tags: arduino-uno, c
---


# Question
Title: Sending data over TCP connection in one piece
I'm trying to send short strings via Java client to Arduino server and vice versa. Sending data to client goes fine, but when I try to send data to arduino it cuts the string into bytes and then sends the first letter. Will the following work?

```
for(int i = 0; i < data.length(); i++)

```

Even if it can be sent as characters I want to send it in one piece, because strings are very short so there should be no problems with length.

EDIT: Alright, I read `client.read()` documentation, so the problem is at arduino.

This is my java code:

```
public class TCP {
static Socket clientSocket;

public static void main(String args[]) throws Exception {
    clientSocket = new Socket("10.10.10.57", 5000);
    sendToServer("HAI THERE\n");
    String msg = getFromServer();
    System.out.println(msg);
    close();
}

static void sendToServer(String msg) throws Exception {
    //create output stream attached to socket
    PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
    //send msg to server
    outToServer.print(msg + '\n');
    outToServer.flush();
}

static String getFromServer() throws Exception{
    //create input stream attached to socket
    InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
    BufferedReader inFromServer = new BufferedReader(isr);
    //read line from server
    String res = inFromServer.readLine(); // if connection closes on server end, this throws java.net.SocketException
    return res;
}

static void close() throws IOException{
    clientSocket.close();
}
}

```

This code sends only one byte at the same time.It might be problem in my arduino code, since I read it with

```
char c = client.read()

```

One more thing. If there is any java master, I would like to know what to do with exceptions. How should I handle disconnected socket, failed connection to server, and so forth?

# Answer
The problem is, that "char" is just one character. So you have to build your return out of the chars... if you want to use the "client.read()" function.

```
String res = ""; //this will be the resived msg after the loop
do {
   char c = client.read(); //c will be -1 if no byte is left
   if(c!=-1)
       strcat(res, String(c)); //Append the char to the result string
} while(c!=-1);

```

//Code is not tested!!!

To your java problem... just put your code parts into try catchs not whole functions (remove it for the function and add it on the points eclipse tell you to). So you can react to each error individually. Then put client stuff in a own thread so it not blocks any other stuff. Every disconnect or faild connection will throw an exception if you dont catch it with an if. So you have to handel it their (try to reconnect or something)

EDIT:

```
static void close() {
    try {
        client.close();
    } catch (IOException e) {
        system.out.println(e.toString()); //Print the error or do something else

    }
}

```
> 2 votes

---
Tags: arduino-uno, tcpip, java
---


# Question
Title: Problem in Uploading a Bootloader to Atmega8A
I am getting an error while Uploading the Bootloader to Atmega8A I am selecting..

```
  Board -> Arduino NG and Older
  Processor -> Atmega8A
  Programmer -> USBasp

```

and sketch code is ArduinoISP, After selecting port then I do "Burn Bootloader"

But getting an error of...

```
   "efuse" memory type not defined for part "ATmega8"
    Error while burning bootloader.

```

Please tell me what to do. Any help will be appreciated.

Thank you

# Answer
I used Programmer "AVRUPro+" for Uploading Program. I downloaded its Software "Progisp" Then I did some few steps....

1) After downloading it, Run the Progisp.exe file.
2) Then went to Command tab, and clicked “Program Fuse”, It just did my fuse set.
3)Then I just did the simple process of burning the bootloader to my Atmega Controller.
4)After this I was able to upload my program to my new Atmega Controller.

Thank you
> 0 votes

# Answer
Google is your friend!!! Apparently this is a known regression bug not yet corrected. The possible solution is also suggested there by user rigelinorion and here is the quote:

```
Hello, I solved it this way...

Open for edit the file C:\Program Files\Arduino\hardware\arduino\avr\platforms.txt
this is standard section uploader/programmers tools

#==============================================================================
tools.avrdude.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude
tools.avrdude.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf
tools.avrdude.cmd.path.linux={runtime.ide.path}/hardware/tools/avrdude
tools.avrdude.config.path.linux={runtime.ide.path}/hardware/tools/avrdude.conf

tools.avrdude.upload.params.verbose=-v -v -v -v
tools.avrdude.upload.params.quiet=-q -q
tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.program.params.verbose=-v -v -v -v
tools.avrdude.program.params.quiet=-q -q
tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.erase.params.verbose=-v -v -v -v
tools.avrdude.erase.params.quiet=-q -q
tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Uefuse:w:{bootloader.extended_fuses}:m -Ulock:w:{bootloader.unlock_bits}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude.bootloader.params.verbose=-v -v -v -v
tools.avrdude.bootloader.params.quiet=-q -q
tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.ide.path}/hardware/arduino/avr/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m
#==============================================================================

create a new tool called, for example, avrdude1
simply copy section tools.avrdude and name it tools.avrdude1
the trick is that we remove switch "-Uefuse:w:{bootloader.extended_fuses}:m" from "tools.avrdude1.erase.pattern="

#=============================================================================
tools.avrdude1.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude
tools.avrdude1.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf
tools.avrdude1.cmd.path.linux={runtime.ide.path}/hardware/tools/avrdude
tools.avrdude1.config.path.linux={runtime.ide.path}/hardware/tools/avrdude.conf

tools.avrdude1.upload.params.verbose=-v -v -v -v
tools.avrdude1.upload.params.quiet=-q -q
tools.avrdude1.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude1.program.params.verbose=-v -v -v -v
tools.avrdude1.program.params.quiet=-q -q
tools.avrdude1.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude1.erase.params.verbose=-v -v -v -v
tools.avrdude1.erase.params.quiet=-q -q

#this line was edited
tools.avrdude1.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude1.bootloader.params.verbose=-v -v -v -v
tools.avrdude1.bootloader.params.quiet=-q -q
tools.avrdude1.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.ide.path}/hardware/arduino/avr/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m
#==============================================================================

Here is an example of the use of the tool avrdude1 in boards.txt file

atmega8.name=ATmega8 OPTIBOOT
atmega8.upload.protocol=arduino
atmega8.upload.maximum_size=7168
atmega8.upload.speed=115200
atmega8.upload.tool=avrdude1
atmega8.bootloader.low_fuses=0xbf
atmega8.bootloader.high_fuses=0xCC
atmega8.bootloader.path=atmega8
atmega8.bootloader.file=optiboot/optiboot_atmega8.hex
atmega8.bootloader.unlock_bits=0x3F
atmega8.bootloader.lock_bits=0x0F
atmega8.bootloader.tool=avrdude1
atmega8.build.mcu=atmega8
atmega8.build.f_cpu=16000000L
atmega8.build.core=arduino
atmega8.build.variant=standard

```
> 1 votes

---
Tags: bootloader
---


# Question
Title: Simple Speed question - Mapping PWM values
I am working on an Arduino project for school to power a 12V DC cooling fan.

I want to adjust the speed of the fan. The instructions say to set the motor pin at an equation of `(0 to 9) * 10 + 150` to get a range of 150 to 240.

I need to write a mathematical equation but can not figure out what 150 to 240 means. Is this voltage, resistance...? Thanks for the help.

# Answer
> 5 votes
The `analogWrite()` function takes a value that is between 0 (fully off) and 255 (fully on).

Your value of 150 to 240 is a value within that range of 0 to 255 and represents a percentage of the "on time" of the PWM signal.

* (150 / 255) * 100 = 58.8% on time
* (240 / 255) * 100 = 94.1% on time.

You seem to have an "input value" of between 0 and 9 inclusive. Let's call this value "*i*". You want an output value, let's call it "*o*".

The instructions say "0 to 9 times 10 plus 150 to get a range of 150 to 240". That is simple enough to convert to a formula. 0-9 is *i*, remember:

* *o = i × 10 + 150*

If *i* is 0 then *o* = *0 × 10 + 150* = *0 + 150* = *150*.

If *i* is 9 then *o* = *9 × 10 + 150* = *90 + 150* = *240*.

As Ignacio mentions, the Arduino API has a `map` function which is meant to be used for this kind of thing;

```
o = map(i, 0, 9, 150, 240);

```

*However:* the `map()` function is quite heavyweight since it is designed to be a generic mapping function for scaling values. Doi g the calculation manually will always be far more efficient since map will use steps and calculations that are not really part of your needed result. It's a bit like the differende between 1 + 2 and 1+ 5 - 3 + 2 - 4 + 2. The result is the same, but one is far simpler to calculate than the other.

# Answer
> 3 votes
They're the value to pass to `analogWrite()` in order to generate a PWM waveform with an appropriate duty cycle.

But don't bother writing your own algorithm, just use `map()`.

# Answer
> 1 votes
The map() function is the answer. It "rescales" the range of the data, using this formula:

```
(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

```

You input these five values:

```
map(value, fromLow, fromHigh, toLow, toHigh)

```
* `value` is the X value you want to resize
* `fromLow` and `fromHigh` is the range that X is currently in
* `toLow` and `toHigh` is the range that you want to scale X to

---
Tags: power, pwm
---


# Question
Title: 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);
}

```

# Answer
From Arduino.cc:

> 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

```
> 2 votes

---
Tags: arduino-uno, c++, led, arduino-ide, c
---


title: Better way than exit(0)?

text:
# Question
Title: 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.

```
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);
  }
}

```

# Answer
> 1 votes
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/

---
Tags: arduino-uno
---


# Question
Title: 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?

# Answer
> 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.
> 1 votes

---
Tags: arduino-uno, shields, ethernet
---


# Question
Title: 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. 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)

# Answer
> 1 votes
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.

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

---
Tags: arduino-uno, arduino-yun, wireless, web
---


# Question
Title: Unable to upload sketch on Mac OSX El Capitan
I recently dusted off an *old* Arduino Duemilanove to play with. I can connect it to my Mac laptop with the same USB cable I used previously and I'm able to monitor the serial port and see the output from the last sketch I uploaded (five years ago). Everything is unplugged from the board.

When I try to upload a new sketch, the Arduino IDE gets stuck on `Uploading...` indefinitely:

```
Using Port                    : /dev/cu.usbserial-A800eGZI
Using Programmer              : arduino
Overriding Baud Rate          : 19200

```

The board itself has the green `PWR` LED and amber `TX` LED on solid once the currently loaded sketch starts running. Initiating an upload causes the amber `L` LED to blink three times, then the `RX` LED blinks twice, and finally the `TX` LED on solid.

Here is the exact board: https://www.sparkfun.com/products/retired/666

---

My research into this issue produced many suggestions that have not resolved the problem...

I disabled the built-in FTDI driver:

```
sudo kextunload -b com.apple.driver.AppleUSBFTDI

```

And made sure the FTDI driver from ftdichip.com was loaded:

```
sudo kextload /Library/Extensions/FTDIUSBSerialDriver.kext

```

I tried `csrutil enable --without kext` against my better judgement and saw no change.

I also tried a completely separate machine -- my PC running Windows 10 -- and the upload hung there too.

I have tried timing the upload to coincide with a board reset, hoping to sneak my upload in before the current sketch starts running. I did this *a lot* and got no satisfaction.

I haven't given up yet; there are too many signs of life to think that it's unrecoverable. I'm looking for more suggestions on how to troubleshoot.

I have already ordered another Arduino -- hopefully I can use it to burn the bootloader on the Duemilanove.

# Answer
The problem was that I selected `ATMega168` when I should have selected `ATMega328`
> 0 votes

# Answer
Possibly the boot-loader baud rate in the IDE's `boards.txt` file is wrong. I have older (less than 6 years) '328p chips whose boot-loaders expect 57600 baud, but the boards.txt file in more recent Arduino IDE's try to talk to them at 115200 baud. I've had to duplicate the Arduino Uno entry in boards.txt and make one that specifies 57600 baud, to use these chips.
> 0 votes

---
Tags: arduino-due
---


title: LM35 and Character LCD

text:
# Question
Title: 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);
}

```

# Answer
> 1 votes
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 from the arduino site.

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

---
Tags: lcd, arduino-pro-mini, temperature-sensor
---


title: How to get started?

text:
# Question
Title: 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

# Answer
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 (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.
> 1 votes

---
Tags: arduino-uno, arduino-leonardo
---


title: What is the Arduino Uno default sketch?

text:
# Question
Title: 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.

# Answer
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.
> 2 votes

---
Tags: arduino-uno, sketch
---


# Question
Title: 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?

# Answer
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:

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.
> 3 votes

---
Tags: arduino-uno, digital
---


# Question
Title: 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?

# Answer
> 4 votes
You can use the internal pullup e.g.

```
pinMode(inPin, INPUT_PULLUP);

```

Then wire your switch between pin and Gnd.

# Answer
> 1 votes
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.

---
Tags: button
---


# Question
Title: Read RC receiver channels using Interrupt instead of PulseIn
I am designing my own quadcopter control algorithm, whereby I currently read 4 RC receiver channels using PulseIn on each loop in the following manner:

```
ch1_raw = pulseIn(rcPin1, HIGH, 25000);

```

In other words, ch1\_raw contains the length of a HIGH pulse in microseconds.

I now want to avoid PulseIn in the interest of speed and instead achieve the same using interrupt.

I have looked at http://playground.arduino.cc/Main/PinChangeIntExample and I am aware that other similar questions have been asked (e.g. How to read RC receiver channels without using pulsein() command with arduino and Is PulseIn fast enough for Quadcopter?), but I don't understand how to implement interrupt to give me the correct ch1\_raw value on each loop.

Can somebody help me? (I'm new to Arduino, so go easy on me please!) Thanks!

---

Edit: So far I have tried to implement the following:

```
#include <PinChangeInt.h>

unsigned long pulsestart, pulsewidth;

int rcPin1 = A0;

void setup(){

  pinMode(rcPin1, INPUT);

  Serial.begin(9600);

  PCintPort::attachInterrupt(rcPin1, counttime,RISING);
  PCintPort::attachInterrupt(rcPin1, subtracttime,FALLING);

}

void loop(){

  Serial.print("  pulsewidth: ");
  Serial.println(pulsewidth);

}

void counttime()
{
  pulsestart = micros();
}

void subtracttime()
{
  pulsewidth = micros()- pulsestart;
}

```

Edit 2: (Somewhat) successful implementation so far, using EnableInterrupt.h instead. It seems that FALLING is being detected, but not RISING.

```
#include <EnableInterrupt.h>

#define rcPin1 10

volatile uint16_t pulsestart=0;
volatile uint16_t pulsewidth=0;
//volatile unsigned long pulsestart=0;
//volatile unsigned long pulsewidth=0;
volatile uint16_t risingcount=0;
volatile uint16_t fallingcount=0;

void counttime()
{
  pulsestart = micros();
  risingcount++;
}
void subtracttime()
{
  pulsewidth = micros()- pulsestart;
  fallingcount++;
}

void setup() {
  Serial.begin(9600);
  pinMode(rcPin1, INPUT_PULLUP);
  enableInterrupt(rcPin1, counttime, RISING);
  enableInterrupt(rcPin1, subtracttime, FALLING);
}

void loop() {
  //delay(1000);
  Serial.print("risingcount: ");
  Serial.print(risingcount);
  Serial.print(" fallingcount: ");
  Serial.println(fallingcount);
  //Serial.print("pulsewidth: ");
  //Serial.println(pulsewidth);
}

```

# Answer
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 (as of 3 April 2015). Consider using `EnableInterrupt.h` 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 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` from arduiniana.org 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.
> 5 votes

# Answer
Interrupts don't obey, or even understand the concept of, the "loop" paradigm.

An interrupt fires when it needs to fire, and if you're reading a PWM signal then that means it's firing hundreds of times a second.

As long as your interrupt is updating a variable that can be read from within the loop, and you ensure that the variable doesn't get updated during your reading of it (Google: *Critical Sections*) then you will always have the most up to date value at your fingertips whenever you need it.

As for the interrupt itself, that's very straight forward - you just need to recognise if it's a rising or falling edge:

* If rising edge: record the timestamp (micros()).
* If falling edge: Subtract the recorded timestamp from the current micros() and store in the global variable.
> 3 votes

---
Tags: arduino-uno, interrupt, pulsein
---


# Question
Title: 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#

# Answer
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.
> 1 votes

# Answer
> 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.
> 1 votes

---
Tags: uart
---


title: Arduino Uno not appearing under ports

text:
# Question
Title: Arduino Uno not appearing under ports
I have an Arduino Uno attached to my MacBook Air running the Arduino IDE 1.6.4.

The Arduino was visible in the Serial port section this morning, but then it just disappeared. The ON light on the Arduino still comes on, but I cannot connect to it through the port section. I attached the Uno to another computer and it did not appear there either. However, when a different Arduino is connected to my computer it does show up. I also tried using a different IDE version, and it did not appear there either.

All of the other topics I found regarding this were saying it is the OS's fault, but since I was able to see the other Arduino, I am pretty sure it is not. I updated the FTDI drivers, and I tried using a powered hub and it is still not there.

UPDATE:

When I took the chip out of the UNO that is not appearing and put it into a working UNO, I was able to see it, is it possible that the Serial port is just not working, and if so how would I fix that

Any help would be appreciated.

# Answer
> 1 votes
If the Arduino doesn't show up on multiple computers, and others do, it may be bricked, or dead. You might try reflashing the chip, and hope that solves your issue. If it doesn't, chances are it's toast.

If however the device simply doesn't show up on one computer, but does on another. It's either a software issue, or a USB issue with that computer.

If winblows OS, try reinstalling, or updating the drivers for the USB, as well as the Arduino. And check your power management on the USB as well. I've seen Windows USB poop the bed if a device is connected / disconnected, or restarted several times in rapid succession. When this happens, sometimes Windows will think the port or device is faulty, and simply stop responding to its presence.

If \*nix, make sure you've configured it properly.

# Answer
> 0 votes
When an Arduino stops appearing, it is usually because it's fried. Especially if other machines appear when connected, and the faulty machine appears on no other machine.

Try burning the bootloader.

---
Tags: arduino-uno, serial, uploading
---


# Question
Title: 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);
    }
  }
}

```

# Answer
> 0 votes
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()%100 ==0) reportState(flingState,releaseState);
  } // end loop

```

# Answer
> 2 votes
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

# Answer
> 0 votes
@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);
      }

  }

}

```

---
Tags: debugging
---


# Question
Title: 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.

# Answer
> 6 votes
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.

---
Tags: arduino-uno, led
---


# Question
Title: Sending and receiving custom messages with Ardulink
I am sending custom code to Arduino with this ardulink command:

```
{        ArduinoControl.link.sendCustomMessage("oled");
}

```

Code from standard Ardulink sketch CustomMessagesChipKit.ino:

```
{
  if (stringComplete) {
    if(inputString.startsWith("alp://")) {
    // OK is a message I know (this is general code you can reuse)
      boolean msgRecognized = true;
      if(inputString.substring(6,10) == "cust") { // Custom Message
        // here you can write your own code.
        int separatorPosition = inputString.indexOf('/', 11 );
        int messageIdPosition = inputString.indexOf('?', 11 );
        String customId = inputString.substring(11,separatorPosition);
        String value = inputString.substring(separatorPosition + 1, messageIdPosition);
        if(customId == "oled") {
            //Clear the virtual buffer
            lcd.noBacklight();
            analogWrite(9,100);
            digitalWrite(13, HIGH);
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("jkhgvjgv");
        } else {
          msgRecognized = false;
          // this sketch doesn't know other messages in this case command is ko (not ok)
        }
      } else {
        msgRecognized = false;
        // this sketch doesn't know other messages in this case command is ko (not ok)
      }
      // Prepare reply message if caller supply a message id (this is general code you can reuse)
      int idPosition = inputString.indexOf("?id=");
      if(idPosition != -1) {
        String id = inputString.substring(idPosition + 4);
        // print the reply
        Serial.print("alp://rply/");
        if(msgRecognized) { // this sketch doesn't know other messages in this case command is ko (not ok)
          Serial.print("ok?id=");
        } else {
          Serial.print("ko?id=");
        }
        Serial.print(id);
        Serial.write(255); // End of Message
        Serial.flush();
      }
    }
    // clear the string:
    inputString = "";
    stringComplete = false;
  }}

```

As a result the LED on pin 13 is turning on after message from java program. But that is all. LCD or or LED on PWM 9 pin are not reacting at all.

Also I could not understand how to send an answer back from Arduino to Ardulink. Can you please show me an example? I would love to send and print data in Java program from DHT11 sensor in response. I know about RawDataListener and I read the whole Ardulink site, but I did not understand that. I a newbie in programming.

When i replace

```
{String customId = inputString.substring(11,separatorPosition);}

```

with

```
{String customId = inputString.substring(11,15);}

```

than everything works. What can it be?

# Answer
you can read a complete (real project) example about how to receive messages from Arduino with Ardulink from here: https://github.com/openQCM

In general you can use a listener (digital, analog, and raw) to receive messages from Arduino. A raw listener receive all messages received from Arduino, so you need to implement code to filter the messages you are interested in. Digital and Analog listeners receive events from digital and analog PINs.

The sketch in your question isn't the original sketch you can find in Ardulink distribution. That sketch was written to manage the OLED on the ChipKit shield I have. You have modified the sketch to manage your LCD.

Actually you can send successfully messages from an Ardulink based application (as Ardulink Console) to Arduino since LED on PIN 13 is turned on. So the problem maybe just on your sketch.

To FIX analogWrite on PIN 9 try to set the PIN as OUTPUT with this statement: pinMode(9, OUTPUT);

I cannot help you with lcd library that I don't know.

If you need for some help don't hesitate to write to me.
> 1 votes

# Answer
It looks like you're trying to send a custom message to arduino and have it respond. As a small add on to your code try serialCommand. It pulls in whatever you send over the command line and executes it as a command and returns whatever you need to whatever interface you gave such as softwareSerial.

https://github.com/scogswell/ArduinoSerialCommand/tree/master/examples

I offer that you could use the two together to get the results you want.

Let serialCommand listen for commands and execute them and then set up a listener in Java for any serial communication back from the unit.

That's more or less what I end up doing when it comes to bluetooth, rf24, and wifi anyway, so why not serial as well.
> 1 votes

---
Tags: arduino-uno, serial, library, communication, java
---


# Question
Title: 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?

# Answer
> 1 votes
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 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.

# Answer
> 1 votes
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

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

Download pdf

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

---
Tags: esp8266
---


# Question
Title: Is there something I can use to control Arduinos easily over Ethernet with .NET?
I'm wondering if there's anything out there that maybe works pretty similarly to Firmata, runs on Unos or Megas, and can be controlled over Ethernet. I am writing a home automation system with .NET, and I see some options for supporting Firmata with .NET, but I want to be able to connect my devices over Ethernet.

# Answer
> 1 votes
I don't use .net but I have done this using php website to control a door lock over ethernet.

My solution was to use the ethernet to recieve commands and be able to use them on the arduino through http calls. And when it was done send a http call back to the server with some data. I was doing a door lock program for example. Please ignore anything talking about doors, locking, unlocking, or other requirements to certain calls, I am just providing examples about how it COULD be used, not that you need to include my door lock code in your project to get it to work.

As far as how that works out with .net that's up to you, however I can give you a hand getting your messages back and forth.

first you want to create the ethernet connection to your router. put this in your header section.

```
#include <UIPEthernet.h>
// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(127, 0, 0, 1);

// initialize the library instance:
EthernetClient client;

char server[] = "www.example.com";
//IPAddress server(127,0,0,1);  // numeric IP for www.example.com (no DNS)

int waitTime = 3L;

unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
const unsigned long postingInterval = waitTime * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

```

throw this in your main loop so it doesn't constantly make http requests spamming a server.

```
// if ten seconds have passed since your last connection,
// then connect again and send data:
if (millis() - lastConnectionTime > postingInterval || buttonState == 0) {
  httpRequest();
}

```

Create a method to handle httpRequest because shoving everything under the main is kinda sloppy.

Alright so there will be quite a bit here because http headers are kinda lengthy.

```
// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();
  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP PUT request:
  Serial.println("String is " + readString);
  if(readString == "Ready" || readString == ""){
    client.println("GET /command.txt HTTP/1.1");
    where = "web";
    waitTime = 5L;
  }
  else{
    // here is the basic format of sending a get command
    //this specific request is so that I can tell where the command came from. I had a web client / mobile app that could control the door AND you could also control it from a physical buttom. The door would have to reply either way to the web server (READ: .net application) in order to have the correct status always show up on the web end.

    client.print("GET /update.php?where=Arduino&command=Ready&status=");
    if(readString == "Reset"){
      client.print("Reset");
    }
    else if(isLocked){
      client.print("Locked");
    }
    else{
      client.print("Unlocked");
    }
    client.println(" HTTP/1.1");
    waitTime = 1L;
  }
  client.println("Host: www.example.com");
  client.println("User-Agent: arduino-ethernet");
  client.println("Connection: close");
  client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

```

TL;DR if you wanna use ethernet you need to use all of ethernet. Start by creating your connection to the router statically (watch for conflicts).

Then create a method of watching for incoming data or waiting for a command if there isn't one. (server call).

Then create A FULL HTTP REQUEST in order to pass your request through. Shorting any parts of this last part and you will either end up with bad request errors or will simply fail.

Let me know if you need anything else or if this was useful to you!

---
Tags: ethernet
---


title: What killed it? Arduino in resin

text:
# Question
Title: What killed it? Arduino in resin
I made a simple circuit controlled by the ATMEGA IC then tried to encase it in resin. It died. What is the thing that caused it to die? I've had other circuits working fine in resin. I want to try again, what steps can I take to prevent this?

I've looked for obvious shorts but can find none.

Resin heats up when it cures, could that be the issue?

# Answer
Potting of circuits can lead to various issues. It can't be told exactly what caused your device to fail until you uncover it like an archeologist.

Common problems are:

* Resin entering a spring loaded contact and canceling out contact forces
* Resin exsuding corrosive substances ruining contacts
* Resin expanding during curing and opening spring contacts or even breaking up solder contacts
* Same effect after cool down of resin

Later and often unexpected problems are:

* thin gaps around potted objects (i.e. no surface contact) literally sucking in water.
* potting material producing water itself during curing.

Many of these problems can be circumvented by applying conformal coating, as suggested by comments and apparently proven right by your experiments. If it is not necessary refrain from using sockets and solder connections directly to the components. You won't be able to salvage them, anyway.
> 3 votes

---
Tags: enclosure
---