# Question
Title: Irregularly triggering an ISR using timers
I seek to call an ISR routine after a fixed time of 400us. This action needs to be done every now and then (in the range of 0.8-3.0ms). For that matter, I thought I'd set timer2 to CTC mode, use OCR2A to set some TOP value for 400us and let the timer call the ISR routine after 400us. Within the ISR I would then stop the timer from triggering interrupts, until I need to count to 400us again, where I would activate the timer interrupt again.

This works, as expected, except for the fact, that after activating the interrupt for OCR2A again, it instantly triggers. The code below, produces a 1ms alternating signal, instead of 1ms+400us.

My question is, am I on a good way with this, or should I use the overflow ISR and preload the timer? Or any other method? The problem is, that after the 1ms waiting time in the main loop, I'd expect the counter to count from 0 to 100, meaning 400us. However on an oscilloscope I see the pin toggle each 1ms.

```
uint32_t timestamp;

void setup() {
  Serial.begin(115200);
  pinMode(9, OUTPUT);
  cli();         // disable global interrupts
  // Timer2 for counting (to release the pin)
  TCCR2A |= (1 << WGM21); // CTC mode, clear timer on compare match
  TCCR2B |= (1 << CS22); // Prescalar 64

  OCR2A = 99; // ticks, before ISR is called
  TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
  TCNT2 = 0x00; // set the timer to 0
  // counting time[s] = (OCR+1)/(F_cpu/prescalar)
  // 99 = 400us | 124 = 500us
  sei(); // enable global interrups
  timestamp = micros();
}

void loop() {
  uint32_t now = micros();
  if (now - timestamp > 1000) {
    timestamp = now;
    cli();
    TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
    sei();
    TCNT2 = 0x00;
  }
}

ISR(TIMER2_COMPA_vect) {
  // Serial.print(F("Here\n"));
  PORTB ^= 2; // set pin 9 high again
  // TCNT2 = 0x00; // reset timer for testing
  // deactivate the counter
   cli();
   TIMSK2 = 0x00; // unlink the ISR from timer
   sei();
}

```

# Answer
> 2 votes
> However on an oscilloscope I see the pin toggle each 1ms.

That's what you expect. You set up the timer to fire every 1 ms. Since the ISR is called some time after that (and that is what toggles the pin) you will see the pin toggle every 1 ms.

I've reworked your example a bit to make it clearer, and to toggle the pin when we start the timer, and again when the ISR fires:

```
uint32_t timestamp;

void setup()
  {
  pinMode(9, OUTPUT);
  // Timer2 for counting
  TCCR2A = bit (WGM21); // CTC mode, clear timer on compare match
  OCR2A = 99;           // ticks, before ISR is called

  // counting time[s] = (OCR+1)/(F_cpu/prescalar)
  // 99 = 400us | 124 = 500us
  timestamp = micros();
  }  // end of seupt

void loop()
{
  uint32_t now = micros();
  if (now - timestamp >= 1000)
    {
    timestamp = now;
    TIFR2 = bit (OCF2A);   // clear any pending interrupt
    TCNT2 = 0;             // make sure counter is zero
    TIMSK2 = bit (OCIE2A); // enable timer compare interrupt
    TCCR2B = bit (CS22);   // start timer: Prescalar 64
    PINB = bit (1);        // toggle pin 9
    }  // end of if
}  // end of loop

ISR(TIMER2_COMPA_vect)
{
  PINB = bit (1); // toggle pin 9
  TCCR2B = 0;     // stop timer
}  // end of TIMER2_COMPA_vect

```

You can see from the scope output that the timer is started every 1 ms (as expected) because Cursor 1 is at -1 ms. The width of the pulse is 400 µs, as expected.

---

> In my example I do not have to set so many settings each time I want to start the timer.

I took out the `cli` and `sei` so I saved you two lines. Don't forget to count them!

If you leave the timer running, it may well have reached the counter again (even though not generating an interrupt). Thus this line is important (even more so for you):

```
TIFR2 = bit (OCF2A);   // clear any pending interrupt

```

Also, if you leave the timer running, you may have a race condition. Say the timer is just about to tick over and generate the interrupt. You clear the flag (as shown above), but one machine cycle later the timer reaches the counter and sets it again, just before you get a chance to zero it. With the timer running, there could be combinations of when you enable interrupts, zero the flag, and clear the pending interrupt flag, that could occasionally work against you. Having the timer stopped is much safer.

