# Question
Title: Reading Arduino from Java is way too slow
I am trying to write a simple Java program to display the analog input fed to an Arduino board upon a stimulus from a user on some physical sensors.

If I use the Arduino program itself and look at the serial monitor, I see the analog read based on user input updated instantly. However, when reading the input from my Java program, there is a significant delay (8-12 seconds) between the physical stimulus and the display of the value.

The code uploaded to Arduino is very simple, just cycle through a bunch of analog ports and print the data:

```
void setup() {
  Serial.begin(9600);
  pinMode(30, OUTPUT);
}

void loop()
  digitalWrite(30, HIGH);

  for (int i = 0; i < 10; i++) {
    int sensorValue = analogRead(i);
    Serial.print(String(i) + ":");
    Serial.println(sensorValue);
  }
}

```

The Java code I am using is almost entirely copied from the example provided here, with the exception that I updated the port name to work for my system (Mac OS X 10.10.3).

Here is the Java code:

```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;

public class SerialTest implements SerialPortEventListener {

    SerialPort serialPort;

    /** The port we're normally going to use. */
    private static final String PORT_NAMES[] = {
            "/dev/cu.usbmodem1411",
            "/dev/cu.usbmodem1451",
    };

    /**
    * A BufferedReader which will be fed by a InputStreamReader
    * converting the bytes into characters
    * making the displayed results codepage independent
    */
    private BufferedReader input;

    /** The output stream to the port */
    private OutputStream output;

    /** Milliseconds to block while waiting for port open */
    private static final int TIME_OUT = 2000;

    /** Default bits per second for COM port. */
    private static final int DATA_RATE = 9600;

    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        //First, Find an instance of serial port as set in PORT_NAMES.
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }

        try {
            // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(),
                    TIME_OUT);

            // set port parameters
            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            // open the streams
            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
            output = serialPort.getOutputStream();

            // add event listeners
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }

    /**
     * This should be called when you stop using the port.
     * This will prevent port locking on platforms like Linux.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    /**
     * Handle an event on the serial port. Read the data and print it.
     */
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine=input.readLine();
                System.out.println(inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    public static void main(String[] args) throws Exception {
        SerialTest main = new SerialTest();
        main.initialize();
        Thread t=new Thread() {
            public void run() {
                //the following line will keep this app alive for 1000 seconds,
                //waiting for events to occur and responding to them (printing incoming messages to console).
                try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
            }
        };
        t.start();
        System.out.println("Started");
    }
}

```

All the program does is print out the values of the Arduino serial monitor, yet it takes way longer (8-12 seconds) through Java than it does from the Arduino program itself.

1) Why is this happening?
2) How do I fix it?

# Answer
> 1 votes
Timing tests show that the Java code lags something like 25 or more seconds behind the input from the Arduino. This can be fixed by changing in the Java code these lines:

```
       try {
            String inputLine=input.readLine();
            System.out.println(inputLine);
        } catch (Exception e) {

```

to:

```
       try {
            while (input.ready ())
              {
              String inputLine=input.readLine();
              System.out.println(inputLine);
              }
        } catch (Exception e) {

```

This extra loop "drains" the input buffer of data in the one serialEvent call, rather than relying upon a serialEvent call per line of data.

I found when testing that the output is now highly responsive, even without a delay on the Arduino side.

---

My other answer of adding a `delay` call slowed output down enough for the Java app to catch up, but I must admit it isn't the best solution.

# Answer
> 0 votes
One more thing you could do is create a `while(true)` loop, after `initialize()` and call `input.readLine()`, so that you don't wait for the event to appear.

For some reason the event is delayed, but doing the while loop hasn't created any issues or exceptions for me so far.

My code is like this:

```
public void initialize() {
   //initializing stuff
   while(true){
       try {
           String inputLine = input.readLine();
           //do stuff here
       } catch (Exception e) {
           System.err.println(e.toString());
       }
   }
}

```

# Answer
> -1 votes
Try adding a delay, eg.

```
delay(200);

```

into your main loop. You may be sending data too fast for the Java app to cope with.

---
Tags: arduino-mega, arduino-ide, mac-os
---


# Question
Title: Powering Arduino with reverse car lights?
I'd like to build a reverse car sensor using Arduino

When we select reverse gear, the reverse lights powers, so we can take electricity from them.

My question is can i power my Arduino directly from the reverse lights wires, or should i use regulators or anything else?

# Answer
Use a switching regulator such as the LM2596. You can get a ready board from eBay for about US$1
> 2 votes

# Answer
It depends very much on the car and your Arduino. There are two factors to consider:

1. Leeching power off lights can have an adverse effect on the car's ability to sense a blown bulb.
2. Many Arduinos have a 2 second delay while the bootloader executes (some even have 8 seconds).

If your car doesn't sense blown bulbs (most modern ones now do, even cheap ones) and you can work without a bootloader (programming directly with a USBasp for example) to avoid the power-on delay, then it may be possible, yes.

As has been mentioned by others, using a switching regulator is the best method for powering the board as it avoids excess power loss through heat (which can especially be a problem in confined spaces). I would recommend not using one of the cheap eBay modules, but instead using a proper "cigarette lighter" to USB adaptor (available from all good gas stations priced $5) which is designed to work with automotive voltages. A car's 12V power has transients in excess of 50V sometimes (back EMF from the spark generation) and the electronics have to be able to cope with that - those cheap eBay modules aren't designed for that and could die taking your Arduino with it.
> 2 votes

# Answer
This is just to top off the other answers. If you have a fairly modern car that runs on LED lights, you can easily use that voltage. ***MOST*** LEDs run from around 3-6V soyou might want to measure the voltage. If everything is good, then you can connect the positive of the LED to the 5V of your Arduino and GND to GND.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Whats the function of the resistor between MCU and its Resonator in Arduino Mega?
I was looking Arduino Mega's schematic and I noticed a resistor between the MCU and its resonator. R3 in this image:

Why is it there and what is its function?

# Answer
That resistor limits the drive through the crystal. If the power applied to the crystal is too high then the slope and phase shift at the resonant frequency will not be optimal and at really high drive levels could cause mechanical damage to the crystal (like that shattered wine glass trick).

See good instruction PDF here, section 2.1.
> 2 votes

---
Tags: arduino-mega
---


title: Using SPI without driving MISO

text:
# Question
Title: Using SPI without driving MISO
I am developing an application where an Arduino Pro Mini communicates with a 12-bit ADC over SPI. The communication is one-way, meaning that the ADC will only send data back to the Arduino, not receive any. The MOSI pin is therefore not required in my application, only SCK and MISO.

I wish to know if there is a way to have the Arduino SPI library ignore the MOSI pin, and controlling the clock pin directly. The ADC requires 16 clock cycles to perform one conversion, sending the data back on the last 12 clock cycles. The way I have implemented it is by using SPI.transfer16() to get 16 clock cycles, and storing the return value in a 16bit variable. The downside to this is that the MOSI pin is driven, and I can therefore not use it for other purposes. I would very much like to be able to generate 16 clock cycles without the need for driving MOSI. Any ideas?

# Answer
> 2 votes
In microcontrollers, the GPIO pins have a multiplexer to select what the pin is used for. When you use the Arduino SPI library, the initialization function will set the multiplexer to MOSI for that pin. You should be able to run your own initialization for that pin and overwrite whatever the SPI initialization function did. Just make sure to call your initialization after SPI.begin(). This is the simplest solution.

If that doesn't work for some reason then you can dig into the source code for the Arduino SPI library. This isn't too hard either.

Bitbanging is the hardest solution and shouldn't be necessary for your application.

# Answer
> 0 votes
You are using ADC which I suppose you have no way of changing firmware or anything to modify the protocol.
According to SPI protocol, when *Slave* receives a byte, it sends byte kind of a two shift registers in circular buffer. So even if your ADC finish the conversion it wont start communication protectively the protocol doesn't allow it.
In case if you have other ADC IC which is programmable you can implement your protocol but it wont be SPI it will be your own protocol, so be assure of it.

---
Tags: spi, adc
---


# Question
Title: How can I fix stuttering motors that are connected to ESC's [Arduino Uno]?
Been making a few posts about my drone and i am getting closer and closer to my goal to make it work.

Right now I have a problem with stuttering with all four of my motors (sometimes the motors does not even start but they beep instead). This is the motor and esc I use: https://hobbyking.com/en\_us/mt1806-brushless-combo-include-esc-5030cw-ccw.html

I put together a very quick schematic on how i have everything connected:

So motor connected to the ESC and the ESC grounds go to arduino Gnd, the signal pins from the ESC goes to different pwm pins and the rest of the esc goes to the power distribution where i also insert my 3s lipo battery. From my power distribution i connect two cables to my arduino uno gnd and vin pin.

When I use this very simple code:

```
ESC9.write (100);
ESC6.write (100);
ESC5.write (100);
ESC3.write (100);
delay (2000);

ESC9.write (0);
ESC6.write (0);
ESC5.write (0);
ESC3.write (0);
delay (2000);

```

The motors start like they should but they stutter (some motors move more than others) and as you can see in my code i tell them to stop after 2 seconds to see if i can control them and indeed they stop nicely.

This is a 3 second video on how it looks once I enter my lipo battery:

https://vid.me/XpWg

Is this a case of bad soldering somewhere perhaps or do I need to calibrate my ESC/motor? Codewise I am just using a simple Servo and then I just use the code I posted above. Do I need to add anything else maybe? Since all 4 motors are stuttering/buzzing it is most likely not a problem with the motor/esc i suppose!

My arduino uno is a chinese copy, could that have anything to do with it?

Also I made this post earlier with a little less information but more info about my soldering: All four of my ESC motors stutters when I run it on my Arduino, how can this be fixed?

Appreciate every help and tips!

# Answer
It isn't clear from your diagram or the video what wire thicknesses you've used or precisely how currents are being routed, or how big your battery is.

Let BPG denote the ground terminal on the battery pack, and BP+ the battery's positive terminal.

There should be heavy wire from BPG to the ground pin of each ESC. There should be a signal wire (that is, heavy or light, makes little difference as long as motor currents have their own heavy wires to follow) from BPG to an Arduino Gnd pin.