Now if you are worried about the number of lines you need to start it (I wouldn't be) then you can move this line into setup:

```
TIMSK2 = bit (OCIE2A); // enable timer compare interrupt

```

Since you stop the timer in the ISR it doesn't matter if the interrupt is still enabled. Now you just have three lines to start the timer:

```
TIFR2 = bit (OCF2A);  // clear any pending interrupt
TCNT2 = 0;            // make sure timer is zeroed
TCCR2B = bit (CS22);  // start timer: Prescalar 64

```

I think we've agreed that clearing the compare flag is important, so this isn't any lengthier.

---

> looking at your divisioning of the time axis, and from code, it is clear, that there is a 600us break, not 1ms!

Yes, there's a 600 µs break, because you start the timer every 1 ms, and it runs for 400 µs, thus there will be a 600 µs break.

---

> I seek to call an ISR routine after a fixed time of 400us.

That's exactly what my posted code does. The pin goes high at the time you desire, in loop, and it goes low 400 µs later. That's what you wanted: a 400 µs interval.

---
Tags: interrupt, timers, isr
---


# Question
Title: Barebones 328p, 2xAA vs 3xAA, which will last longer?
So im just running a 328p at 8mhz with the internal oscillator. Datasheet says 1.8 to 5.5v is voltage range.

Will 3xAA in series (~4.5v) last longer than 2xAA in series (~3v), assuming all batteries have the same capacity, theoretically each option should have the same mAh but does the difference in voltage affect things ?

# Answer
> 3 votes
Yes, running at a higher voltage will consume more current. In the datasheet you have this nice graph:

I have highlighted the two voltages at 8MHz for you. At 4.5V you would typically be using about 4.7mA. At 3V you would be using around 2.8mA. That's not taking into account anything else in your circuit of course - just the ATMega itself.

# Answer
> 2 votes
Majenko's answer is correct, however he (or both of you) are assuming that the processor clock is running. When it runs, a processor cycle at a higher voltage will use more current. However when in power-down sleep mode the clock stops, and consumption is much lower. If you don't need the watchdog timer (for example, a switch closure activates the processor) then the difference will be negligible. Indeed, the current consumption is around 100 nA.

If you need the watchdog to periodically wake you, then the difference will be about 2 µA (that's a lot less than 2.8 mA).

These are quoted at room temperature - around 25°C.

---

I would be concerned about 2 x AA batteries. Their nominal voltage might be 3V, but their actual voltage (say, if they are NiMh batteries) might be closer to 2.4V, and that is the minimal amount for running at 8 MHz.

With 3 x AA batteries you are much more safely in range for the voltage requirements, particularly if you have some peripherals that might drain power, and thus lower the voltage.

---

Other discussions about low-power considerations at http://www.gammon.com.au/power.

---
Tags: atmega328, battery
---


# Question
Title: Error: "invalid use of incomplete type" and "forward declaration"
I have the following errors trying to use a TFT library function inside my library. My library uses the pointer to an instance of the TFT library in the constructor, as well described there:

Basic C++ programming, how to pass constructor argument into class?

The errors are:

```
error: invalid use of incomplete type 'class TFT'
_TFTscreen->background(0, 0, 0);

error: forward declaration of 'class TFT'
class TFT;

```

*MESmenu.h:*

```
#ifndef _MESMENU_H_
#define _MESMENU_H_

#include <SPI.h>
#include <SD.h>

class TFT;

class MESmenu{
public:
  MESmenu(TFT* pTFT) : _TFTscreen(pTFT) {};
  void start();
  void execute();
private:
  TFT* _TFTscreen;
};

#endif

```

*MESmenu.cpp:*

```
#include "Arduino.h"
#include "MESmenu.h"

void MESmenu::start(){
  _TFTscreen->background(0, 0, 0);
  _TFTscreen->text("starting menu...", 0, 0);
  //...
}

void MESmenu::execute(){
   //some code...
}

```

The *Arduino sketch* is:

```
#include <SPI.h>
#include <SD.h>
#include <TFT.h>  // Arduino LCD library
#include <MESmenu.h>  // my library

// --------- TFT LCD ---------
// pin definition for the due
#define sd_cs  7
#define lcd_cs 10
#define dc     9
#define rst    8
TFT TFTscreen = TFT(lcd_cs, dc, rst);

// MES menu class
MESmenu *mainMenu = new MESmenu(&TFTscreen);

void setup() {
  // initialize TFT
  TFTscreen.begin();
  TFTscreen.background(0, 0, 0);
  // set the stroke color to white
  TFTscreen.stroke(255,255,255);
  TFTscreen.fill(255,255,255);
  TFTscreen.setTextSize(2);
  TFTscreen.text("TEST", 0, 0);

  // Start menu
  mainMenu->start();
}

void loop () {
  mainMenu->execute();
}

```

The problem is related to the function:

```
_TFTscreen->background(0, 0, 0);

```

inside the MESmenu::start() in the .cpp file.

**UPDATE:**

As suggested by **frarugi87** I've updated the question with the details of .h and .cpp files. Those file are in the Arduino\libraries\MESmenu folder.

I try to change

```
class TFT;

```

with

```
#include <TFT.h>

```

and removed the #include from the main arduino sketch.

This leads to the following errors:

```
libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: first defined here

libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::read16(SDLib::File)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::read32(SDLib::File)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::loadImage(char const*)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

```

# Answer
Try to change

```
class TFT;

```

to

```
#include <TFT.h>

```

Then you can remove the `#include <TFT.h>` from the main arduino sketch.

Moreover you should at least write a piece of code to make the compiler include your library just once; this is the usual way to do it:

```
#ifndef _MESMENU_H_
#define _MESMENU_H_

#include <SPI.h>

...
the rest of your library
...

  TFT* _TFTscreen;
}

#endif

```

`_MESMENU_H_` is any unique string (usually the filename is used, remembering that you can't put spaces or other punctuation marks except the underscore). And you should put it only in the header file (\*.h or *.hpp), not in the source (*.c or \*.cpp or \*.ino)

EDIT:

The additional info lead me to analyze the library and.. there are problems with the library. Particularly the file `TFT/src/utility/Adafruit_GFX.h` has a big problem: it has the code for the functions.

To fix it, you have to modify the library.

Go into the folder `TFT/src/utility/` and make a copy of `Adafruit_GFX.h`, calling it `PImage.cpp`.

Open `Adafruit_GFX.h` and delete everything between line 227 and line 370. This means that from

```
bool useFill;
};

#if defined(__SD_H__)  // Arduino SD library

#define BUFFPIXEL 20

void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) {

...

  return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip);
}

#endif

#endif // _ADAFRUIT_GFX_H

```

it should become

```
bool useFill;
};

#endif // _ADAFRUIT_GFX_H

```

Having done this, open `PImage.cpp` and delete everything above line 227, then delete the function `Adafruit_GFX::image` and the last `endif` and add, at the beginning, `#include Adafruit_GFX.h`. This means that the file should look like

```
#include "Adafruit_GFX.h"

#if defined(__SD_H__)  // Arduino SD library

#define BUFFPIXEL 20

// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.

uint16_t PImage::read16(File f) {

...

  return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip);
}

#endif

```

Then try to compile again the program

BTW: the source I looked at is at this page.
> 1 votes

---
Tags: c++
---


# Question
Title: Why is my LCD 16*2 is not displaying any characters, although all the wiring is correct?
Recently I have linked up a typical 16\*2 LCD (Liquid Crystal Display) display to my Arduino Uno and have linked all the pins up.

Here is my connection:(LCD pin first)

1=GND, 2=+5v, 4=11, 6=12, 11=5, 12=4, 12=3, 14=2, 15=backlight positive, 16=backlight negative

```
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis()/1000);
}

```

This is the code that is the default for the LCD, I didn't write it.

So I have done all this and when I turn it on the screen is blank and nothing is happening. Could anyone explain what I have done wrong?

# Answer
> 7 votes
Check out this tutorial on Adafruit. It will walk you through setting it up. In the tutorial they change the pins, which I believe is the issue here. Here is a snippet.

And change your pins:

```
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

```

# Answer
> 8 votes
Recently I also faced similar problem, with connection as:

1=GND, 2=+5v, 4=11, 6=12, 11=5, 12=4, 12=3, 14=2, 15=backlight positive, 16=backlight negative

Solution: I just **connected VEE (pin 3) of LCD to Ground (GND)** without use of potentiometer as it worked.

# Answer
> 3 votes
What is connected to LCD pin 3? Pin 3 is the contrast V0 and needs to be connected with a 10 KOhm potentiometer.

Some LCD's need a negative contrast voltage, check the datasheet of the display.

If the contrast voltage is not correct the display will stay blank. I came across the same problem until i saw the negative voltage must be applied :-)

---
Tags: arduino-uno, programming, pins, lcd
---


# Question
Title: How to interrupt a Timer to Change position along a Colour Cycle
I want to have a loop of 4 colours which runs constantly (i.e. red -\> green -\> blue -\> white) each of the colours having their own LED and pin on the Arduino board. There is a 7 second delay between switching the colour and this cycle should run continuously. When I press a button, I want the cycle to immediately switch back to green and continue the cycle (i.e. -\> blue -\> white -\> red) again.

How should I go about this? Can you have a listener for a button press going at the same time as a delay? How do you interrupt the timer and change the active LED?

# Answer
> 1 votes
You could start with the attachInterrupt example sketch and work from there. Here is a possible solution:

```
enum { GREEN = 0, BLUE = 1, WHITE = 2, RED = 3};
const int buttonPin = 2;
const int ledPin[] = { 4, 5, 6, 7 };
volatile bool reset = false;
int state = GREEN;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  for (int i = 0; i < 4; i++) pinMode(ledPin[i], OUTPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin), doResetState, FALLING);
}

void loop() {
   digitalWrite(ledPin[state], HIGH);
   delay(7000);
   digitalWrite(ledPin[state], LOW);
   if (state == RED || reset) {
     state = GREEN;
     reset = false;
   }
   else {
     state = state + 1;
   }
}

void doResetState () {
    reset = true;
}

```

This will not immediately cycle back to GREEN when pressing the button but you can fix that by modifying the doResetState().

Cheers!

# Answer
> 0 votes
The SimpleTimer library would be ideal for this. One timer callback function, the present contents of the loop() function, would advance the lighting state, called by a 7 second timer. Another, your present doResetState() with the modification noted by @MikaelPatel, would read (and debounce) the button on, say, a 100ms timer. The main loop would be reduced to `Timer.run();`

---
Tags: led, interrupt, timers
---


# Question
Title: Problem updating Arduino WiFi Shield's Firmware
I'm using Arduino Uno R3 and the official Arduino WiFi Shield R3. I'm trying to update the Shield's firmware to 1.1.0 through ***this*** guide.

Everything goes fine until Step 9. When I execute the code in Step 10, I get an error (see attachment) as:

`AtLibUsbDfu: 3EB 2FF8 no device present`

`FAIL Could not open USB device.`

`ISP done.`

***EDIT:*** I re-installed the firmware on my shield and now the problem's gone.

# Answer
I cant comment because of reputation... You've already upgraded the firmware. Just when you try upgrading again your wifi device is rebooting itself because of upgrading before.
> 1 votes

# Answer
Many of the online instructions do not work. This one does - http://arduinotronics.blogspot.com/2015/06/upgrading-arduino-wifi-shield-firmware.html
> 1 votes

---
Tags: wifi, firmware
---


# Question
Title: Can I use two sensors with different baud rate without problems on arduino?
One sensor has a baud rate of 115200, the other 9600. I think this will create problems in the serial because I can only choose one baud rate.

What do you think? The first sensor is the pulse sensor, while the other is the gsr sensor by grove. Link: http://pulsesensor.com/ Link 2: http://www.seeedstudio.com/wiki/Grove\_-\_GSR\_Sensor

# Answer
You can only have one sensor on one serial port, and the baud rate is set on the serial port.

So as long as you have two serial ports, or SoftwareSerial ports (I wouldn't, it causes more problems that it solves - get a board with multiple UART interfaces) then yes you can have two baud rates.
> 1 votes

# Answer
> One sensor has a baud rate of 115200, the other 9600. I think this will create problems in the serial because I can only choose one baud rate.
>
> > Why do you think the sensor has a baudrate?

Both the sensors seem to use the "serial connection" of the Arduino to log their information.

> What do you think? The first sensor is the pulse sensor, while the other is the gsr sensor by grove. Link: http://pulsesensor.com/ Link 2: http://www.seeedstudio.com/wiki/Grove\_-\_GSR\_Sensor
>
> > I think it'll work fine.

Looking at the facts of your sensors, the pulse sensor does have some kind of weird low-level timing/ADC access. But your Grove GSR sensor can basically be read out through an analog input.

**So what to choose?**

You could choose 9,6k or 115k2 (9600 or 115200). It wouldn't make all that much difference. 9600 or 115200 will work fine. 115200 is a lot faster, but for debugging purpose 9600 is used, since it's often default and (often) more reliable.

**Wrapping up**

I don't think there is an issue with the two serials. You can easily log both messages to the same serial output.

Try using 115200 since timing is essential in your case, you want your sensor to be response/fast.

They do both use the same analog to digital converter on your board. An Arduino can't check both sensors at the same time. But by switching between them very fast, you will get a resolution that's good enough.
> 1 votes

---
Tags: arduino-uno, sensors, arduino-nano, baud-rate
---


# Question
Title: Connect a USB slave into Arduino using FTDI
Probably I'm asking a nonsense question but I'm new at interfaces.

I want to connect an USB barcode scanner to an Arduino (Uno or Mega). I've read that I need a USB host shield to achieve this. But I don't have any. I have a FTDI, so I suppose I could plug the USB output of the scanner into the FTDI and connect the FTDI to the UART port of Arduino. Then, I would be passing the USB output to Serial.

Is it correct? Thanks and sorry if I said something stupid!

# Answer
No, that is completely wrong.

In USB you have *hosts* and *devices*. A *device* has to connect to a *host*. Your FT232 is a *device*. The barcode scanner is a *device*. Both of them need to be connected to a *host* for them to do anything.

So you need a USB *host* shield to act as that host.

However - check the manual for your barcode scanner: it may well have a RS-232 mode that it can be switched into (may need a different cable attached).
> 2 votes

---
Tags: arduino-uno, usb, ftdi
---


title: Arduino disconnecting at upload

text:
# Question
Title: Arduino disconnecting at upload
This problem doesn't seen to be very common around the Arduino community.

Basically, what's happening is that as soon as I click the upload button, the Arduino IDE tells me that my Arduino board is not connected. What's strange though is that the python application ino is able to upload my code just fine, so my only guess is that there is something wrong with the IDE itself.

Here's a copy of the error message I am getting at the time of uploading the sketch:

> Binary sketch size: 444 bytes (of a 32,256 byte maximum)processing.app.SerialException: Error opening serial port '/dev/ttyACM1'.at processing.app.Serial.\<init\>(Serial.java:178)at processing.app.Serial.\<init\>(Serial.java:77)at processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:77)at processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:174)at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)at processing.app.Sketch.upload(Sketch.java:1671)at processing.app.Sketch.exportApplet(Sketch.java:1627)at processing.app.Sketch.exportApplet(Sketch.java:1599)at processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)at java.lang.Thread.run(Thread.java:744)Caused by: gnu.io.UnsupportedCommOperationException: Invalid Parameterat gnu.io.RXTXPort.setSerialPortParams(RXTXPort.java:213)at processing.app.Serial.\<init\>(Serial.java:163)... 9 moreprocessing.app.debug.RunnerException: Error opening serial port '/dev/ttyACM1'.at processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:101)at processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:174)at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)at processing.app.Sketch.upload(Sketch.java:1671)at processing.app.Sketch.exportApplet(Sketch.java:1627)at processing.app.Sketch.exportApplet(Sketch.java:1599)at processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)at java.lang.Thread.run(Thread.java:744)