There should be heavy wire from BP+ to the positive voltage pin of each ESC. There should be a signal wire from BP+ to Arduino Vin.

There should be signal wires from Arduino PWM outputs to ESC PWM inputs. There should be heavy wires from ESCs to motors.

Also, in your code try changing 100 on up to 200 or 250 (or near whatever the ESC maximum setting is) to see if problem persists at higher levels of PWM drive. Also if your battery pack is small, add some more packs of the same voltage in parallel, or try a heavier-duty pack.

*Edit 1:* Check whether each of the motors can work ok by itself. That is, either comment out three at a time, or use if-statements that check button or jumper settings. If all the motors work ok singly, try them in pairs or triples. There are six different combinations of motor pairs, so rather than trying all six of those you might first try the four different sets of three motors at a time, and if that reveals a combination of three motors that fails, try the pair combinations among those three to see if there is some interaction between two motors. If problems occur when testing with fewer than four motors, try swapping motors on to different ESCs, to find out if the problem is due to a motor, an ESC, or the battery. (You can also swap motors on ESCs and test all four at once, but testing with fewer motors going should provide a more systematic problem solving method.)
> 0 votes

# Answer
Beeping noise comes from the motors when the PWM of ESC does not have enough power to rotate the motor. Since you are hearing a noise, this is a good indication that PWM exists.

Now, if you lower your duty cycle, beeping noise should decrease and vice versa. This way, you can know that the arduino is capable of controlling your ESC PWM and duty cycle.

Since you can control duty cycle and you have a PWM and no motion, there are a couple problems that comes to mind.

* PWM of ESC can not follow BLDC rotation speed. So your ESC can't detect back emf of your motor. (From your diagram, I think its a sensorless ESC.) This could happen if ESC voltage sense pin does not work, or there is noise etc. But its unlikely that all ESC are broken.
* You say that sometimes it works and there is stuttering. Well, stuttering exists also if BLDC can't sense back emf correctly so it is issuing the wrong angle at the wrong time and this causes the motor to sometimes go back a bit which appears as stuttering.
* ESC supply voltage drops when motors are running, this causes ESC to shut down/ behave erratically. This happens when you have bad soldering or thin wires.

I would say that the third is the most probable cause.

As for back emf detection, measure motor back emf yourself using your arduino (if you don't have an osilloscope, of course). Send data to PC and see if there is good back emf when you turn the motors (turn them fast using another motor or your hands with a quick motion)
> 0 votes

---
Tags: drone
---


# Question
Title: Arduino Disconnects after router password changes
I am working with arduino Uno R3 connected with EPS8266(http://www.amazon.in/ESP8266-Serial-Wireless-Transceiver-Module/dp/B00O34AGSU?tag=googinhydr18418-21&tag=googinkenshoo-21&ascsubtag=858e5035-7713-403a-942e-487a0fe24800). After router password is changed, it should be re programmed with new password. Is there any another way not to do so repeatedly. I managed 2 SSID for router which one have always unique password. But I think this is not a solution. Is there any technique or idea that says only for particular mac address, the SSID will be opened.

# Answer
Routers have multiple "passwords". I assume you are talking about your wireless encryption key (i.e. WPA/WPA2 key). When the encryption key is changed, you are correct: you have to re-program the ESP8266 with the new key, because it can't learn this information on its own. If this key were broadcast, then your network would not be secure as everyone would be informed of the encryption key.

Why is the key changing? Is there really a need to change the encryption key often?

MAC addresses can be spoofed, so permitting a specific MAC address to "always connect" is not secure.
> 2 votes

---
Tags: ethernet, wifi
---


# Question
Title: LCD from Arduino Starter Kit not displaying text
I've been tinkering with my new Arduino a bit and I was adding an LCD from the starter kit, using information from the eleventh project in the project book, "Crystal Ball." When I connect the Arduino to my computer, the LCD lights up, but no text is displayed on the screen.

Here are some screenshots of my connections:

Finally, here's the code that I uploaded to the Arduino:

```
#include <LiquidCrystal.h>

// Create this display with the pins that I wired
LiquidCrystal lcd(12, 11, 2, 3, 4, 5);

void setup()
{
    // This is a 16x2 display
    lcd.begin(16, 2);

    lcd.print("hello!");
}

void loop()
{
}

```

edit: Additionally, I tried adding a potentiometer to control the display, but to no avail. Below is the wiring for this (back pin goes to the third to last pin for the LCD).

# Answer
In the end, it turned out being a combination of what Andre's Answer suggested, as well as the "brightness" of the LCD. My potentiometer seems to have kind of a "stick" to it, meaning that to get the LCD to move to the value necessary, I had to crank the thing harder than normal, then it started displaying my text.
> 1 votes

# Answer
Looking at your first picture it looks like you are wired on 12 and 13 not to 11 and 12 like your sketch specifies.

Double check your wiring against this : https://www.arduino.cc/en/Tutorial/HelloWorld

Also take your multi-meter out and buzz your connections.
> 1 votes

---
Tags: arduino-uno, lcd
---


# Question
Title: Why do we need to amplify the signal of an electret?
I do understand from my reading that I should amplify the signal from an electret to be able to read it with an Arduino. I'd love to know the science behind that, why should we amplify the signal to be able to get a correct reading ?

# Answer
Arduino (or any chip that uses ADC for that matter) has a resolution. For example, arduino analog read divides 5V to 1024 levels. A.k.a 0V -\> 0, 5V-\>1024. That gives you 4.8mV per level.

Now assume that you want to read the voltage fluctuation of a very low voltage power supply that fluctuates from 0 mV to ~8mV. What does the arduino read? You'll see either 0 or 1. So basically, you just can't successfully read that low voltage with your current setup.

Now, if you use an analog OPAMP and amplify that signal to 5V, (0mV-\>0V, 8mV-\>5V) then you can use all 1024 levels available to you, provided by arduino.

That's why you need to amplify the signal.
> 0 votes

---
Tags: analogread, sound
---


# Question
Title: Arduino Uno + USB Host Shield + Motor Shield
We have an obstacle avoiding robot, and we decided to upgrade it by controlling it with a PS3 controller, so I am asking if above the Arduino UNO we can attach the USB host and above the Host attach the motor shield where the motors are connected to?

# Answer
> 0 votes
You need to check the I/O used by each shield to make sure there is no conflicts.

---
Tags: arduino-uno, arduino-motor-shield
---


# Question
Title: How is the bootloader activated when device is running?
For the sake of specificity I am referencing my question to Arduino. It applies to all AVRs with hardware USB and a bootloader though.

The bootloader is capable of receiving new program data over the USB interface, and, after programming, releases the interface. It can then for instance be used for the emulation of a serial port, or even register as a HID.

I know what a bootloader is and how it reads program data from the PC and how it writes it to the devices flash memory.

I am asking how the bootloader is triggered again if the user wants to upload a new program. The PC needs to reset the AVR in order to fire up the bootloader. How is this reset instruction implemented in Arduinos with built-in USB hardware (e.g. the Arduino Micro)? Is it solved by performing a software reset after the DTR line goes low just as in e.g. the Arduino Nano, except that the DTR line only exists in software?

**EDIT**: If that is the case, the solution is unique to Arduinos. I was thinking that there would be some standard way of doing it common to all AVRs.

# Answer
> 6 votes
On microcontrollers with bootloader (not just AVRs), the bootloader is a separate executable in flash, and it's typically the program that runs on system startup. The application will have a special trigger, such as a button sequence, getting a specific byte sequence over I2C, or really anything that will tell the bootloader to enter into its "update" mode. From there, the bootloader will have some communication (I2C, USB, WiFi, serial, etc) to download and the flash the new application image.

This link has more information about the Arduino bootloader

> On the PC side, to trigger a reset on the RESET pin, the PC (avrdude.exe or GNU/Linux equivalent) opens the serial port to Arduino when your press upload and the code is ready to upload. This causes the Data Transmit Ready (DTR) line of the USB/TTL chip to go LOW. The Arduino board has a capacitor charging circuit that uses this LOW (charging the capacitor) signal to momentarily pull down the RESET line of the ATMEGA328P chip before returning it to HIGH (capacitor charging completes). So Arduino resets each time its serial port is opened.
>
> Upon reset, Arduino enters the bootloader.
>
> The bootloader looks at the source that caused the reset. There are several sources that can cause a reset. If the reset was caused by the RESET pin, then it waits for one second for the PC to send in commands. When it receives valid commands, it will start accepting new Arduino code in HEX format and erase the existing code to load new one. If it doesn’t receive valid commands, it times out after one second and triggers a Watch Dog Timer (WDT) reset.

For Arduinos with built-in USB, such as the Micro, the Arduino library (firmware) triggers the system reset. There's a little chunk of code that looks for the virtual COM port to open at 1200 baud and then close. When that happens, the code triggers a system reset (by writing a register, typically) which launches the bootloader.

> Rather than requiring a physical press of the reset button before an upload, the Micro board is designed in a way that allows it to be reset by software running on a connected computer. The reset is triggered when the Micro's virtual (CDC) serial / COM port is opened at 1200 baud and then closed. When this happens, the processor will reset, breaking the USB connection to the computer (meaning that the virtual serial / COM port will disappear). After the processor resets, the bootloader starts, remaining active for about 8 seconds. The bootloader can also be initiated by pressing the reset button on the Micro. Note that when the board first powers up, it will jump straight to the user sketch, if present, rather than initiating the bootloader.
>
> Because of the way the Micro handles reset it's best to let the Arduino Software (IDE) try to initiate the reset before uploading, especially if you are in the habit of pressing the reset button before uploading on other boards. If the software can't reset the board, you can always start the bootloader by pressing the reset button on the board.

Personal story: I wrote an I2C bootloader for the PIC32. The only communication with the device was through the I2C bus. The main application had a special 3 byte trigger that would set a non-initialized variable in RAM, and then trigger a system reset. The bootloader, which runs on system startup, would check that variable and if it was set, would wait for commands over I2C to download and flash the new application image. That variable in RAM had to be specially marked as non-initialized, otherwise the C startup code would clear it and the bootloader would never update.

The bootloader also calculated a CRC32 over the application image to validate it before attempting to boot. If the calculated CRC32 didn't match the stored CRC32 (which was part of the application image), then the bootloader would enter its firmware update mode. This was a guard against trying to run a corrupted firmware image, which could happen if power was pulled during the update process.

---
Tags: avr, bootloader
---


# Question
Title: Ethernet Shield: Failed to configure Ethernet using DHCP
I am currently making a design that uses the Arduino's Ethernet shield. I am using the PushingBox API for Arduino, and have tried it with my Arduino Mega (2560) with the ethernet shield attached to the router. When I did this, however, it displayed a message on my serial monitor saying `Failed to configure Ethernet using DHCP`. The model for my Ethernet Shield is a W5200 Seeed Studio Ethernet Shield, and I am using the libraries that Arduino provides. I do not have an SD card inserted and the DHCP on all other wired devices works. Any help is greatly appreciated.

The code (in case):

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

  /////////////////
 // MODIFY HERE //
/////////////////
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x19 };   // Be sure this address is unique in your network

//Your secret DevID from PushingBox.com. You can use multiple DevID  on multiple Pin if you want
char DEVID1[] = "{[I have replaced this with my DevID]}";        //Scenario : "The mailbox is open"

//Numeric Pin where you connect your switch
uint8_t pinDevid1 = 3; // Example : the mailbox switch is connect to the Pin 3

// Debug mode
boolean DEBUG = true;
  //////////////
 //   End    //
//////////////

char serverName[] = "api.pushingbox.com";
boolean pinDevid1State = false;                // Save the last state of the Pin for DEVID1
boolean lastConnected = false;                 // State of the connection last time through the main loop

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  Serial.begin(9600);
  pinMode(pinDevid1, INPUT);

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    Serial.println("Please reconfigure the settings and try again.");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }
  else{
    Serial.println("Ethernet ready");
    // print the Ethernet board/shield's IP address:
    Serial.print("My IP address: ");
    Serial.println(Ethernet.localIP());
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
}

void loop()
{
      ////
      // Listening for the pinDevid1 state
      ////
      if (digitalRead(pinDevid1) == HIGH && pinDevid1State == false) // switch on pinDevid1 is ON
      {
        if(DEBUG){Serial.println("pinDevid1 is HIGH");}
        pinDevid1State = true;
        //Sending request to PushingBox when the pin is HIGH
        sendToPushingBox(DEVID1);
      }
       if (digitalRead(pinDevid1) == LOW && pinDevid1State == true) // switch on pinDevid1 is OFF
      {
        if(DEBUG){Serial.println("pinDevid1 is LOW");}
        pinDevid1State = false;
        //Sending request to PushingBox when the pin is LOW
        //sendToPushingBox(DEVID1);    //Here you can run an other scenario by creating a DEVID2 variable
      }

      //DEBUG part
      // this write the respons from PushingBox Server.
      // You should see a "200 OK"
      if (client.available()) {
        char c = client.read();
        if(DEBUG){Serial.print(c);}
      }

      // if there's no net connection, but there was one last time
      // through the loop, then stop the client:
      if (!client.connected() && lastConnected) {
        if(DEBUG){Serial.println();}
        if(DEBUG){Serial.println("disconnecting.");}
        client.stop();
      }
      lastConnected = client.connected();
}

//Function for sending the request to PushingBox
void sendToPushingBox(char devid[]){
  client.stop();
  if(DEBUG){Serial.println("connecting...");}

  if (client.connect(serverName, 80)) {
    if(DEBUG){Serial.println("connected");}

    if(DEBUG){Serial.println("sendind request");}
    client.print("GET /pushingbox?devid=");
    client.print(devid);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(serverName);
    client.println("User-Agent: Arduino");
    client.println();
  }
  else {
    if(DEBUG){Serial.println("connection failed");}
  }
}

```

If the code for the DHCP error is removed, it does display an external IP address, but actual HTTP requests do not work. I tried port forwarding and that did not work either.

EDIT: Now, unusually, it gives me an IP address WITHOUT the ethernet cord connected.

# Answer
If I understood your problem correctly then you might want to check this out, it's more or less the same thing :D

DHCP Failing on Arduino Uno
> 1 votes

---
Tags: arduino-mega, ethernet
---


# Question
Title: Bidirectional communication between Arduino and Raspberry Pi over USB possible?
Is it possible to have bidirectional communication betweeen an Arduino Uno Rev 3 and a Raspberry Pi Modell B+ running Rasbian? They're connected ofer USB, and it would be good if I could use Python on the Pi.

# Answer
Yes. The Arduino Uno implements a serial protocol inside the USB signal using hardware. This is how it is built. The Linux side is a bit more complex as there are many USB protocols. Here is a howto which talks about the Linux side of the Arduino / Linux connection.

To be clear, Rasbian is a derivative of Linux.
> 1 votes

# Answer
Yes, it is possible to have a USB serial communication between a raspberry pi and an Arduino. And it is much more easier when using Python on the raspberry pi.

Python has a serial library within it's standard library which you can import on the raspberry pi and then use it to send or receive data to/from the Arduino or the raspberry pi.(Just connected via USB cable).

Here is the link for a very similar requirement on YouTube.
> 0 votes

---
Tags: arduino-uno, serial, usb, python, raspberrypi
---


# Question
Title: Serial communication between arduino and raspberry pi works once, then stops working
I'm using a Arduino Uno Rev 3 connected over usb to a Raspberry Pi Modell B+ running Rasbian.

Here ist the arduino code:

```
int input = 0;
String command = ""; // beinhaltet den aktuellen befehl
int Action = 1;

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

void loop() {
  if (Serial.available() > 0)
  {
        input = Serial.read();
    char currentChar = input;

    if(currentChar  == '!') // frage nach trennzeichen
    {
      Serial.println(command);
      //Serial.write(Action);
      Action = command.toInt();

      command = ""; // befehl wieder leeren
    }else
    {
      command = command + currentChar ; // falls noch kein trennzeichen vorhanden, erweitere kommando
    }
    }
}

```

Here is the Raspberry Pi code (in python)

```
import serial
from time import sleep as sleep
ser = serial.Serial('/dev/ttyACM0',9600)
s = [0]
while True:
        ser.write(b'2!')
        a =  ser.read(1)
        print a
sleep(2)