I am expecting to hear a few questions regarding this issue, so I'll go ahead and answer all the questions I can think of.

> *Is this the first time you trying to connect to the Arduino from this computer?*

No. In fact, I was able to upload the same source code just fine less than two hours ago.

> *Did you try a different USB cord?*

Yes, I did.

> *Can you upload the source code from a different computer?*

Yes, I can.

> *Have you tried removing and reinstalling the IDE?*

Yes, I have.

> *Have you tried a different USB port?*

Yes, I have.

What seems to be the problem here?

# Answer
> 4 votes
First of all, you must test if the device that you are trying to access, actually exists. The device file may change when you replug the Arduino. The easiest way to accomplish that is to find the device name in the error message, in this case `/dev/ttyACM1`. Then check two things:

1. Does the device file exist in the `/dev` tree? `ls -l /dev/ttyACM*`
2. Is the Arduino IDE configured to use the correct device? Check under `Tools` =\> `Serial Port`.

Maybe another application is using the device. When working on Linux, you can verify this with the following commands:

```
$ lsof /dev/ttyUSB0
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF      NODE NAME
avrdude 7356   jippie    3u   CHR  188,0      0t0 266450197 /dev/ttyUSB0

```

or

```
€ fuser /dev/ttyUSB0
/dev/ttyUSB0:         7356

```

Where of course you have to replace `/dev/ttyUSB0` with the device file as mentioned in the error message. In case of this question `/dev/ttyACM1`, but do notice that the number can change when you unplug the board for a moment and then replug it.

In both results, the `7356` is the PID of the process that is locking the device. In my example I was reading flash from the command line, so the output for your specific situation will be different. To identify the process, you can use:

```
$ ps -fp 7356
UID      PID  PPID  C STIME TTY          TIME CMD
jippie  7698 28116  1 20:34 pts/8    00:00:00 avrdude -patmega1280 -carduino -P/dev/ttyUSB002 -b57600 -D -Uflash:r:/tmp/flash:i

```

or a more portable command:

```
$ ps -ef | grep 7356
jippie  7698 28116  1 20:34 pts/8    00:00:00 avrdude -patmega1280 -carduino -P/dev/ttyUSB002 -b57600 -D -Uflash:r:/tmp/flash:i

```

# Answer
> 2 votes
A pretty detailed troubleshooting guide is available at arduino.cc. Besides the checks already mentioned in the question and the answers, it is recommended to check that `serial.download_rate` is set to `19200` in `~/.arduino/preferences.txt`.

`19200` is the default baud rate used by most bootloaders, so this doesn't apply if you don't use one, or use a modified version.

# Answer
> 1 votes
Try setting the baud rate to 9600 in the Serial Monitor. You need a working serial port to open the Serial Monitor. Or go to \>File \>Preferences\> and edit the preferences.txt (must close Arduino IDE before editing) "serial.debug\_rate=9600"

I have several Arduino boards and had the exact same issue with the boards that use the Atmel mega8U2 as the USB - serial bridge. The boards with the FTDI USB bridge (SparkFun Red board, Pro mini) did not show the same problem. Setting the baud rate solved my problem.

There is a firmware upgrade for 8U2 that might fix it but I didn't want to risk making bricks. ;-)

# Answer
> 1 votes
I have same problem after set baud rate to 14400. For fix this I manual set serial.debug\_rate=115200 in config file ~/.arduino/preferences.txt

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


title: Micro USB to USB adapter m/m

text:
# Question
Title: Micro USB to USB adapter m/m
I'm looking into working with an Arduino micro, and I'd like to be able to plug it into my computer directly(without a cable). I've been looking around, and the best thing that I found was this. The reason I haven't bought the linked adapter is because I've seen a number of bad reviews of the seller with close to half of the reviews being 1-star. Anybody have an idea where I can find something similar?

EDIT: I'm going to be using this for security testing, emulating a rubber ducky usb, so I need the computer to recognize the Arduino as an HID, not an arduino, but I also (obviously) need to be able to load my code onto it

# Answer
> 2 votes
That adapter is not suitable. Not only is it the wrong gender on the large end, but it is designed for a completely different purpose.

That is an "On The Go" adapter which is designed for connecting things with a USB A plug (such as a memory stick, etc) to a mobile phone's USB socket. It is not suitable for connecting things to an Arduino.

I have never heard of an adapter like you want, but I have heard of Arduino-like boards that plug direct into a computer like you want. One example is the Digispark from Digistump which is an ATTiny85 on a USB plug.

---
Tags: usb, arduino-micro
---


# Question
Title: Setting Up a JavaEE app on an Arduino Yun Board
I'm looking for some reference material to start on a project I'd like to do.

I have an Open House at my school. My group project has been to create a little timesheet app using JavaEE. I just started looking for how to do this and if I can. But I would like to wow people a bit by setting this up using an Arduino Yun board. I know it has WiFi and I'm pretty sure I can run Linux on the little guy.

Any help would be greatly appreciated.

# Answer
> 0 votes
Sorry, forget it. 64Mb ram, 16Mb flash what the Yun has. Java EE is magnitudes bigger (and bugger) than that.

You might try with Java SE embedded, the smallest profile might fit to 11Mb: http://www.oracle.com/us/technologies/java/oracle-javase-embedded-ds-365290.pdf and then you can roll your own web server.

(Personal comments: For little timesheets JavaEE is overkill, for anything modern JavaEE is obsolete - consider modern Java micro web frameworks, which offer magnitudes better performance than JavaEE).

What you can try is Raspberry PI, which works well with network, and Java (SE). Not that well but also Java EE works: https://blogs.oracle.com/theaquarium/entry/glassfish\_4\_on\_the\_raspberry

---
Tags: arduino-yun, java
---


title: Get strings from Serial.read()

text:
# Question
Title: Get strings from Serial.read()
I want to read strings from `Serial.read()` to send them later.

To get the data from the Serial monitor I'm doing this:

```
String stringOne  = "";
int  incomingByte;

if (Serial.available() > 0) {

  while(Serial.available() > 0)
  {
     incomingByte= Serial.read();
     stringOne = String(stringOne + String(incomingByte));
  }

  Serial.println(stringOne);
  stringOne = "";

```

The issue is that when I type:

```
'a'

```

I got:

```
'97'

```

for 'abc'

I got

```
'979899'

```

so on and so forth.

What should I do in order to get the same string I type?

# Answer
> 6 votes
You're adding the ASCII value of each char to your string, hence you get numbers. See the various String constructors at: https://www.arduino.cc/en/Tutorial/StringConstructors

Either cast the read byte to a char:

```
stringOne = String(stringOne + String((char)incomingByte));

```

or consider receiving characters as chars, instead of ints:

```
char incomingByte;

```

There is a perfectly valid one-method call which does all of this hassle easier and more efficiently: https://www.arduino.cc/en/Serial/ReadStringUntil

Note that you'll sooner or later anyhow have to add a framing prototcol. For example, you're sending down text commands to Arduino, and each command is separated by a new line character. ReadStringUntil will handle that very nicely.

# Answer
> 2 votes
Instead of using:

```
while(Serial.available() > 0)
  {
     incomingByte= Serial.read();
     stringOne = String(stringOne + String(incomingByte));
  }

```

Use the following to cast them to character:

```
while(Serial.available() > 0)
  {
     char incomingByte= Serial.read();
     stringOne.concat(incomingByte));
  }
Serial.println(stringOne);
stringOne="";

```

---
Tags: serial, string
---


# Question
Title: burn arduino bootloader and compiled sketch at same time
How can I write the bootloader and sketch code to an Arduino through the ISP and then write the sketch code again using the Arduino IDE later?

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

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

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

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

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

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

```

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

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

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

# Answer
> 1 votes
Normally (using the IDE via the serial/USB interface) the bootloader is retained, and the bootloader itself replaces the main code.

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

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

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

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

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

The hex file format, as documented in my programmer sketch is:

```
Line format:

  :nnaaaatt(data)ss

  Where:
  :      = a colon

  (All of below in hex format)

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

            * We don't use these