```

It always works if once after the code was uploaded to the arduino, but if I stop the script on the pi and restart it it stops working. What is the problem here?

# Answer
> 2 votes
"It always works if once after the code was uploaded to the arduino...." Whenever you you reset the arduino the link between the arduino and the rasperry pi is broken momentarily thus causing the code on the raspberry pi to hang/ffreeze and not responding/ showing any valid results.

Try giving a keyboard interrupt by ( Ctrl + Z ) and restart the python script and that should work just fine!

---
Tags: arduino-uno, serial, raspberrypi
---


# Question
Title: Looking for learning resources to teach the "principles" rather than "follow this" projects
I just got the Arduino starter kit as my background is software developer (C++, python, etc) and I'm interested to get into the electronics side, and I love LED effects and home automation of all kinds. As such I'm quite comfortable with the type of C programming required (loops etc) but need to learn the principles of electronics.

Can you suggest any resources (websites, tutorials, books - I'm willing to pay for books if they are useful) whose focus is teaching the principles as well as doing specific projects?

The kit came with the "Arduino Projects Book" but I don't really like it as it's focused on "do this, do that, put the circuit together according to this diagram" rather than explaining the principles first. For example I did the "Spaceship Interface" (light up different LEDs in different patterns based on whether a button is pushed or not) and it introduces things like "You'll also need to add a 10k ohm resistor from ground to the switch pin that connects to the Arduino \[...\] it connects the pin to ground when the switch is open so it reads LOW when there is no voltage coming in through the switch". I understand that in principle I think, but why is it 10kohm, why do we have to connect it using a resistor when the switch is open, etc. (I see that we have to have a complete circuit and I'm assuming it is because the 10kohm is a "default" branch of most resistance with nothing else connected?)

I'm asking about general principles rather than the specific case of why do we have a 10kohm resistor in this case, but this is a pretty good example early in the book.

# Answer
> 3 votes
Welcome to the Arduino world!

First I'd like to try to answer your question: (*This explanation does not apply to his situation as explained in the comments, but, I guess, it's a fun and useful read so I'll leave it here*)

> "You'll also need to add a 10k ohm resistor from ground to the switch pin that connects to the Arduino \[...\] it connects the pin to ground when the switch is open so it reads LOW when there is no voltage coming in through the switch". I understand that in principle I think, but why is it 10kohm, why do we have to connect it using a resistor when the switch is open, etc. (I see that we have to have a complete circuit and I'm assuming it is because the 10kohm is a "default" branch of most resistance with nothing else connected?)

I haven't seen your circuit but I think I know the deal here. The author is basically telling you to create a *pull-down* circuit. What this does is, what it says. It pulls down the voltage on arduino pin to GND. Now, why would you want to do that? I think because in your project, the author was reading analog values from that pin. He wants the pin pulled down because otherwise when the switch is open, the pin would be *floating* i.e. not connected to anything. Floating pin means that you will get random analog readings from that pin. Basically, if you don't connect that pin to any source/sink, it will act as an antenna. You will get noise. (You can actually use this to create random numbers for your arduino!)

Now, about that 10kOhm resistor: Its depends on two things. First, if you put a low value resistor, then you will draw lots of current from the supply to the ground when the switch is closed. You normally don't want that, why spend energy more than you have to? So, you pick any big resistor that you can possibly pick. But how big can you really put there? This depends on the analog read pin's current consumption. Whenever you do an ADC (analog to digital conversion) a.k.a analog read, your pin sinks/supplies tiny amounts of current and samples it to determine voltage. Atmel datasheet says that:

As you can see, the good guys in Atmel already did some tests and determined that with the current Atmega328p (Arduino-UNO chip) chip, a source of 10kOhm internal resistance is sampled the best. (When you open the switch, the 10kOhm resistor is basically a 0V source with 10kOhm internal resistance)So basically, I guess, that's why the author used 10kOhm. Could you have used 20kOhm instead? Of course...

Now about the electronics book thing. The best practice with electronics is to both read and do. So, whatever book you pick, make sure it has examples and explanations that you can try. Don't buy a highly theoretical book with lots of math and physics. Don't use a simple do-this do-that book either. I can't provide you a single good book, because that's not how I prefer to learn. But I might have some good suggestions for you if you prefer to study like this as well:

* Learn the basics or R,L,C. Study filters, energy, their differential equations etc. Any book, website will do.
* Use software and simulate theoretical/explanatory circuits. LTSpice is best. For bigger projects, something like MATLAB is better.

If you do that, you'll gain some insights on how things actually work.

* Move on to transistors: BJT, MOSFET etc. What are they and how they behave?
* Combine transistors and R,L,C to create some digital-analog circuits. How do you make a RAM cell? Can you make an arithmatic logic unit?

At this point, you should be comfortable with most elements of electronics.

* Since you started with arduino, study RISC/CISC architechture. What actually is a microcontroller?
* Since you know software, try using assembly code to turn on and off some leds. This is where you meet software and hardware at the lowest possibly level you can.
* Try to make your own microcontroller using FPGA! (I've done this -it was a simple and not-so-useful CPU but nevertheless it provided insight. You can invent your own assembly language!!)

At this point you should be able to understand most basic arduino projects.

* Read atmega datasheets.
* Read Transistor, motor driver IC etc. any driver datasheet and search the terms on google. What do they mean?

After that you can do this:

* Pick a project, and do it from scratch. Without, copying any circuits from the internet. Can you place atmega chip to work stand alone, away from arduino board? Can you use that and make for example a BLDC driver?
* Pick a project and ask stackexchange. (Well, obviously). There are some really brilliant people here that are willing to help. Personally, I feel I'm learning better if I try to answer other peoples questions and ask questions.

I guess the downside/upside is you never stop learning. Electronics combined with software is a huge area of expertise.

So I wish you Good luck!

# Answer
> 2 votes
I see people are voting to close this as too broad. Well, it is broad, but I'll try to give you some pointers. I used to wonder this stuff too, like "why use 10k and not 20k or 5k?". A good starting point is to watch some of Dave Jones' EEVblog videos.

For example Designing a Li-Ion Battery Gauge with the LM3914 - EEVblog #204 \- this is already 5 years old. He has done a lot of them. This particular one describes using the LM3914 chip to make a battery gauge, and in the middle he works through the resistor values using Ohm's Law.

Another entertaining and informative blog is Afrotechmods. He also goes into detail but in a humorous way.

Also try M J Lorton's blog.

My only problem with videos is, if you are trying to reproduce some of their stuff you end up having to rewatch a (perhaps lengthy) video and pause it from time to time to copy stuff off the screen.

For this reason I made some posts of my own on the Electronics part of my own forum. (Some of the more popular ones are also here in Stack Exchange as reference questions, for example How do you use SPI on an Arduino?).

You could also look at the Adafruit and Sparkfun tutorials (amongst many others).

---
Tags: programming
---


# Question
Title: Arduino-RS232 converter baud rate problem
i have built a TTL/RS232 converter to send strings via RS232 using an Arduino nano, following the tutorial:Arduino-RS232. My problem concerns the transmission baud rate, because in the tutorial it is suggested a short script which manually generates the code which will become the RS232 signal. In this script some constant delays are used, i.e. "bit9600Delay 100 " and so on. These delays are set for a baud rate of 9600, but i need to double it to have a baud of 19200. Is it enough to divide by two those constant values or should i use a different method? Thank you very much

# Answer
It is never good to base code on delays instead of intervals. This is especially true for faster intervals where the execution of the code its self consume a significant portion of the interval. Also note, some protocols only occasionally resynchronize. RS232 resynchronizes after each byte (about 8 bits of data). So any accumulated delay errors may impact the integrity of the bits furthest from the resynchronization event.

Instead of delays use the Arduino's built in hardware to send and receive RS232 communications. The hardware is designed to work independently of code execution and will out perform software implementations especially for the faster baud rates.
> 2 votes

# Answer
This Arduino sketch is a wonderful opportunity for you to learn the very basics of serial communication.
You should be very careful scaling the constants given in any baud rate program (whether using a hardware or software UART) as they are normally off by some small percentage, and without understanding the implications you may eventually introduce timing errors. There is a great description of the timing sensitivities in this Picaxe note.

The table below shows the actual bit times for various baud rates:

Notice here that for 9600 baud the sketch uses a constant which will use a 100 uS delay function for the bit times. From the table above you can see that this is slightly inaccurate, and the more correct delay would be 104 uS. This is an error of about 4%.

Would this error prevent successful reception of characters in the sketch? Single characters with inter character spaces more than 1 character time, no ....but if you sent a string of characters end to end with no gaps this sketch would fail on receive.

Scaling the constant for 19200 baud --\> 100/2 gives 50 but the bit time for 19200 is actually 52 uS, so again an error, this time of about 1%. If we scaled the constant (100) for 115200 --\> 100/12 gives 8.3 uS while 104/12 gives 8.7 uS for an error 4.5% or close to 0%.

There is IMO an error in this sketch for the serial receive routine, since it's hard wired to expect 2 stop bits. Any concatenated characters separated by only one stop bit will fail (you miss the second character start bit).

```
int SWread()
{
  byte val = 0;
  while (digitalRead(rx));
  //wait for start bit
  if (digitalRead(rx) == LOW) {
    delayMicroseconds(halfBit9600Delay);
    for (int offset = 0; offset < 8; offset++) {
     delayMicroseconds(bit9600Delay);
     val |= digitalRead(rx) << offset;
    }
    //wait for stop bit + extra
    delayMicroseconds(bit9600Delay);     ....hard wired two stop bits
    delayMicroseconds(bit9600Delay);     ....or 1 stop and 1 bit time gap
    return val;
  }
}