```

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

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

---
Tags: bootloader, isp
---


# Question
Title: Field Programming a Arduino with another Arduino with SD card over RX/TX lines
I am not sure if this question has been asked before but here's what I wanted to do.

I have a Arduino Nano, which I need to update with a new sketch. The plan is to be able to use another Arduino (maybe a Nano again), with an SD card reader and a sketch loaded as HEX file on it. Then connect both using a 4 pin RX/TX/5V/GND and upload the sketch from the transmitter to the receiver. Is it possible?

I am not sure how to do this; I know I can use one Arduino as an ISP to update other, but I am thinking of streaming the hex file to the other. Has anyone done this, any hints would be extremely helpful.

# Answer
There's actually a library for that as well! See here and here.
> 1 votes

# Answer
See What happens when code is uploaded using the bootloader?

There is a graphic on that page (reproduced below) which shows the general idea of what happens when you program using Tx/Rx after reset.

You could delve into the specs for the STK500 protocol (see linked page) and make your second Arduino follow that, to program from the SD card file.
> 0 votes

---
Tags: arduino-nano, uploading, firmware
---


# Question
Title: Print string from arduino to serial monitor
I want to send text over serial monitor to Arduino and make Arduino return that string back to me over serial monitor.

I have made this function which reads from serial input and returns a string object.

```
String readSerial() {
    String input;
    while(Serial.available() > 0)
        input.concat(Serial.read());
    return input;
}

```

In the `loop()` I have:

```
if(Serial.available()) Serial.print(readSerial());

```

If I just do something like `Serial.print("Hello world!");` everything is fine. But, if I try to return string object I get lot's of numbers.

I guess `Serial.print` doesn't know how to read `String` object and returns ASCII codes of characters or something?

**\[update\]** I have checked it, and it's indeed outputing ASCII codes. For `Hi` I get `72105`.

**\[update\]** I have updated my `readSerial` function to use this :

```
input += (char)Serial.read();

```

But now I'm getting carriage return and new line after every character:

```
[SEND] Hi
H(CR)
i(CR)

```

So, how can I make it return my text so that is readable?

# Answer
> 1 votes
`String.concat()` takes a `String` as the second argument. `Serial.read()` returns an `int`. The compiler creates code that converts the `int` into a `String` similar to this:

```
input.concat(String(Serial.read()));

```

This is not what you want.

Let's tell the compiler what you really want instead:

```
input.concat((char)Serial.read());

```

This will tell the compiler to do the following:

```
input.concat(String((char)Serial.read()));

```

We are now having the compiler call the correct `String` constructor, and the code will work as we expect.

# Answer
> 0 votes
Answering the other part of the question:

* you're getting CRs because your readString is just wrong.

The problem is that you don't wait for receiving a whole line of string. For example, if you press H on the serial monitor, then it is getting received and echoed back as if it would been the whole input, ending with a new line.

You might wish to check my answer at Get strings from Serial.read() that is use https://www.arduino.cc/en/Serial/ReadStringUntil which reads you the whole string until a separator (for example the whole string until it ends with a CR when you press Enter on the serial monitor).

---
Tags: serial, string
---


# Question
Title: Thermistor value correct on Uno backwards on Nano
EDIT: upon further investigation: I found out that if I wired it Thermistor \> resistor \> GND values go one direction. If I wired it Thermistor \> Resistor \> 5v, it goes the other direction. So my new question: Which way is correct? One sketch assumes it works one way, and one the other.

I have some Thermistors from here. I have an Arduino Nano and an Arduino Uno, both set up identically with pictures of the wiring below. On the sketch below, when I heat up the thermistor the value increases on the Uno and decreases on the Nano.

```
// which analog pin to connect
#define THERMISTORPIN A0
// resistance at 25 degrees C
#define THERMISTORNOMINAL 10000
// temp. for nominal resistance (almost always 25 C)
#define TEMPERATURENOMINAL 25
// how many samples to take and average, more takes longer
// but is more 'smooth'
#define NUMSAMPLES 5
// The beta coefficient of the thermistor (usually 3000-4000)
#define BCOEFFICIENT 3950
// the value of the 'other' resistor
#define SERIESRESISTOR 9800

int samples[NUMSAMPLES];

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

void loop(void) {
  uint8_t i;
  float average;

  // take N samples in a row, with a slight delay
  for (i=0; i< NUMSAMPLES; i++) {
       samples[i] = analogRead(THERMISTORPIN);
   delay(10);
  }

  // average all the samples out
  average = 0;
  for (i=0; i< NUMSAMPLES; i++) {
     average += samples[i];
  }
  average /= NUMSAMPLES;

  Serial.print("Average analog reading ");
  Serial.println(average);

  // convert the value to resistance
  average = 1023 / average - 1;
  average = SERIESRESISTOR / average;
  Serial.print("Thermistor resistance ");
  Serial.println(average);

  float steinhart;
  steinhart = average / THERMISTORNOMINAL;     // (R/Ro)
  steinhart = log(steinhart);                  // ln(R/Ro)
  steinhart /= BCOEFFICIENT;                   // 1/B * ln(R/Ro)
  steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
  steinhart = 1.0 / steinhart;                 // Invert
  steinhart -= 273.15;                         // convert to C

  Serial.print("Temperature ");
  Serial.print(steinhart);
  Serial.println(" *C");
  Serial.println();

  delay(1000);
}

```

On the sketch below, the Uno is backwards and the Nano is correct. I'm sure there's something simple I'm missing, but I sure can't find it. Any suggestions?

```
#include <math.h>

double Thermistor(int RawADC) {
 double Temp;
 Temp = log(10000.0*((1024.0/RawADC-1)));
 Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
 Temp = Temp - 273.15;
 Temp = (Temp * 9.0)/ 5.0 + 32.0;
 return Temp;
}

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

void loop() {
  int val;
  double temp;
  val=analogRead(7);
  temp=Thermistor(val);
  Serial.print("Temperature = ");
  Serial.print(temp);
  Serial.println(" F");
  delay(1000);
}

```

Nano Wiring

Uno Wiring

# Answer
> 0 votes
There is no "correct" way. The thermistor and the resistor combine to make a voltage divider. Whether the thermistor is connected to +5V (AKA R1) or to GND (AKA R2) determines the formula to use to calculate the resistance.

The general form is:

```
          R2
Vout = ------- x Vin
       R1 + R2

```

To solve for R2 (thermistor connected to GND) you re-arrange to:

```
                 1
R2 = R1 x --------------
          (Vin/Vout) - 1

```

To solve for R1 (thermistor connected to +5V) it's:

```
     R2 x Vin
R1 = -------- - R2
       Vout

```

Vin, of course, is 5V, and Vout is a voltage you calculate from the analog reading on the Arduino.

Once you have the resistance you can then calculate the temperature. That part doesn't change regardless of the orientation of the thermistor.

---
Tags: arduino-uno, sensors
---


# Question
Title: How to make servo rotate for angle bigger than 180°
Connected servo motor (180°) to Arduino Uno R3.

Currently I am using a servo motor which have rotation angle specified as 180°, but I have a requirement to rotate to certain angles greater that 180°.

So do I need to go for a *continuous rotation servo motor (360°)*, so that I can stop the motor at different angles greater than 180°, was my assumption true, will continuous rotation servo motor satisfy this requirement?

I am referring to Servo - Generic High Torque Continuous Rotation (Standard Size)

Current code, which I am using 180° servo motor.

```
Servo myservo;
int pos = 0;
void setup() {
  myservo.attach(9);
}

void loop() {
   {
    myservo.write(180);
    delay(15);
  }
}

```

# Answer
No. The continuous rotation servo rotates *continuously* and you can not control where to stop. You can control the rotation direction and the speed at a little.

What you need is either a special 270 degree servo, or you can use some mechanic, e.g. gears to transform the 0..180 rotation to 0..whateverrotation you prefer, depending on the gearbox ratio.

Alternatively, you can use stepper motors, where you can control steps in 1.8 degrees, and at the same time free to move as many turns as you prefer. Note though that steppers have two disadvantages compared to servos:

* steppers require electrical current to hold their current position - for servo, the gearbox works ok for this
* steppers don't know their initial position. So you need an optointerrupter or other means to learn the initial position first, then drive the steps to get to any position.
* steppers require a more serious driving circuit, as well as a good power supply. Not for DIY robot running on batteries.

In industrial solutions, the stepper motor + some gearbox + an absolute rotation encoder is used to compose an industrial servo drive. (Similarly as a DC motor + some gearbox + an inexpensive potentiometer works in a model servo.)
> 5 votes

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


title: Varying motor speed with the L293D

text:
# Question
Title: Varying motor speed with the L293D
Im using a potentiometer to control the speed of two generic 6-8V DC motors. The potentiometer input is scaled from 0-1023 to 0-255, I then use the analogWrite() function to write this value to the enable pins on my L293D motor controller.

Im sure this should control the speed but it doesn't, I have the code printing the value it sends to the enable pins and this is correct, but no speed increase, the motors either move at one speed or don't move at all. My enable pins are 12 and 13 on my Arduino Uno, previously 5 and 6 but I moved them to see if that was the problem.

Is there a problem with the PWM frequency maybe? I don't understand why it won't go faster and slower after days of troubleshooting.. The inputs are all set correctly, allowing both motors to move in the forward direction..

```
int Speed = analogRead(speedChange);
int SpeedMap = map(Speed,0,1023,0,255);
analogWrite(enable1, SpeedMap);
analogWrite(enable2, SpeedMap);

```

Its a long shot but does anyone know enough about PWM control on DC motors to think of any things I may be missing while trying to do this? Ill provide any info ASAP, thanks

# Answer
Although I am still figuring things out, but i hope the following things help:

http://www.solar4rschools.org/sites/default/files/robotic-sunflower-lesson4-handout4.pdf

The problem, as far as I think is that the enable pins are the ones which are supposed to help you control the speed. Please connect them to the PWM ports on your Arduino/any other device you may be using for your project.

Or, you can simply write a code which keeps on disabling and enabling the enable pins to get the desired speed (that's what PWM is supposed to do but you can try it this way, at least).
> 2 votes

# Answer
I guess you're not using the designated PWM pins provided on the Arduino Board, anyhow I suggest you read this instructible: http://www.instructables.com/id/Arduino-DC-motor-speed-and-direction-L293D/step2/L293D-Pin-Layout/ ,Perhaps this can help you in making proper connections and also help you with the code :)
> 1 votes

---
Tags: arduino-uno, motor, h-bridge
---


# Question
Title: How to avoid blocking while loop reading Serial?
I am currently playing with a MindWave Mobile headset. I am parsing bluetooth data received from a connected BlueSMIRF Silver. The code I started from is a sample from the MindWave wiki and it works using hardware Serial. For reference here is the original code:

```
////////////////////////////////////////////////////////////////////////
// Arduino Bluetooth Interface with Mindwave
//
// This is example code provided by NeuroSky, Inc. and is provided
// license free.
////////////////////////////////////////////////////////////////////////

#define LED 13
#define BAUDRATE 57600
#define DEBUGOUTPUT 1

#define GREENLED1  3
#define GREENLED2  4
#define GREENLED3  5
#define YELLOWLED1 6
#define YELLOWLED2 7
#define YELLOWLED3 8
#define YELLOWLED4 9
#define REDLED1    10
#define REDLED2    11
#define REDLED3    12

#define powercontrol 10