```
> 1 votes

---
Tags: serial, rs232
---


# Question
Title: How to send SMS from an Ethernet shield via SMS Gateway?
How do I send SMS from an Ethernet shield via SMS Gateway?

The site Clickatell provides free SMS.

Does anyone know how to do this or is there some other way to do it?

# Answer
> 2 votes
First contact Clickatel's support and ask them how to use their API, make yourself familiar with it.

Then when you know that you connect your Arduino to your ethernet shield, I'm just gonna assume you got Arduino's original shield, because you want to support the arduino foundation.

http://arduino.cc/en/Main/ArduinoBoardEthernet if you have the standalone board. http://arduino.cc/en/Main/ArduinoBoardEthernet if you have the shield board.

# Answer
> 1 votes
Open an account and try to implement their API using something like Chrome REST client. Then do the same through the ESP8266. I would personally relay it through my own web service/ url. You could also take a look at: http://www.instructables.com/id/Send-SMS-from-Arduino-over-the-Internet-using-ENC2/

# Answer
> 0 votes
Thanks to the moderator for telling me to give an improved answer, Here it goes-\>

From your question I infer that you want to send a SMS from your Arduino with an Ethernet Shield.

My suggestion to you is to use a service "CAYENNE". It's a cross platform service for IOT.

You can create a **FREE** account on it by visiting their website :here

You will be provided with a **KEY** to use with your devices

Then all you have to do is connect your Ethernet Shield and upload Cayenne's BASIC code to your Arduino so that it would link the key assigned to you to the account.

You can now Control your Arduino from any APP or directly through their website as provided above.

As far as SMS is concerned all you'll have to do is to add a trigger (GO TO OPTIONS -\> TRIGGERING AND ALERTS ) and select the notify option(Add SMS here)

Then you just have to enter the country code along with the phone number and when a particular event of your choice occurs you will be notified via SMS.

Hope this helps :) Feel free if you have any further doubts.

---
Tags: arduino-uno, arduino-mega, ethernet
---


title: Connecting ethernet shield to computer

text:
# Question
Title: Connecting ethernet shield to computer
What configuration settings do I need to change on my computer to use the ethernet shield mounted on my Arduino UNO as I don't want to connect the ethernet shield to the router?

# Answer
First off you need a basic understanding of TCP/IP networking. One you have that you need to:

1. Allocate yourself a new subnet - one that's not your normal local network (say 192.168.1.0/24)
2. Assign an IP in that subnet to your Arduino (say 192.168.1.1)
3. Assign a different IP in that subnet to your PC (say 192.168.1.2)
4. Configure your Arduino's sketch with it's IP address and netmask
5. Configure the PC's Ethernet interface with it's IP address and netmask
6. Connect the two together with a suitable cable. If the PC's Ethernet port doesn't have auto-direction sensing you will require a special cross-over cable where TX+/TX- and RX+/RX- are swapped over.
> 1 votes

# Answer
You can try the easy way This always works for me :D

1. Connect the shield to the Arduino and plug in the cables to the PC(RJ45/Ethernet).
2. Go to network communication center.
3. Go to change adapter settings.
4. Select Ethernet(Arduino) and wireless(Wifi) /(internet source) and right click.
5. Click bridge connections.
6. Wait for a few seconds.
7. **Enjoy**.
> 1 votes

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


# Question
Title: Cannot directly connect Arduino Ethernet to PC
I have been following various tutorials (especially: this) to connect an Arduino Ethernet board to my Ubuntu PC via Ethernet directly.

The IP address of the computer was found to be 10.100.31.128, and so I tried addresses in this range (10.100.31.67, 10.100.31.121, ...) without success. DHCP also doesnt seem to work. For the MAC address I used the sticker on the back of the board. I am using a patch cable, maybe that's the problem?

# Answer
> 1 votes
Network problems can be complex. If these suggestions are not right I can change the answer later if other solutions present themselves.

If you are connecting two Ethernet devices directly you may need a cross over cable.

To test your connection with out using IP addresses, try to follow what is discussed in this answer where the MAC address is used on a Ubuntu system instead of the IP address.

You also might try using wireshark to monitor the Ubuntu box's Ethernet port.

# Answer
> 0 votes
When you connect your Ethernet Shield to your Ubuntu PC your PC 'looks' at the Ethernet shield as if it were a router and therefore tries to connect to it as an internet source, thus it tries to get an IP and other related stuff from the Ethernet shield.

**BUT**

What you want is that the Ethernet shield should use the ubuntu PC as an internet/local network source. For this you must have active internet on your PC from Wifi/ USB data etc.

You will have to **BRIDGE** the connections of your Ethernet shield and your internet source in order to do so.

The link to accomplish Bridging networks in Ubuntu is here

When you bridge two Ethernet networks, the two networks become one single (larger) Ethernet network. Thereby making the Ethernet shield a part of the larger network (Internet in this case). You can now upload any of your sketches onto the Arduino as per your requirements and accomplish your task.

---
Tags: ethernet, web-server, tcpip
---


# Question
Title: Adding external power supply to any arduino connected component
I have an Arduino Pro Mini 3.3v and the voltage is too small for my buzzer to ring loudly. I want to add a 9v battery to power the buzzer.

This is my current circuit:
Arduino (pin 9) =\> Buzzer +ve
Arduino Gnd =\> Buzzer -ve

I want to power the buzzer using an external 9v battery but I have no idea how to implement it in the circuit. All I know is that the ground should be common.

What next?

# Answer
> 1 votes
You can use an NPN transistor for this purpose.

All you have to do is connect it this way

Obviously use a buzzer instead of the motor and pin 9 instead of 4 :D

Arduino (pin 9)==\>1k-10k Resistance==\>Transistor base

Buzzer +ve ==\> + 9V

Buzzer -ve ==\> Transistor collector

Transistor Emitter ==\> battery -ve ==\> Arduino GND.

So now whenever you set the pin 9 to HIGH the transistor would allow current to pass through it from collector to emitter and your buzzer would work just as you wanted.

# Answer
> 0 votes
Use a MOSFET. They are like little electronic switches. They will work fine with the 9V that you want to use.

Tutorial.

---
Tags: power, arduino-pro-mini, battery, wires, buzzer
---


# Question
Title: ArduCam ESP8266 and (Not-Mini) OV2640 Camera Module interface?
I bought ArduCam ESP8266 and a OV2640 Module. However it is not the mini-version. At the time it didn't seem like it was necessary.

I might have made a big mistake here.

The board has 8 female pins specifically for the camera module. But the OV2640 module has 20 male pins. A mini-version of the same camera leaves 8 pins, and has a nice interface.

I might have to send this back and get that one, but I want to know if it's possible to simply use this one and wire it up with certain pins instead?

Links to the two products to be specific: http://www.arducam.com/camera-modules/2mp-ov2640/ (Camera) http://www.arducam.com/arducam-esp8266-uno-board-arduino-camera/ (Board)

Thanks for your help,

Fred

# Answer
No, you can't "mix and match" like that. The 8-pin header has I2C and SPI on it for a "cooked" video interface. The 20-pin interface has the "raw" camera CSI interface.

The difference is, the mini version has its own small video processor and FIFO chip on it which processes and buffers the video image allowing you to take a picture then slowly stream that data back through to the slow Arduino at a speed it is comfortable with. The non-mini version doesn't have that and relies on the host controller board having enough power to process a live CSI video signal, which the Arduino cannot do.
> 1 votes

---
Tags: arduino-uno, sensors, esp8266, pins, spi
---


title: Motor shield for Arduino Nano ATmega328

text:
# Question
Title: Motor shield for Arduino Nano ATmega328
I am looking for a cheap and not so space consuming motor shield for my Arduino Nano ATmega328. I would like to charge the whole thing with a 9V battery. The shield must have at least 2.1A of output current so I can run 3 brushed DC motors on it. There will also have to be some pins left for a Bluetooth card and 3 analog pins for sensors.

Do you know any shields that meet my requirements?

# Answer
**In short:**

Nano + Shield = no possible

---

> \[...\] 9V battery. The shield must have at least 2.1A of output \[...\]

You can't invent power out of nowhere.

---

**Options for the shield**

**Option 1:**

Use an other Arduino. It will simplify everything.

**Option 2:**

Use a Nano to Uno adapter.

**Option 3:**

By an Uno shield and connect it pin by pin to the Nano.

**Option 4:**

Use MOSFETs. They'll work fine for what you are trying to do.

---

**Options for powering**

**Option 1:**

Use a 2s lipo. Voltage is above 5V so you have to reduce it with a down converter, but you should have enough juice for the motors.

**Option 2:**

Use a *lot* of AA, some in series to augment the voltage and then in parallel to augment the current.

**Option 3: (just the the crazy minded)**

Use a lead-acid battery (aka car battery).
> 1 votes

---
Tags: arduino-nano, atmega328, arduino-motor-shield
---


title: Arduino as wireless network host

text:
# Question
Title: Arduino as wireless network host
I have a rather simple question, which I cannot seem to find the answer to online.

I would like to host a wireless network using an arduino. Other devices could connect to and communicate with the arduino. Could I do that with a shield like this?

Also, once a device (say a phone) is connected, how would it go about requesting a web page, or other information?

Thank you!

# Answer
> 2 votes
Yes!

You can absolutely do the above said task with the shield that you provided information about.

All you have to do is to connect the Shield to the Arduino and upload the WiFiWebServer sketch from the Arduino's examples in the WiFi library!

Then you'll have to replace the SSID and Password with your WiFi's password.

Once uploaded, then you'll get your Arduino's (Server's) IP Address on the Serial monitorl.

Note the IP Address and open any browser on any device of your choice.

**NOTE**\- Your device must be connected to the same WiFi network to which your Arduino is connected to. If you wish to access the Arduino server from outside your LAN then you'll have to forward/open a port on your WiFi router and direct it to the IP Address of your Arduino. But I am assuming that you just want to access it from your LAN therefore the port forwarding can be ignored.

You'll see the default webpage in the Sketch which you can change/edit as per your own wish by using HTML.

Here's the link to the detailed explanation from arduino.cc itself.

Coming to the Second part of your question: "Also, once a device (say a phone) is connected, how would it go about requesting a web page, or other information?"

Well once the server is started on the Arduino all you do is type the IP of Arduino in the browser of the device and then the browser sends a HTTP request to the server.(This is the same way in which the browser sends requests to any other website or server like google/youtube/stackexchange . It is same for all ).

---
Tags: wifi, wireless
---


title: Why is the loop() stopping?

text:
# Question
Title: Why is the loop() stopping?
I would like to move my servo motor (SM-S2309S) between random angles. In order to do so, I used this simple code:

```
#include <Servo.h>
Servo servoMain; // Define our Servo

// SM-S2309S angular speed
float speed = 0.12/60;

void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * int(from-to));
}

void setup()
{
   servoMain.attach(10); // servo on digital pin 10
   Serial.begin(115200);
   // move to center as a start
   servoMain.write(90);
   delay(1000);
}

void loop()
{
  // the previous angle, initially set as center (per the setup() call)
  static int oldangle = 90;
  // apparently 15 to 165 deg is a safe range
  int newangle = random(15,165);
  Serial.println(newangle);
  move(oldangle,newangle);
  oldangle = newangle;
}

```

It starts by placing the arm in the center (in the `setup()` function) and then should generate a random number (the new angle to go to), in a loop.

What I get is the initial position, then two moves (counterclockwise, then clockwise). The output on the serial console shows `22` and `64`, which is consistent with the two moves.

**Then everything stops.** There is no error message on the console (I do not expect one to be, but I am not sure if there could be any feedback from the Arduino, being a complete beginner). **What can be the reason for this stop, after two successful loops?**

# Answer
> 5 votes
Just a **small** mistake! Not much big of a deal :D

In the move function

`void move(int from, int to)
{
 // initiate the move to the new angle
 servoMain.write(to);
 // wait for the movement to actually happen over the actual angle to move through
 delay(1000 * speed * int(from-to));
}`

suppose the values passed are 20, 35 then the last line would be 1000\*speed\*(-15) Which is negative therefore the arduino delay function converts the - signed bit to a very large unsigned number.

All you have to do is to take the magnitude of from - to ie |from - to | by calling the abs() function.

your move function would look like this:

`void move(int from, int to)
{
 // initiate the move to the new angle
 servoMain.write(to);
 // wait for the movement to actually happen over the actual angle to move through
 delay(1000 * speed * abs(int(from-to)));
}`

Just alter your move function or copy mine and you'll have no problem at all!

---
Tags: arduino-uno, programming, servo
---


# Question
Title: Programming ATMega328p using VP812 programmer (for AVR/Atmel chips)
I bootloaded an ATMega328p (the one that uses the basic Arduino bootloader). Then, I used the VP812 for dumping other programs written in C (in Atmel Studio).

The process of erasing, blank test, programming and verification are all working fine and it seems that the program is actually being flashed. However, when I insert the same chip (controller) back in the Arduino Uno board, the controller doesn't function as programmed. Also, I am not able to dump any other example sketches.

1. Does this mean that the chip is damaged?
2. Does using the bootloaded chip with VP812 cause such problems?

Also, I used the "Write Fuse" option with the standard fuse configuration (all marks checked) in the VP812 configuration dialog box. Did this setting in any way create the problems I am facing now?

# Answer
> 1 votes
Yes - the settings created this problem. You have erased and disabled (via default fuses) the bootloader. It means that your application will run perfectly fine on an Arduino board, but you will not be able to flash over USB.

If you want to use Arduino USB bootloader again then you have to follow this guide

---
Tags: avr
---


title: Several Piezo contact mics with Arduino

text:
# Question
Title: Several Piezo contact mics with Arduino
I'd like to connect about 6 contact mics to my arduino and receive simultaneous signals to be used in my computer for an art installation.

Nonetheless, I don't know what's the ideal way to go. Shall I use Analog pins or Digital? How should I connect them - what schematics shall I follow? I read that ADC is CPU intensive, but I couldn't really find any viable alternative that explicitly shows the Digital deal.

Can I connect several contact mics to different analog pins and receive their input simultaneously as shown here? If this works, then it's perfect.

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

# Answer
> 1 votes
simulate this circuit – Schematic created using CircuitLab

A piezo element can be connected to an analog input (A0 for example) of your microcontroller, but extra resistors are advisable if you wish to have a digital sample that is linearly proportional to the element's alternating voltage.
Andy's caution about over-voltage is relevant too - these elements can produce voltages far greater than your Arduino's DC supply voltage. Such over-voltage can cause damage. Resistor R3 helps limit potential damage.
Each piezo element will require its own set of three resistors (duplicates of R1, R2, R3). Many microcontrollers have multiple analog inputs - you can have as many piezo circuits as there are analog inputs. You cannot sample them all simultaneously, since most microcontrollers usually have only one analog-to-digital converter, which is switched between its various analog inputs by program control. A piezo element would have to be sampled, then switched to the next element for sampling, then the next....etc.
Sampling can be done fast enough that "audio" (however you define it) is fairly represented by the digital sample stream. However, be aware that processing these audio samples may be beyond the speed capability of simple microcontrollers like Arduino. That part is up to you.
Be aware that piezo elements make poor microphones. Units mounted in plastic shells are designed to **output** audio tones, and have significant resonant peaks. Frequency response is not flat, as required by a proper microphone.

---
Tags: piezo
---


# Question
Title: Code is supposed To extract data between * ie *989*= 0989*; Runs only once then doesn't please help
```
void loop() {
       char *stptr=&string[0];
       if(Serial.available() > 0)
       {
          data = Serial.read();
          if(data=='*')
          {
            ib=1;jb=0;
            string[0]='0';
            //Serial.print("GOT INTO IF");
            while(string[ib-1]!='*')
            {
              //Serial.print("Got into reading while");
              //Serial.print(string[i]);
              if(Serial.available() > 0)
              {
                if(string[ib]!='*')
                {
                  string[ib]=Serial.read();
                  ib++;
                }
              }
            }
         }
      }
}