// checksum variables
byte generatedChecksum = 0;
byte checksum = 0;
int payloadLength = 0;
byte payloadData[64] = {
  0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;

// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;

//////////////////////////
// Microprocessor Setup //
//////////////////////////
void setup() {

  pinMode(GREENLED1, OUTPUT);
  pinMode(GREENLED2, OUTPUT);
  pinMode(GREENLED3, OUTPUT);
  pinMode(YELLOWLED1, OUTPUT);
  pinMode(YELLOWLED2, OUTPUT);
  pinMode(YELLOWLED3, OUTPUT);
  pinMode(YELLOWLED4, OUTPUT);
  pinMode(REDLED1, OUTPUT);
  pinMode(REDLED2, OUTPUT);
  pinMode(REDLED3, OUTPUT);

  pinMode(LED, OUTPUT);
  Serial.begin(BAUDRATE);           // USB

}

////////////////////////////////
// Read data from Serial UART //
////////////////////////////////
byte ReadOneByte() {
  int ByteRead;

  while(!Serial.available());
  ByteRead = Serial.read();

#if DEBUGOUTPUT
  Serial.print((char)ByteRead);   // echo the same byte out the USB serial (for debug purposes)
#endif

  return ByteRead;
}

/////////////
//MAIN LOOP//
/////////////
void loop() {

  // Look for sync bytes
  if(ReadOneByte() == 170) {
    if(ReadOneByte() == 170) {

      payloadLength = ReadOneByte();
      if(payloadLength > 169)                      //Payload length can not be greater than 169
          return;

      generatedChecksum = 0;
      for(int i = 0; i < payloadLength; i++) {
        payloadData[i] = ReadOneByte();            //Read payload into memory
        generatedChecksum += payloadData[i];
      }

      checksum = ReadOneByte();                      //Read checksum byte from stream
      generatedChecksum = 255 - generatedChecksum;   //Take one's compliment of generated checksum

        if(checksum == generatedChecksum) {

        poorQuality = 200;
        attention = 0;
        meditation = 0;

        for(int i = 0; i < payloadLength; i++) {    // Parse the payload
          switch (payloadData[i]) {
          case 2:
            i++;
            poorQuality = payloadData[i];
            bigPacket = true;
            break;
          case 4:
            i++;
            attention = payloadData[i];
            break;
          case 5:
            i++;
            meditation = payloadData[i];
            break;
          case 0x80:
            i = i + 3;
            break;
          case 0x83:
            i = i + 25;
            break;
          default:
            break;
          } // switch
        } // for loop

#if !DEBUGOUTPUT

        // *** Add your code here ***

        if(bigPacket) {
          if(poorQuality == 0)
            digitalWrite(LED, HIGH);
          else
            digitalWrite(LED, LOW);
          Serial.print("PoorQuality: ");
          Serial.print(poorQuality, DEC);
          Serial.print(" Attention: ");
          Serial.print(attention, DEC);
          Serial.print(" Time since last packet: ");
          Serial.print(millis() - lastReceivedPacket, DEC);
          lastReceivedPacket = millis();
          Serial.print("\n");
        }
#endif
        bigPacket = false;
      }
      else {
        // Checksum Error
      }  // end if else for checksum
    } // end if read 0xAA byte
  } // end if read 0xAA byte
}

```

One problem I have is the blocking while loop in the ReadOneByte function:

```
byte ReadOneByte() {
  int ByteRead;

  while(!Serial.available());
  ByteRead = Serial.read();

#if DEBUGOUTPUT
  Serial.print((char)ByteRead);   // echo the same byte out the USB serial (for debug purposes)
#endif

  return ByteRead;
}

```

I am trying to avoid this so I started drafting a basic state machine approach:

```
#define BAUDRATE 57600

// checksum variables
byte generatedChecksum = 0;
byte checksum = 0;
int payloadLength = 0;
byte payloadData[169] = {0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;

// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;

int payloadIndex;

int state = 0;
const int STATE_WAIT_FOR_FIRST_A        = 0;
const int STATE_WAIT_FOR_SECOND_A       = 1;
const int STATE_WAIT_FOR_PAYLOAD_LENGTH = 2;
const int STATE_WAIT_FOR_PAYLOAD        = 3;
const int STATE_WAIT_FOR_CHECKSUM       = 4;
const String stateNames[5] = {"waiting for first A","waiting for second A","waiting for payload length","accumulating payload","waiting for checksum"};

void setup() {
  Serial.begin(BAUDRATE);           // USB
}
void loop() {}
void parsePayload(){
  poorQuality = 200;
  attention = 0;
  meditation = 0;

  for(int i = 0; i < payloadLength; i++) {    // Parse the payload
    switch (payloadData[i]) {
    case 2:
      i++;
      poorQuality = payloadData[i];
      bigPacket = true;
      break;
    case 4:
      i++;
      attention = payloadData[i];
      break;
    case 5:
      i++;
      meditation = payloadData[i];
      break;
    case 0x80:
      i = i + 3;
      break;
    case 0x83:
      i = i + 25;
      break;
    default:
      break;
    } // switch
  } // for loop
  Serial.print("bigPacket:");
  Serial.println(bigPacket);
  if(bigPacket) {
    Serial.print("PoorQuality: ");
    Serial.print(poorQuality, DEC);
    Serial.print(" Attention: ");
    Serial.print(attention, DEC);
    Serial.print(" Time since last packet: ");
    Serial.print(millis() - lastReceivedPacket, DEC);
    lastReceivedPacket = millis();
    Serial.print("\n");
  }
  bigPacket = false;
}

void printState(){
  Serial.print("state:");
  Serial.println(stateNames[state]);
}
void serialEvent(){
  if(Serial.available() > 0){
    switch(state){
      case STATE_WAIT_FOR_FIRST_A:
        printState();
        if(Serial.read() == 170) state = STATE_WAIT_FOR_SECOND_A;
      break;
      case STATE_WAIT_FOR_SECOND_A:
        printState();
        if(Serial.read() == 170) state = STATE_WAIT_FOR_PAYLOAD_LENGTH;
      break;
      case STATE_WAIT_FOR_PAYLOAD_LENGTH:
        printState();
        payloadLength = Serial.read();
        Serial.print("payloadLength:");Serial.println(payloadLength);
        if(payloadLength > 169){
          Serial.println(payloadLength > 169);
          state = STATE_WAIT_FOR_FIRST_A;
          return;
        }
        generatedChecksum = payloadIndex = 0;
        state = STATE_WAIT_FOR_PAYLOAD;
      break;
      case STATE_WAIT_FOR_PAYLOAD:
        printState();
        if(payloadIndex < payloadLength){
          payloadData[payloadIndex] = Serial.read();
          generatedChecksum += payloadData[payloadIndex];
          Serial.print("payloadData[");Serial.print(payloadIndex);Serial.print(" of ");Serial.print(payloadLength);Serial.print("]: ");
          Serial.println(payloadData[payloadIndex]);
        }else{
          state = STATE_WAIT_FOR_CHECKSUM;
        }
      break;
      case STATE_WAIT_FOR_CHECKSUM:
        printState();
        checksum = Serial.read();
        generatedChecksum = 255 - generatedChecksum;
        if(checksum == generatedChecksum) {
          Serial.println("checksum MATCH! parsing payload");
          parsePayload();
          state = STATE_WAIT_FOR_FIRST_A;
        }else{
          Serial.println("checksum FAIL!");
          state = STATE_WAIT_FOR_FIRST_A;
        }
      break;
    }
  }
}

```

As far as I can understand from the serialEvent() reference this function would be called only when a new byte is available. I've also added a condition to check if `Serial.available() > 0`.

I can see the messages I expect when parsing the data, but only small packets(usually 4 bytes long) end up having a correct checksum and never receive a payload with the useful EEG data I'm looking for.

How can I check that my approach is correct or not/ I'm not loosing bytes using `serialEvent()` instead of the blocking `while(!Serial.available())` ? If so, how can I rewrite the while loop in a non blocking way ?

I've not super experienced with Arduino, but I started reading on interrupts. Would a `USART_RX` interrupt help at all ? (or would it do the same as serialEvent -\> trigger when a new byte is available?)

**Update!** Using Wirewrap's suggestion to use read() which returns -1 if there is no data, I've used peek() which does almost the same, except it doesn't remove the character peeked at from the buffer. For reference here is the code used:

```
#define BAUDRATE 57600
#define DEBUGOUTPUT 1

// checksum variables
byte generatedChecksum = 0;
byte checksum = 0;
int payloadLength = 0;
int payloadIndex;
byte payloadData[169] = {0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;

// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;

int state = 0;
const int STATE_WAIT_FOR_FIRST_A        = 0;
const int STATE_WAIT_FOR_SECOND_A       = 1;
const int STATE_WAIT_FOR_PAYLOAD_LENGTH = 2;
const int STATE_WAIT_FOR_PAYLOAD        = 3;
const int STATE_WAIT_FOR_CHECKSUM       = 4;

void setup() {
  Serial.begin(BAUDRATE);           // USB
}
void loop() {}
void parsePayload(){
  poorQuality = 200;
  attention = 0;
  meditation = 0;

  for(int i = 0; i < payloadLength; i++) {    // Parse the payload
    switch (payloadData[i]) {
    case 2:
      i++;
      poorQuality = payloadData[i];
      bigPacket = true;
      break;
    case 4:
      i++;
      attention = payloadData[i];
      break;
    case 5:
      i++;
      meditation = payloadData[i];
      break;
    case 0x80:
      i = i + 3;
      break;
    case 0x83:
      i = i + 25;
      break;
    default:
      break;
    } // switch
  } // for loop
  if(bigPacket) {
    Serial.print("PoorQuality: ");
    Serial.print(poorQuality, DEC);
    Serial.print(" Attention: ");
    Serial.print(attention, DEC);
    Serial.print(" Time since last packet: ");
    Serial.print(millis() - lastReceivedPacket, DEC);
    lastReceivedPacket = millis();
    Serial.print("\n");
  }
  bigPacket = false;
}

void serialEvent(){
  if(Serial.peek() >= 0){
    switch(state){
      case STATE_WAIT_FOR_FIRST_A:
        if(Serial.read() == 170) state = STATE_WAIT_FOR_SECOND_A;
      break;
      case STATE_WAIT_FOR_SECOND_A:
        if(Serial.read() == 170) state = STATE_WAIT_FOR_PAYLOAD_LENGTH;
      break;
      case STATE_WAIT_FOR_PAYLOAD_LENGTH:
        payloadLength = Serial.read();
        if(payloadLength > 169){
          state = STATE_WAIT_FOR_FIRST_A;
          return;
        }
        generatedChecksum = payloadIndex = 0;
        state = STATE_WAIT_FOR_PAYLOAD;
      break;
      case STATE_WAIT_FOR_PAYLOAD:
        if(payloadIndex < payloadLength){
          payloadData[payloadIndex] = Serial.read();
          generatedChecksum += payloadData[payloadIndex];
          payloadIndex++;
        }else{
          state = STATE_WAIT_FOR_CHECKSUM;
        }
      break;
      case STATE_WAIT_FOR_CHECKSUM:
        checksum = Serial.read();
        generatedChecksum = 255 - generatedChecksum;
        if(checksum == generatedChecksum) {
          parsePayload();
          state = STATE_WAIT_FOR_FIRST_A;
        }else{
          state = STATE_WAIT_FOR_FIRST_A;
        }
      break;
    }
  }
}

```

# Answer
Interestingly enough, **Serial.read()** does not work like most of us think.

Serial.read() is not blocking, it always returns immediately with a byte 0-255 or -1 if there is no character to read.

From Arduino Reference

> **Description**
>
> Reads incoming serial data. read() inherits from the Stream utility class.
>
> **Syntax**
>
> Serial.read()
>
> **Parameters**
>
> None
>
> **Returns**
>
> the first byte of incoming serial data available (or -1 if no data is available) - int
> 7 votes

# Answer
Nick Gammon, a moderator on the official Arduino site and a very active member of the Arduino community on Stackoverflow, has done a very nice post on reading serial without blocking. I've posted the relevant code. /\* Example of processing incoming serial data without blocking.

```
Author:   Nick Gammon
Date:     13 November 2011.
Modified: 31 August 2013.

Released for public use.
*/

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

void setup (){
Serial.begin (115200);
} // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
 {
 // for now just display it
 // (but you could compare it to some value, convert to an integer, etc.)
 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

```
> 3 votes

# Answer
I don't like `serialEvent()` because it only checks to see if it should run that function after the whole loop is executed. With your new example, it's basically the same as the original (except you moved that code to the very bottom of the loop).

I'm not sure exactly how fast the data is sent, but you should first ask yourself if the data is sent fast enough that you don't even notice that it's blocking. Blocking code isn't bad itself (except maybe from a standpoint of the other device freezing up and stalling your program), but blocking code *that takes a long time* is bad.

Since you need five bytes, the best thing would be to wrap the blocking code in an if statement like this:

```
if(Serial.available >= 5) {
  //Blocking code here
}

```

It's simple and readable, yet effective.
> 2 votes

# Answer
Since then I've figured out how to rewrite the code to be non-blocking, by replacing the while loop with states, accumulating one byte at a time.

I've written my first Arduino library with this occasion: Mindwave. Here's a basic example:

```
#include <Mindwave.h>                   //import the library
Mindwave mindwave;                      //start using it

void setup() {
  Serial.begin(MINDWAVE_BAUDRATE);      //setup serial communication (MindWave mobile is set to 57600 baud rate)
}
//create a function to received new values as soon as they're avaialble
void onMindwaveData(){
  Serial.print("attention: ");
  Serial.println(mindwave.attention()); //access attention value
}
void loop() {
  mindwave.update(Serial,onMindwaveData);//update using the data input(Serial in this case) and the function to call when data is ready
}

```

It's non blocking, you can see the implementation here

This was used for the Walk with Me art installation.
> 2 votes

---
Tags: arduino-uno, serial, programming
---


# Question
Title: Arduino clone CH340G (ATmega328P), MIDI over USB
I just bought my first Arduino compatible device, and I am greatly enjoying it. I finally could not resist the urge after going to an Arduino meetup, where someone showed me their `Teensy` connected to their laptop and reacting to MIDI signals over USB.

Not knowing anything, I bought my clone and soon learned about the whole `CH340G` limitation where it doesn't "just work" (I cannot simply use the USBMIDI Arduino library), and instead I need to run a software MIDI-serial converter command (`ttymidi`) in order to send the signals to my Arduino clone.

I've been reading up a bit (the amount of information out there is perhaps too vast and often outdated or simply doesn't exactly solve my problem) and have learned of V-USB and the project V-USB-MIDI but I am really out of my element here and do not know how to approach this to get it all working (since it is not just an Arduino sketch and `.h` header). Or even if this is a solution to my problem. I've read about some solutions which require using an AVR via some of the pins (as opposed to over USB) since you have to reprogram the chip in such a way that it no longer is programmable over USB once the sketch is uploaded, but if I understood it correctly, you can't do even this on the `CH340G`.

In any case, are there any examples of getting this working? A sketch or something? I downloaded the latest V-USB release, but I really don't want to make a mistake that will brick or otherwise ruin my device.

Basically: I want to just upload my MIDI sketch (with whatever necessary modifications or code) such that I do not need `ttymidi` to have the device recognized as a MIDI device (over USB) that I can just "plug 'n' play".

# Answer
> 2 votes
V-USB bit bangs some GPIO pins so that they speak the low-speed USB protocol. This does not use the 'normal' USB connection through the CH340; you would have to solder a separate USB cable to those GPIO pins.

Programming would be no problem; the V-USB code is just normal code that runs on the MCU. (Programming through ISP pins would be required on hardware where USB communication and programming is handled with a *second* AVR MCU; in that case, the USB/MIDI code would run on that second MCU.)

Low-speed USB is not supposed to be used for MIDI, and as a software emulation, V-USB does not work very well, or efficiently. If you want to create a USB device, you should use an MCU that actually supports USB in hardware, such as the ATmega32U4 or AT90USB646 used on some Teensies.

---
Tags: usb, midi
---


title: HC-05 to low cost AB shutter 3

text:
# Question
Title: HC-05 to low cost AB shutter 3
I'm trying to connect a HC-05 to AB Shutter3 module. However, when I try to search AB Shutter3 address via AT commands (`AT+INQ`) I could not find AB Shutter3.

I want to integrate both, so that I can send commands from an AB Shutter button click to HC-05.

I also want to know whether the HC-05 needs to be in master or in slave mode.

# Answer
> 0 votes
I rather suspect the AB Shutter 3 is a Bluetooth HID device (like a keyboard or a mouse). The HC-05 can only communicate with Bluetooth Serial devices, such as the HC-06 or systems that can emulate a serial device (such as a computer or a smartphone).

You won't get them to communicate no matter how hard you hit them.

---
Tags: arduino-uno, bluetooth, hc-05
---


# Question
Title: Where do avrdude parameters get defined in the Arduino IDE?
I am interested in learning how the Arduino IDE handles parameters in order to correctly upload hex files with *avrdude*.

I found this in *boards.txt*:

```
uno.name=Arduino/Genuino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
uno.vid.2=0x2A03
uno.pid.2=0x0043
uno.vid.3=0x2341
uno.pid.3=0x0243

uno.upload.tool=avrdude
uno.upload.protocol=arduino
uno.upload.maximum_size=32256
uno.upload.maximum_data_size=2048
uno.upload.speed=115200

uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0x05
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

uno.build.mcu=atmega328p
uno.build.f_cpu=16000000L
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

```

There is this in *platform.txt*:

```
# AVR Uploader/Programmers tools
# ------------------------------

tools.avrdude.path={runtime.tools.avrdude.path}
tools.avrdude.cmd.path={path}/bin/avrdude
tools.avrdude.config.path={path}/etc/avrdude.conf

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

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

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

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

```

This line is particularly interesting:

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

```

It seems like these variables are corresponding:

```
{cmd.path} --> tools.avrdude.cmd.path
{config.path} --> tools.avrdude.config.path
{upload.verbose} --> tools.avrdude.upload.params.verbose
{build.mcu} --> uno.build.mcu
{upload.protocol} --> uno.upload.protocol
{serial.port} --> ?
{upload.speed} --> uno.upload.speed
{build.path} --> ?
{build.project_name} --> ?

```

It seems these are likely used in the Java code for the IDE. There are obviously a few I am unsure of. I would guess these are considered user inputs in the IDE. Though I am by no means a Java or JavaScript programmer.

Where are these variables explicitly defined in the Arduino library? (e.g. `{runtime.tools.avrdude.path}`, `{path}`, `{cmd.path}` ....) Or how do they get defined by IDE?

# Answer
> 1 votes
There are 3(or 4) places that you need to look at to know how to upload.
There is the boards.txt file and the platform.txt file.
You can consider a platform.txt file line

```
tools.avrdude.path={runtime.tools.avrdude.path}

```

as (in linux in windows replace ${xx} by %xx%)

```
set tools.avrdude.path ${runtime.tools.avrdude.path}

```

and the board.txt for the selected board like

```
uno.bootloader.tool=avrdude

```

as

```
set bootloader.tool avrdude

```

The arduino ide uses the following string to know the upload command environment variable

```
tools.${bootloader.tool}.upload.pattern

```

This way it knows the command to upload is

```
"{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

```

{cmd.path} is hardcoded as tools.${bootloader.tool}.cmd.path which equals {path}/bin/avrdude
where {path} is to be understood as tools.${bootloader.tool}.path wich equals {runtime.tools.avrdude.path}.
{runtime.tools.avrdude.path} is defined by the boardsmanager based n the json file and the location where the boardsmanager extracted the download.

So that makes 3 files: boards.txt, platform.txt and json file and some hard coding.

A 4th file comes into play when you use the "other upload commands". These are located in the programmers.txt file.

IMHO Arduino IDE core team did not opt for the simplest solution to define these things. They also change the way they work from time to time.
If you use a makefile know that a lot of people have done this already so it may be a good idea to "reuse other peoples work" instead of "reinventing the wheel". It is not so easy or straightforward.

**Note** I know all these things because I implemented the Arduino eclipse IDE. As far as I know none of this is documented.

# Answer
> -1 votes
The Arduino library is about what runs on the target, while the "IDE" (not sure if it can still be called IDE, as now they try to do also command line) is about everything else.

But my impression is that if you are ready to ask these sort of question, you could consider dropping the IDE and moving to a more standard Makefile approach. Or Maybe Eclipse, where you still have the IDE, but you can define everything in a more standard way.

The Arduino approach is good to get people with little experienced started, but after a while one started to feel its limitations.

---
Tags: arduino-ide, uploading, avrdude, core-libraries
---


# Question
Title: How can I exactly put my sensor at 4 Hz readings?
I'm using the grove GSR sensor: http://www.seeedstudio.com/wiki/Grove\_-\_GSR\_Sensor with this code:

```
const int GSR=A0;
int threshold=0;
int sensorValue;
const long interval = 1000;
void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){
  int temp;
  sensorValue=analogRead(GSR);
  Serial.println(sensorValue);
  temp = threshold - sensorValue;
  delay(250);
  }

```

There is the delay way to skip milliseconds or the `millis()` function. Do you have ideas on how can I implement it? The delay has the problem that doesn't consider the time the sensor uses to read the data.

Here's what I am trying

```
const int GSR=A0;
int threshold=0;
int sensorValue;
const long interval = 1000;
unsigned long startTime=millis();

void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){

  if((millis() - startTime) % 250 == 0) {
   int temp;
  sensorValue=analogRead(GSR);
  Serial.println(sensorValue);
  temp = threshold - sensorValue;

  }
  }

```

# Answer
The difference between your first code and the second one is that the first one is blocking execution when it reaches the `delay` function, but the second code keeps running without being blocked.

Now your algorithm has a drawback, the loop may or may not reach the `if` condition exactly when the modulo is strictly equal to 0. So you may prefer to use something like :

```
unsigned long T = millis();

...

if( millis() - T >= 250 ) {
    ... // sensor stuff
    T = millis();
}

```

This idea is also presented in this article https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.

Another approach is to use Timers and Interrupts, but this is far more complicated (http://playground.arduino.cc/Code/Timer1).
> 2 votes

# Answer
Both other answers are correct, but my usual way of dealing with this is

```
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
...
void loop()
{
    if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        // Do your job, such as
        int temp;
        sensorValue=analogRead(GSR);
        Serial.println(sensorValue);
        temp = threshold - sensorValue;
    }
}

```

The difference between this way and the other ones (Nick's way, i.e. saving `millis` and setting the `startTime` variable to it, or nico's one - which is worse - , to set it again), is that this way if there is some error (e.g. 260ms between two calls) it gets recovered by the next cycle (which will be of 240ms), while in their way it is not.
> 2 votes

# Answer
Something like this should do it:

```
const byte LED = 13;
unsigned long lastReading;
const unsigned long INTERVAL = 250;

void setup()
  {
  pinMode (LED, OUTPUT);
  }  // end of setup

void loop()
  {
  unsigned long now = millis ();
  if (now - lastReading >= INTERVAL)
    {
    lastReading = now;
    digitalWrite (LED, HIGH);
    delay (50);  // simulate reading delay
    digitalWrite (LED, LOW);
    }
  }  // end of loop

```

This code saves when we are *about to* do a reading, and uses that as the basis for when to do the next one. This eliminates the reading time from the equation. In my example code I throw in a 50 ms delay to prove the point.

The LED flashes exactly at 250 ms intervals.
> 0 votes

---
Tags: arduino-uno, c++, arduino-nano
---


# Question
Title: How to perform a data transfer to an external server
So I'm doing a project that involves getting sensor data from several sensors, and then sending them to an external server when a tragic occurs. But I've been having trouble figuring out how to send this data, and I am welcome to advice (I'm still relatively new to Arduino coding).

I'm using an Arduino mega, with a sim900 GSM shield and an SD card. The sensors are just analog reads and a GPS.

I've looked into FTP, a Xively account and http requests to a web server but couldn't figure it out.

# Answer
> 1 votes
There is a good example of using the **SubmitHttpRequest()** in this article: GPRS Shield SIM900 Arduino

You could easily modify: **mySerial.println("AT+HTTPPARA=\\"URL\\",\\"www.yourwebsite.com/testing.php\\"");**

to include a string of the sensor value, and then using a PHP script to MySQL on your webserver. Maybe something like: http://**yourwebsite.com**/testing.php?**sensor1**=5&**sensor2**=10

---
Tags: arduino-mega, sensors, gsm, sd-card
---


# Question
Title: Need to make an action just once when condition is reached
I'm making a device for the visually disabled that makes a sound when the water in a bowl reach certain levels.

I've already made the sensors for three levels of water and if statements to make the sound, but I need the sound to be played just once for every level change and it loops over and over. How can I make it to sound just one time?

Here is my code:

```
#include <PCM.h>
const unsigned char sample[] PROGMEM = { //Here goes the sample
};
int low = 0;
int mid = 0;
int high = 0;

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

}

void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
  }
  else if (mid >50){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
  }
  else if (low > 50){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
  }
  delay(100);

```

# Answer
> 3 votes
A possible solution to your problem can be the following:

```
#include <PCM.h>
const unsigned char sample[] PROGMEM = { //Here goes the sample
};
int low = 0;
int mid = 0;
int high = 0;
bool first = true;
bool second = true;
bool third = true;

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

}

void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50 && first){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
    first = false;
  }
  else if (mid >50 && second){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
    second = false;
  }
  else if (low > 50 && third){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
    third = false;
  }
  delay(100);

```

In this way the sound for each level will be played only once. I hope this is what you were looking for.

# Answer
> 0 votes
As an addition to the answer of Mattia.

I suspect you have something like:

```
void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (resetVariables){
     first = true;
     second = true;
     third = true;
     resetVariables = false;
  }

  if (high > 50 && first){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
    first = false;
  }
  else if (mid >50 && second){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
    second = false;
  }
  else if (low > 50 && third){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
    third = false;
  }

  if(buttonPressed){
    resetVariables = true;
  }
  delay(100);
}

```

A better practice would be to use another function

```
void resetFlags() {
  first = true;
  second = true;
  third = true;
}

```

And the main code would be:

```
void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50 && first){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
    first = false;
  }
  else if (mid >50 && second){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
    second = false;
  }
  else if (low > 50 && third){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
    third = false;
  }

  if(buttonPressed){
    resetFlags();
  }
  delay(100);
}

```

Would this be faster?

* It would at least make your loop code more readable, instead of juggling flags around.
* `resetFlags()`; would act immediately and independent from the flag checking etc.
* It saves checking unnecessary if's (which equals a very little speed increase).
* It saves 1 boolean (byte maximal in memory) which equals a very little memory/speed increase.

But why mind speed if you have a 100msec delay? You could make it only output the water level when it changes. Then you can run the water checking extremely fast! (It wouldn't spam your console, plus, writing to console takes considerable amount of time, compared to checking if's.)

---
Tags: c++, arduino-pro-mini, sound
---


# Question
Title: Is it possible to directly set the registers that control the ADC clock on the Arduino?
Is it possible to directly set the registers that control the ADC in an Arduino Yun (micro-controller side is essentially a Arduino Leonardo) from a sketch or is there a specific file somewhere you must edit?

I am working on a project that collects a signal digitizes it and sends it through a digital filter. I looked up the Datasheet for the micro-controller on the Yun and wrote the code setting the registers associated with the ADC portion of the micro controller. The code setting the registers was something like `REGNAME = 0x01;`. Yet when tested several of the associated registers were unaffected. Pointers on the process to set the ADC manually without using the `analogRead()` function would be appreciated.

Edit: My original code looked something like this:

```
void setup(){
    // register to turn on ADC
    REG1 = REG1 | 0x01;

    //register to set sample rate and set ADC to Free Running Mode
    REG2 = REG2 & 0x30;

    // register to set other settings
    REG3 = REG3 | 0xF1;
}

void loop(){
    // code to take samples from ADC
    // and send them through a digital filter here.
}

```

# Answer
> 1 votes
Since your project is about acquiring signals I guess that the sample frequency is important for you. In fact you need to know exactly how much time passes from one sample to another. This cannot be achieved by simple reading the ADC in your loop(). The easiest implementation is to use an interrupt that occurs every n seconds (e.g. every overflow of timerX).

I'm going to write a pseudo-code for this:

```
void SetTimer()
{  TISREG |= 1<<Prescaler_bit   //set the prescaler
   TICNT = 0   //sdt the tarting value
   TIINT |= 1<<OVF_Interrupt_enable
   sei() //enable global interrupt
}

ISR(TIM1_OVF_vect)   //happens every [prescaler*2^bit_timer/F_CPU] seconds
{
   while( !(ADCSREG &= (1<<bit_is_ready)) ) ; //usually there is a bit that is 1 while the ADC has read the data, and 0 while it is doing the conversions

//imagine the ADC stores the 3 MSBits in the ADCHI
//and the LSBits in the  ADCLO

value_high = (ADCHI & 0b00000111);
value_low = ADCLO;

value = (value_high << 7) | value_low;

}

```

# Answer
> 1 votes
I can see no problem with your pseudo-code. You should probably post a complete testable code in order to get better feedback.

That being said, here are a few suggestions:

1. You should *completely set* the ADC registers to the values that suit your application, instead of just changing a few bits here and there. This is because you should not care about how the Arduino core library initializes those registers, especially if this is a prototype for a final product that will not use Arduino core. For example, instead of

```
REG1 = REG1 | 0x01;

```

you can write something like this:

```
REG1 = _BV(FOO)   // use foo mode...
     | _BV(BAR);  // ...in the bar setting

```

where `_BV(x)` is a macro from avr-libc that expands to `(1<<(x))`, and the bit names are those of the datasheet, for better readability.

2. You may want to run the digital filter in the ADC interrupt service routine. If you can split your processing into a fast filter (processing every sample) and a slow filter (running on decimated samples), then do only the fast one in the ISR and leave the slow one to the main loop. I say this from experience: when I tried to do all the processing in `loop()` I always lost samples, which did not happen when I moved the filter to the ISR.
3. But then, make sure your filter is optimized to be *fast*. Avoid floating point operations in the ISR if at all possible.

I have written a program that looks very similar to what you are trying to do: it samples an analog input at 9.6 kS/s and runs an homodyne detection filter in order to extract the signal power in a very narrow band around 1 kHz. The ADC is set to free running mode. In the ADC ISR, I retrieve the sample, run it through the filter, and store the result into volatile variables. In `loop()`, I read these back from time to time. Here is how I set the ADC:

```
static void configure_adc()
{
    ADMUX  = _BV(REFS0)  // ref = AVCC
           | _BV(ADLAR)  // left adjust result
           | analog_in;  // input channel
    ADCSRB = 0;          // free running mode
    ADCSRA = _BV(ADEN)   // enable
           | _BV(ADSC)   // start conversion
           | _BV(ADATE)  // auto trigger enable
           | _BV(ADIF)   // clear interrupt flag
           | _BV(ADIE)   // interrupt enable
           | 7;          // prescaler = 128
}

```

The complete program is available here: homodyne.ino. It was initially intended for an Arduino Uno, but it runs unmodified on a Leonardo clone.

---
Tags: arduino-yun, adc
---


# Question
Title: Arduino GPRS (GSM) shield (SIM900) no long pins
I have bought a SIM900 shield for an ordinary Arduino Uno board. The problem is that it doesn't have long pins on the bottom side, making it impossible to click on mu Arduino Uno. The shield I have is this:

As you can see, there are identical pin spaces next to the red and yellow plastic female pin things. Can I just solder new pins in the free spaces and will it work like that? I notice that the yellow and red plastic female pin holders on my board are on the free spaces in this picture. I supposed I can just use the adjacent foles to solder long pins so I can use it for my Arduino?

# Answer
Yes, you can.

There is two methods of making shields stackable:

1. Use the quite hard to source extra long pinned headers to go right through and down (such as these https://www.adafruit.com/products/85) , or
2. Use separate headers and pins and (if you are using through hole) offsetting them.

Your shield uses the second method, but the descending pins haven't been populated. By populating those pins you are just completing the build.
> 3 votes

---
Tags: arduino-uno, shields, gsm
---


# Question
Title: Can't upload sketches to breadboard Arduino
* I have an ATmega328 chip with the boot-loader installed.
* I also have an Arduino Uno with the ATmega328 chip removed.
* I hooked this chip up to a breadboard with the proper 22pF caps, 16MHz crystal, and 10kΩ pull-up resistor.
* The LED flasher was loaded prior, and this works fine when I hook an LED and resistor up to pin 19. I have confirmed my external crystal works by disconnecting it, and the flashing stops, when I reconnect the crystal, the flashing continues.
* Power is fed from my Arduino Uno 5 V out to the DIY Arduino
* I connected the reset wire, and data wires, ensuring pin 2 went to RX and pin 3 to TX.

**In the software**

First to confirm everything works, I removed the chip from the breadboard and placed it in the Arduino. The sketch uploaded successfully using the settings: Arduino Uno as board and AVRISP mkll as programmer.

Now I move the chip to the breadboard, and ensure all the wires are connected. The LED starts to blink again, but when I try to upload the sketch, I get an error:

`avrdude: stk500_recv(): programmer is not responding`

I ensure continuity between the reset, TX, RX, and power connections and try different settings like Arduino as ISP and different boards under settings including the Duemilanove and nano but nothing seems to be working.

Any suggestions on what to try next?

# Answer
> 2 votes
Answered by Skyler440:

> Never mind, found the problem. My software switched to the bluetooth for some reason after I changed some other settings.

*Converted to answer to reduce unanswered questions.*

# Answer
> 0 votes
There are two AVR ICs present on the Arduino board, one is used for the USB to ICSP interface and the other one is the μC which you're using.

As I've noticed that you've tried to connect `Tx` and `Rx` pins including reset for programming the IC. Those pins are used for communication on serial protocol, where as the AVR in Arduino is programmed using SPI Protocol, so you should be using MISO, MOSI, SCK, SS (they're pins 13-10 respectively) and Reset pins on the Arduino, then the AVR which is used as USB-SPI bridge for programming can communicate with the μC and program it.

---
Tags: arduino-uno, programming, uploading
---


title: 2WD robot - logic error

text:
# Question
Title: 2WD robot - logic error
I am making a basic 2WD robot using Arduino Uno with motor shield. I am getting no compile errors - but something in my logic flow is not working as expected.

Expected Operation:

1. Ping sensor does distance check.
2. If distance is less than 5cm.
3. Turn both Channel A & B motors half-speed for 1 second.
4. Stop motors.
5. Take new distance reading ping, start again.

What however is happening, is that channel A works as expected, but channel B motor keeps running?? Where is my code / logic mistake?

Later date I will add to `else` statement to turn one wheel to change direction.

```
/*
 HC-SR04 Ping distance sensor:
 VCC to arduino 5v
 GND to arduino GND
 Echo to Arduino pin 7
 Trig to Arduino pin 8
 */

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 1000; // Maximum range needed
int minimumRange = 1; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
  // put your setup code here, to run once:

Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)

  pinMode(12, OUTPUT); /* Motor Channel A RIGHT SIDE*/
  pinMode(9, OUTPUT); /* Motor Channel A */

  pinMode(13, OUTPUT); /* Motor Channel B LEFT SIDE */
  pinMode(8, OUTPUT);

  }

void loop() {

  /* Distance check begins */

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;

 /* End distance check */

 if (distance >= 5){
 /* Distance great enough to provide room to move */
  Serial.println("Move!");

  digitalWrite(LEDPin, HIGH); /* LED show movement */

  digitalWrite(12, LOW); /*move channel A motor half-speed */
  digitalWrite(9, LOW);
  analogWrite(3, 123);

  digitalWrite(13, HIGH); /*move channel B motor half-speed */
  digitalWrite(8, LOW);
  analogWrite(11, 123);

  delay(1000);

  digitalWrite(9, HIGH);
  digitalWrite(8, HIGH);
 }

 else {
 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */
 Serial.println(distance);
 digitalWrite(LEDPin, LOW);
 }

 //Delay 50ms before next reading.
 delay(500);

}

```

# Answer
> 2 votes
I believe that your error is in that you declare `LEDpin` as pin 13 and then your motor B as pin 13 as well, that to me would result in errors when you write to the led in the else statement at the end of your code. I would recommend that you clean this up, don't use pins for different things. Try this first.

Your logic is ok in terms of functionality.

Also why is there inconsistency at this part on your code:

```
digitalWrite(12, LOW); /*move channel A motor half-speed */
  digitalWrite(9, LOW);
  analogWrite(3, 123);

  digitalWrite(13, HIGH); /*move channel B motor half-speed */
 digitalWrite(8, LOW);
  analogWrite(11, 123);

```

Why do you say pin `12` must be`LOW` and `13 HIGH` when moving forward? Is this the way your un-mentioned circuit setup works, if possible could you add this info?

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