```

# Answer
> 0 votes
Something like this should work:

```
void loop()
{
    char *stptr = string;
    if (Serial.available()) {
        data = Serial.read();
        if (data == '*') {   // Check for starting *
            *stptr++ = '0';  // Copy '0' to string

            // Loop until: no data in port, or second * received
            while (Serial.available() && '*' != (data = Serial.read())) {
                // Copy to string
                *stptr++ = data;
            }
            // Terminate string
            *stptr = '\0';
        }
    }
}

```

---
Tags: serial, uart
---


# Question
Title: Why does the serial monitor needs to be repeated a command?
I am experimenting with the serial monitor in an Arduino Uno. My project consists in a simple LED turning on and off at will with the commands "ON" and "OFF" respectively.

To achieve this, I use an HC-06 Bluetooth module, but because of the nature of the test I decided to disconnect it and 'debug' my project using the serial monitor as an equivalent.

The circuit has the following connection table:

**LED +:** Pin 12 on my Arduino. **LED -:** GND on my Arduino.

...as you can see, I have tried to simplify as much as I can the circuit, as I wanted to make sure I didn't have wire problems.

Here's the code:

```
char command;
String string;
#define led 12

void LEDOn()
    {
          digitalWrite(led, HIGH);
    }

void LEDOff()
    {
      digitalWrite(led, LOW);
    }

void setup()
{
      Serial.begin(9600);
      pinMode(led, OUTPUT);
}

void loop()
{
     if (Serial.available() > 0)
           {string = "";}

     while(Serial.available() > 0)
    {
           command = ((byte)Serial.read());

           if(command == ':')
           {
                  break;
           }

           else
           {
                  string += command;
           }

           delay(1);
    }

    if(string == "LO")
    {
           LEDOn();
     }

   if(string == "LF")
    {
           LEDOff();
    }

```

The problem comes when I type the commands. Normally, an LED in the board will react (I think it's the RX one), but the LED in pin 12 will not react at all. After testing ten times with each command alternatively, I calculated the serial needs an average of 6 command repetitions in order to react. Exactly the same happens when the HC-06 is connected.

Is there a reason for this?

# Answer
> 0 votes
Your problem is, amongst other things, that you are assuming that all the serial data arrives at once, which doesn't necessarily happen at all.

I have a discussion about this sort of thing.

Rewriting your sketch using the ideas presented there we get this:

```
#define led 12

void LEDOn()
{
  digitalWrite(led, HIGH);
}

void LEDOff()
{
  digitalWrite(led, LOW);
}

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
{
  Serial.begin (9600);
  pinMode(led, OUTPUT);
} // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
{

  if (strcmp (data, "ON") == 0)
    LEDOn ();
  else if (strcmp (data, "OFF") == 0)
    LEDOff ();
  else
    {
    Serial.print (F("Unexpected command: "));
    Serial.println (data);
    }
}  // end of process_data

void processIncomingByte (const byte inByte)
{
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
  {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

  }  // end of switch

} // end of processIncomingByte

void loop()
{
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

}  // end of loop

```

> with the commands "ON" and "OFF" respectively.

I changed the test to be for "ON" and "OFF" not "LO" and "LF" which seems a weird way of meeting your requirements.

For this to work you need a **delimiter** (which tells the Arduino when you have finished sending a command). I have used linefeed which you can automatically send in the IDE's serial monitor (see bottom RH corner).

I also put in code to show "Unexpected command: " if you don't get ON or OFF (note that "on" is not the same as "ON").

# Answer
> 0 votes
It worked fine for me, *if* I typed the entire command, "LO:" or LF:" (without the quotes of course). However, if I typed and sent one character at a time, it failed. The problem is quite likely the code:

> ```
>    if (Serial.available() > 0)
>          {string = "";}
>
> ```

If you send all of the characters at once, the `while( Serial.available() )` loop will get the whole line and match it. But if there is any pause between characters, what does that `if` statement do? (Hint: `loop()` executes way faster than you can type!)

I was using the serial terminal built into the Eclipse IDE. Different terminal software might behave differently when you type a string and send it. Remember, any gaps between characters, and that first `if` statement gets time to do its dirty work.

---
Tags: arduino-uno, serial, led, bluetooth
---


# Question
Title: How to execute commands on Arduino (via PC) without touching the current sketch?
I am working on my first Arduino project. It's a Reverse Geocache. Basically, it's a puzzle where a battery-powered Arduino is mounted inside a locked box, and is able to unlock the box if the user brings the box to the correct GPS coordinates and presses a push-button (that activates the Arduino, that runs a sketch, that checks the GPS, and operates a servo to release the lock).

It's all working, but I am trying to build in a backdoor, so I can unlock the box when I need to.

I have made the Arduino USB port accessible, and my hope is that I could connect a PC, and execute the appropriate command to operate the servo to unlock the box. The command is:

```
servo.write(OPEN_ANGLE);

```

The sketch that drives the whole puzzle depends on these libraries, but I am guessing the only one needed to operate the servo is PWMServo.h:

```
#include <PWMServo.h>
#include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <EEPROM.h>
#include <LiquidCrystal.h>

```

I would like to be able to operate the servo without altering/replacing the uploaded sketch.

Is it possible to execute code "command prompt" style? Or can I somehow detect from within the sketch code that there is a USB connection, and have that trigger the unlock?

Finally (not the main question, but I would appreciate clarification), I have been told that the power to the Arduino should be disconnected before uploading new sketches (not sure why or if this is true). If forcing an unlock via the backdoor required uploading a new sketch, I seem to have a problem... For the puzzle to work within the locked box, the battery must be permanently connected, and also connecting to a PC via the USB seems to immediately power up the Arduino too. Does this mean uploading a new sketch would be impossible?

# Answer
The simple thing would be for your sketch to read from the serial port continuously. If it finds something it stores it and when a newline arrives it sees if that happens to be a password known only to you. So, for example, all you would have to do is plug in the USB cable, activate the Serial Monitor on your PC, type `swordfish` and the servo opens the box.

You would need to allow for garbage arriving, so make sure that you discard input if it exceeds the size of the buffer you allocate for this purpose.

---

> I have been told that the power to the Arduino should be disconnected before uploading new sketches (not sure why or if this is true).

I don't see how that can be true as you have to reapply power to upload the sketch. I never do that.

---

> Is it possible to execute code "command prompt" style?

No, you upload compiled code.

---

> Or can I somehow detect from within the sketch code that there is a USB connection, and have that trigger the unlock?

Then all the person you give the box to has to notice the USB port, plug something in, and it unlocks. I think not.

---

An even simpler solution would be to have two locations that unlock the box. For example, your kitchen could be one, so to unlock it you just take the box to your kitchen. The other location would be the "real" one that you want your friend to have to find. All the stuff about "you are 200 km from your destination" would of course refer to the real destination. You just make the code check that if it happens to find itself in your kitchen it unlocks the box.
> 4 votes

---
Tags: servo, sketch, tinygps
---


# Question
Title: Making an automated watering system with Arduino
I am trying to make an automated watering system using an Arduino.

Here is my wiring diagram:  And here is my circuit wired up:

Here is the code that I'm using with Arduino. The code seems alright and the wiring on the Arduino seems okay as well, but I don't know where to place a speaker on the Arduino. The biggest problem is that the program doesn't run like I coded. After I uploaded this code to Arduino, the water pump just keeps running forever. Can anyone check up my code to make this run properly?

```
/**automated watering program **/

#include <avr/sleep.h>
#include <avr/wdt.h>
#define BEAT 300 // define time for the tone.
#define PINNO 12

int led = 13;

void setup() {
  // setup code to run once:
  pinMode(led, OUTPUT);
}

void loop() {
  // main code here, to run repeatedly:
  tone(PINNO,262,BEAT); // C(do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,262,BEAT); // C (do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,392,BEAT); // G(so)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,262,BEAT); // C(do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  delay(1000); // Wait for 1 second
  digitalWrite(led,HIGH); //Make No. 11pin output HIGH = 5V
  delay(500); // Watering time
  digitalWrite(led,LOW); //Make No.11 pin output LOW = 0V
  // Shut down program to save battery using by watchdogtimer 24h standby mode
  int var = 0;
  while(var < 10800) {
    delayWDT(9); // 9seconds of shutdown
    var++; // 10800times repeat ＝24h
  }
}

void delayWDT(unsigned long t) {
  // delay excute while using powerdown mode
  delayWDT_setup(t); // watchdog timer setting
  ADCSRA &= ~(1 << ADEN); // ADEN bit clear and stop ADC
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Powerdow mode
  sleep_enable();
  sleep_mode(); // sleep mode
  sleep_disable(); // WatchDog Timer times up and start working again
  ADCSRA |= (1 << ADEN); // turn on the ADC
}

void delayWDT_setup(unsigned int ii) {
  // setting up timer
  // 0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms
  // 6=1sec, 7=2sec, 8=4sec, 9=8sec
  byte bb;
  if (ii > 9 ) {
    // get rid of strange numbers
    ii = 9;
  }
  bb =ii & 7;
  if (ii > 7) {
    bb |= (1 << 5);
  }
  bb |= ( 1 << WDCE );
  MCUSR &= ~(1 << WDRF); // MCU Status Reg. Watchdog Reset  Flag ->0
  // start timed sequence
  WDTCSR |= (1 << WDCE) | (1<<WDE); // allow to edit watchdog
  // set new watchdog timeout value
  WDTCSR = bb;
  WDTCSR |= _BV(WDIE);
}
ISR(WDT_vect) {
  // the work after time up, WDT
  //  wdt_cycle++;
}

```

# Answer
> 2 votes
Problems with your setup:

* Your pump is connected to pin 11 but you are controlling pin 13 (`int led = 13;`)
* You have an LED in line with your transistor base. That should be a resistor, and the LED should be in *parallel* with the base (with its own resistor).
* Your transistor is wired wrong. According to the datasheet the pins are C-B-E as viewed from the angle in your wiring diagram. You have the Arduino connected to E instead of B, the pump connected to B instead of C, and ground connected to C instead of E.
* You don't have a flyback diode across the motor.

simulate this circuit – Schematic created using CircuitLab

---
Tags: arduino-uno, programming, c++, c, code-review
---


# Question
Title: How to insert into table in database after every 5 minutes using Real time clock module
I have RTC module attached to arduino mega,

to calculate time difference of minutes I am getting minute from the RTC module

and checking if passed time is greater than 5 minutes then insert to MySQL table in database.

```
  int mint = util::getMinute();

  if (util::getMinute() - mint >= 5)

  {
    // inserting to sql database on mysql server
    INSERT_SQL = "";
    INSERT_SQL.concat("INSERT INTO arduinoSensorData.outTempLog (out_temperature) VALUES ('");
    INSERT_SQL.concat(tempInC);
    INSERT_SQL.concat("');");

    const char *mycharp = INSERT_SQL.c_str();
    delay(1000);

    if (!connected) {
      my_conn.mysql_connect(server_addr, 3306, user, password);
      connected = true;
    }
    else if (connected == true)
    {
      delay(500);
      Serial.print("Inserting : ");
      Serial.println(INSERT_SQL);
      Serial.println("Connection Successfull,inserting to database.");
      my_conn.cmd_query(mycharp);

    }
    else {
      Serial.println("Connection failed.");
    }
    mint = util::getMinute();
  }

```

the full code is here

# Answer
> 0 votes
So I figured it out myself and used `millis` instead.

in global declaration I did:

```
unsigned long sqlInsertInterval = 300000; // the repeat interval after 5 minutes

```

then initiate timer in setup method

```
  timer = millis(); // start timer

```

followed by below changes in the loop method.

```
void loop() {
  // perform sql insert after 5 minutes
  if ((millis() - timer) > sqlInsertInterval) {
    // timed out
    timer += sqlInsertInterval;// reset timer by moving it along to the next interval

    // inserting to sql database on mysql server
    INSERT_SQL = "";
    INSERT_SQL.concat("INSERT INTO arduinoSensorData.outTempLog (out_temperature) VALUES ('");
    INSERT_SQL.concat(tempInC);
    INSERT_SQL.concat("');");

    const char *mycharp = INSERT_SQL.c_str();
    if (!connected) {
      my_conn.mysql_connect(server_addr, 3306, user, password);
      connected = true;
    }
    else if (connected == true)
    {
      Serial.print("Inserting : ");
      Serial.println(INSERT_SQL);
      Serial.println("Connection Successfull,inserting to database.");
      my_conn.cmd_query(mycharp);

    }
    else {
      Serial.println("Connection failed.");
    }
  }
}

```

# Answer
> 0 votes
```
int mint = util::getMinute();

if (util::getMinute() - mint >= 5)

{

```

Well, if `mint` is `util::getMinute()` then surely `util::getMinute() - mint` will *always* be 0.

I think you meant `mint` to be `static`, or a variable in the *global scope*.

---
Tags: arduino-mega, programming, sketch
---


# Question
Title: Couldn't connect to local server using Ethernet Shield and Arduino Mega 2560
I'm trying to connect the arduino mega and ethernet shield and try to send some data to a php script. I have connect the ethernet shield to the laptop. Lap is connected to router through wi-fi. Any help in advance please.

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

/******************** ETHERNET SETTINGS ********************/

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x85, 0xD9 };   //physical mac address
byte ip[] = { 192, 168, 1, 5 };                   // ip in lan
byte subnet[] = { 255, 255, 255, 0 };              //subnet mask
byte gateway[] = { 192, 168, 0, 1 };              // default gateway

IPAddress server(192,168,1,2);
EthernetClient client;

void setup() {
    Serial.begin(9600);  // Initialize serial communications with the PC
    while (!Serial);     // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    Ethernet.begin(mac,ip,gateway,subnet);     // initialize Ethernet device
    Serial.print("My IP address: ");
    for (byte thisByte = 0; thisByte < 4; thisByte++) {
      Serial.print(Ethernet.localIP()[thisByte], DEC);
      Serial.print(".");
    }
    Serial.println();
    Serial.println("connecting....");
}

void loop()
{
  if (client.connect(server,1234)) { // REPLACE WITH YOUR SERVER ADDRESS
    Serial.println("Server connection OK");
    client.println("GET /add.php?temp1=10&hum1=20 HTTP/1.1");
    client.println("Host:" + server);// SERVER ADDRESS HERE TOO
    client.println("Content-Type: text/plain");
  } else {
    Serial.println("connection failure");
  }

  if (client.connected()) {
    client.stop();// DISCONNECT FROM THE SERVER
    Serial.println("disconnected");
  }

  delay(5000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
}

```

Serial Out Put

```
My IP address: 192.168.1.5.
connecting....
connection failure
connection failure
connection failure
connection failure
connection failure
connection failure
connection failure

```

# Answer
> 1 votes
I had this problem for quite a long time and then I did a little bit of research! Here it is in an easy explanation-

When you connect your Ethernet Shield to the Laptop the laptop takes the Ethernet Shield as a source of internet and tries to get an IP Address and other network stuff FROM the shield! BUT what we want is the other way round.

We want the Ethernet shield to take the laptop as a source of internet and get itself an IP assigned by the laptop!

What I do is I make a Laptop-Ethernet Shield network and a Laptop-WiFi network.(Simply means that I connect my laptop to WiFi and Ethernet shield)

Then I JOIN the two networks!

This joining of networks is called network bridging and is done easily, I'll tell you how-

If you're using linux then follow this link here.

else if you're running windows-

1) Connect your Ethernet Shield (With Arduino attached obviously) to the laptop and make sure that your laptop is connected to the WiFi.

2) Go to Network and Sharing Center.

3) Go to Change adapter settings.

4) Select your Wifi adapter and the Ethernet adapter together.

5) Right click on any of the selected adapter and click Bridge connections.

6) Wait till a new network bridge is connected and is done verifying after it's creation.

7) Upload the sketch again on Arduino and you'd be connected.

**NOTE**

DHCP may not always work as it's a feature of your router/WiFi and not your laptop so try assigning a mannual IP by calling Ethernet.begin(mac,ip) instead of using DHCP by caling Ethernet.begin(mc);

AND do change your ip to 192.168.1.XXX I mean change the last tuple so it does not clash with the ip of any other device.(XXX any number less than 255, generally 100-200)

Do let me know the outcome after trying this out! :D

# Answer
> 0 votes
First your network config is wrong. The gateway is outside the scope of your netmask. This is invalid and may fail the tcpip stack depending on how the Arduino library is implemented.

Second, once you fix this, your laptop needs to be configured as a router to access resources on your network resources unless 192.168.1.2 is the laptop you are connected to.

---
Tags: arduino-mega, shields, ethernet
---


# Question
Title: Programming an ATmega328P by holding it on an Uno's
I was looking at this Uno clone, the Nanino and then happened to read this article on "Manhattan style" circuit design. Anyway, that got me thinking...

If I borrowed someone's Arduino Uno, could I hold a blank ATmega328P on top of the identical chip on that Uno and load a bootloader onto the board's chip as well as my chip? The desired result would be to give my blank ATmega328P a bootloader.

# Answer
> 3 votes
It's easy enough to use a Uno to program a bootloader onto another chip. I describe this process here.

The idea of holding one chip on top of another is likely to fail for various reasons. Both chips will try to respond to the programming attempt at slightly different times, probably making them both fail to be programmed.

See my post about making a breadboard Arduino. It only takes a few wires to program the target chip.

However this isn't just "paralleling the pins" - it is using one chip to program another, in the way it is designed to do.

# Answer
> 0 votes
> If I borrowed someone's Arduino Uno, could I hold a blank ATmega328P on top of the identical chip on that Uno and load a bootloader onto the board's chip as well as my chip? The desired result would be to give my blank ATmega328P a bootloader.

Well burning a bootloader(over a SPI communication) is quite different than simply uploading code(Serial communication), therefore it requires a specific setup which is an AVR-ISP.(In-System Programmer).

So you can't burn a bootloader by simply holding it over the other because of the Uno design.

The IC socket for the Atmega chip on the Uno board is not set for SPI communication so you can't burn a bootloader onto it directly. Instead, you'll have to do a similar setup to Nick Gammon's. Use one arduino as an ISP to burn the bootloader onto another.

Therefore placing the 'raw' chip in the socket and trying to burn the bootloader won't even work.

**Note** that in this setup, the Uno is communicating as an ISP and *it* uploads the code to the 'raw' Atmega328 chip. The chip on the Uno already has the bootloader(in fact it is configured/programmed to be an ISP).

Hope it helps! Best of luck!

---
Tags: arduino-uno, atmega328, bootloader
---


title: Arduino ligths on/off clapping hands

text:
# Question
Title: Arduino ligths on/off clapping hands
I'm new to Arduino and I'd like to realize a system using Arduino One and SparkFun Electret Microphone Breakout (BOB-09964) to turn on/off lights clapping my hands. https://www.sparkfun.com/products/9964

What are the components I need? I'm going to buy them and I don't want to buy components which I will not use soon (so no starter kits but only a breadboard, resistors, LEDs, etc...).

Sorry for this basic question but as I said I'm new to this world.

# Answer
If you start from the beginning of the project, instead of trying to jump in half way through, you'll know precisely what components you need.

Your first step shouldn't be trying to order components, but to identify (through research) how the technology works.

Second is to find out how it can be implemented, by looking at existing schematics and designs that other people have created.

Third is to design your own schematic.

Fourth is to prototype it. It's only at this stage that you should be thinking about what components to order.

Go back to stage one and do the research. Thanks to the likes of Google it'll probably only take you a few minutes.
> 1 votes

# Answer
See the Arduino tutorial for a Sound Sensor Example.

This is a very similar project that shows the breadboard layout and code needed for a clapping sensor based on an electret microphone breakout board.

The website listed above has a list of parts needed, the circuit diagram as well as the code needed.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Convert ASCII output to human readable form and assign to a variable
I'm reading the RFID output and I can print it to the serial monitor as human readable. But what I want is to assign that to a variable. But I'm getting the ASCII. Is there any way to convert it and get to the variable like Serial.write() do.

```
byte readbackblock[19];

for (int j=0 ; j<16 ; j++)//print the block contents
    {
      Serial.write (readbackblock[j]);
      cardNumber += readbackblock[j];
    }

Serial.print(cardNumber);

```

Serial output

```
read block: 1234567890123456

49505152535455565748495051525354

```

Any help please.

# Answer
I don't think it is possible.

The Arduino is 8-bit microcontroller, and can't handle integers larger than 32-bit. The maximum value for a unsigned 32-bit integer is 4294967296. This is a smaller number than your readblock, so it wil never fit.

If you want to do this with smaller numbers, you can use these 2 function:

* atoi -\> convert char array to integer
* atol -\> convert char array to long integer
> -1 votes

---
Tags: arduino-mega, rfid, convert
---


# Question
Title: while(1) loop blocks program to enter interrupt
I want to build a program in C that enables / disables a passive matrix display. But my problem occurs before I can even implement one function of this display.

I have a simple switch connected to Port C pin 24, which is configured as INPUT with a pull-up resistor and debouncing input filter. When I toggle the switch the code enters an interrupt and toggles the "display" on or of depending on the state of the switch.

Everything works fine until I introduce a simple `while(1)` loop, which should handle everything I want to do. But every time I write the function called `run`, which only contains one `while(1)` loop and a single dummy operation `__asm__("nop")`, the while loop prevents the code from entering the interrupt.

This is my code:

```
void display_init(void) {
    sysclk_init();
    delay_init(sysclk_get_cpu_hz());
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk(ID_PIOC);
    NVIC_EnableIRQ(PIOC_IRQn);
    REG_PIOC_PER = SWITCH;
    REG_PIOC_ODR = SWITCH;
    REG_PIOC_OWDR = SWITCH;
    REG_PIOC_PUER = SWITCH;
    REG_PIOC_IFER = SWITCH;
    REG_PIOC_DIFSR = SWITCH;
    REG_PIOC_LSR = SWITCH;
    REG_PIOC_REHLSR = SWITCH;

    //Clear input change register to avoid immediate interrupt
    REG_PIOC_ISR;
    REG_PIOC_IER = SWITCH;
    run();
}

void run() {
    while(1) {
        __asm__("nop"); //Dummy operation for debugging
    }
}

void PIOC_Handler(void) {
    REG_PIOC_ISR;
    if(REG_PIOC_PDSR & PIO_PC24) {
        __asm__("nop"); //Breakpoint
    } else {
        __asm__("nop"); //Breakpoint
    }
}

```

As far as I know, an interrupt stops everything executed at the current time and starts working on the interrupt code. My question is now: Why is the interrupt not stopping the while loop?

Before I recognized this problem, I had a simple condition in the while loop that checks whether 1 or 0 to equals 1 when I set this state to 0, so the condition was `1 == 0` which should equal `false`. The loop did not stop and continued to run even if the condition for this loop was false... Is it possible that while loops do not like to be used in parallel with interrupts?

**EDIT:**

```
void main(void) {
    board_init();
    display_init();
}

```

I don't have an Arduino setup() function because I'm using Atmel Studio to ensure working at low Level, to avoid unnecessary code and to keep memory usage as low as possible.

# Answer
> 2 votes
The while loop should have no effect on interrupts. Where does `run()` get called? We'll need to see the code that sets up and calls the code you've shown. But as a sanity check, you could try replacing the entire contents of run() with a `;`, that is make it an empty function. Then add in an empty while loop (contains only a `;`, no \__asm\__ code) and try again. Then replace the body of the while loop with \__asm("nop")\__ and try again. At which of the above steps does your interrupt fail? That should lead you in the right direction.

Update:
What does your main() function do after display\_init() returns? Because that won't ever happen when run() runs forever.

The job of main() is to create the C/C++ run-time environment. That may not have been completed (enabling interrupts, for instance) when display\_init() and run() get called, but gets completed shortly after they returns - *if* run() is allowed to end.

Without seeing your main(), we can't know enough to be more specific, but I'd suggest you move all of your code out of main() and down into the Arduino setup() function because, by the time it gets called, the run-time environment will be complete.

Update 2:

> to avoid unnecessary code

If that is your entire main() function, you've left out the run-time environment setup and it's little wonder that your code behaves strangely. You've asked for help and we've made some suggestions: to show your entire code, not just selected pieces of it; and run your code in a standard way and let us know the result. Then you can optimize your code if you feel it's worth it to you. When you've done that test, and you still have questions, ask again. Until then, you're just asking us to guess. We did that. Once.

---
Tags: arduino-due, c, interrupt, port-mapping, sam3x
---


# Question
Title: How to send information from a web-site to the arduino?
I currently have an Arduino Mega + an Arduino Ethernet shield, I would like to know if it's possible to send data to the arduino from a web-site hosted on the shield itself. So that when someone press a Button on the web-site it sends a signal to the arduino to trigger an action. Could anyone kindly help me.

# Answer
> 3 votes
Yes of course!

First things first - Yes, it is possible to accomplish what you're thinking.

The idea is to create a server on the Ethernet Shield and open the webpage hosted by it on any device and based on the options selected on the web page we can trigger desired actions on the Arduino.

I've modified the web server code of Arduino built-in examples to match your requirements, just upload it and make necessary changes as required, here it is-

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

byte mac[] = {
   0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
 };

 IPAddress ip(192,168,1,199); // Any ip address not on your network.
 EthernetServer server(80);   // Port 80 is default for http.

  int led=2;

  String request;

  void setup(){
    Ethernet.begin(mac,ip);
    pinMode(led,OUTPUT);
    Serial.begin(9600);
   }

  void loop(){

      EthernetClient client = server.available();
  if(client)
         {
       Serial.println("Client is trying to connect......");
       while(client.connected())
       {
  if(client.available())
  {
    char c = client.read();
    request.concat(c);
    if(c=='\n'){
    Serial.print(request);
    if(request.indexOf("ON")>0){
      digitalWrite(led,HIGH);
      Serial.println("ON");
      }

      else if(request.indexOf("OFF")>0){
        digitalWrite(led,LOW);
        Serial.println("OFF");
        }
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    //client.println("Refresh: 5");  // refresh the page automatically every 5 sec
    client.println();

    client.println("<!doctype html>");
    client.println("<html>");
    client.println("<head><title>LED</title></head>");
    client.print("<!DOCTYPE HTML><html><body ><a href ='/?LED_ON'><p style = ' text-align:center'>LED ON</p></a><br><a href ='/?LED_OFF'><p style = ' text-align:center'>LED OFF</P></a><br></body></html>" );
    client.println("</html>");
    client.stop();
    request="";

  }
  }
 }

    }

   }

```

This sketch will turn an LED on or off attached to digital pin 2.

You have to go to the IP address that you provide to the shield (192.168.1.199 in my case). You'll see 2 hyperlinks to switch on or off the led and that would pass a query which the Arduino looks for again and again in the loop and takes action accordingly.

Hope this helps, try this out, and do let me know the result.

**NOTE**

Make sure that you access the Ethernet Shield from a device within your LAN only otherwise you'll have to use port forwarding.

---
Tags: arduino-mega, c++, ethernet, c, sd-card
---


# Question
Title: Port Manipulation and serial communication
i'm working on a laser timer using arduino and i saw that using direct port manipulation can have a really better time precision. My only concern is about serial communication, because i am using some pins for a software serial, and i don't know how to set them in the ports register. The pins are the 4 and 5, and the number 3 is the trigger output, unluckily this pinset cannot change. How should i set them in the DDRD? I'm using an Arduino Nano board

# Answer
> 1 votes
You can modify a single or multiple bits in a register by using a Read-Modify-Write approach. Essentially something like this:

```
byte temp = DDRD;
temp = (temp & ~(bitmask)) | bits_to_set;
DDRD = temp;

```

In the above code, `bitmask` is some value with the bit or bits you want to modify set - e.g. if you want to change bits 4 and 5, it would be `(_BV(4) | _BV(5))` or just `(0b00110000)`. `bits_to_set` is a value with all bits that you want to be one set - e.g. if you want bit 5 to be a 1, it would be `(_BV(5))` or `(0b00100000)`.

What the code does is to first get the current value of the register you want to manipulate. Then it will clear only the bits which you want to modify to 0 by using bitwise AND on the temp value. Next it will set only the bits you want to change to be set by using a bitwise OR. Finally it writes it back to the register.

If you are using interrupts which, you may wish to do this atomically (so that the register is not changed by an interrupt occurring before the new value is written back). You can do this by wrapping the above code in:

```
byte oldSREG = SREG;
cli();
...
SREG = oldSREG;

```

Which will clear the global interrupt flag to pause any interrupts, and then will restore the value of it afterwards.

---

If you just want to change a single bit in a register you can optimise this code down to one of the following examples:

```
DDRD |= _BV(4); //Set bit 4
DDRD &= ~_BV(5); //Clear bit 5

```

Again you may want to do this atomically as it may compile to a Read-Modify-Write access.

---
Tags: softwareserial, timers, port-mapping
---