title: How to speed up

text:
# Question
Title: How to speed up
I found that using more float variable in arduino uno(atmega328p) slows it down (very muck that i can get slow response)

so, how to speed up it processing ?

my data are euler's angle with 2 digits and 2 decimals like give below

XX.XX , where X is number Eg.(85.63,34.65,etc) (from MPU6050)

How to process it fast?

# Answer
A technique commonly used in digital signal processing is using fixed-point arithmetic instead of floating point. In fixed-point arithmetic, one calculates using numbers multiplied by some power of two or ten, and in effect mentally positions a binary or decimal point several bits or digits up while calculating. Numerical analysis may be needed to determine if the arithmetic is accurate enough and whether numbers will stay in bounds, or overflow.

The question doesn't say what's being calculated; it's possible fixed-point arithmetic might work, or might not. A short self-contained fixed-point calculation that starts with MPU6050 sensor readings is likely to be ok, but long-term calculations (eg, integration of accelerations to get velocities and positions) that let error accumulate without reset may go too far astray. In such a case, numerical analysis can indicate what intermediate results need to be stored most accurately.

Typically, when slow code is posted someone can point out speedups, from a few percent up to dozens of times faster. Changes may range from adding or removing parentheses or temporary variables, to refactoring, to substitution of a new algorithm.
> 3 votes

---
Tags: arduino-uno, programming, mpu6050, float
---


title: Regulator magic smoke

text:
# Question
Title: Regulator magic smoke
I have accidentally released the magic smoke from the regulator on a digispark board. I did this when I accidentally plugged a circuit into the 5V and the VIn instead of the 5V and Gnd, and then plugged the board into the USB port.

The attiny chip still works - I know because I plugged it in to the USB ,with no circuitry attached, and the uploaded program still runs happily.

My question is, is there any possibility that when the magic smoke was released from the regulator, the attiny was also damaged?

Secondly, is there any harm in leaving the dead regulator on the board? Or am I better off cutting it off?

# Answer
Linear voltage regulators have an internal parasitic diode that shorts the output to the input. You have burned out this diode which has destroyed the regulator, but it is highly unlikely that any other components have been damaged. You can get away with cutting away the legs of the regulator, but complete removal will be difficult due to the large size of the tab connection and will likely result in damage to the other components.
> 2 votes

---
Tags: attiny
---


# Question
Title: Arduino Uno + Adafruit Ultimate GPS Shield Serial issue
I've had an Arduino Uno for a couple of months-making basic sketches-and recently purchased an Adafruit ultimate GPS shield and attached with soldered headers. This shield has 2 options for reading data, direct and soft serial.

I can sit near a window in my house and receive data using the direct method. This is just due to uploading a blank sketch and reading the serial window. Next, I tried to use one of the examples included in the Adafruit\_GPS library and the serial window shows a bunch of nonsense updating.

Has anyone else seen this problem? I'm wondering if its the digital pins on the Arduino that I may have damaged since the example code has a simple phrase to display at the start, and I don't even get this.

Code eg: Serial.println("Get version!").

Just to verify, both boards have power and the direct method was giving me good GPS readings, the serial method gave me junk (not even a simple printed phrase to start), and I verified the Soft Serial switch was flipped and the baud rates matched in code and serial window.

I've attached pictures of the direct method results from that in the serial window, and then the junk results using an unaltered sample serial code. Any help with this would be appreciated.

# Answer
It looks like you are using the wrong baud rate somewhere.

You mentioned that you had checked your baud rates but check again because the second terminal window looked as if the baud rate was wrong.

In your terminal window. Go to bottom right hand corner where it says 9600 and change it to match the serial speed set in your arduino code.

Or it could be that you are receiving too much data as per the bottom of this article: https://learn.adafruit.com/adafruit-ultimate-gps-logger-shield/soft-serial-connect
> 1 votes

# Answer
Definitely a baud rate problem. The GPS is sending at 9600.

When you use a sketch to receive the data, the SoftwareSerial .begin should be set to 9600. The Serial.begin should be set to a rate higher than 9600, so that the Arduino cannot fall behind in relaying the data to the PC.

If this does not solve you problem, please post your sketch and a wiring diagram so we can analyze it further.
> 1 votes

---
Tags: arduino-uno, softwareserial, gps, adafruit
---


title: Arduino Pro Mini

text:
# Question
Title: Arduino Pro Mini
I have the following problem

I have a pro mini clone, with 328/5V. It was successfully working in my board. I pulled it out of the board, and wanted to update my software. I connected it to my FTDI, arduino was normal by this time. Power on LED was on. I stared uploading, my sketch compiled and started writing. While it was writing, my 3.5 year old daughter who approached me from behind and whom I did not see pulled the Arduino out of FTDI - "what is that nice red light?" Of course writing failed. Now, when I connect the arduino to FTDI, it is dead. No LEDs light up, no sync... what to do? Any chance to revive it?

# Answer
Check for physical damage! Solder connection of the programming pins to the board was damaged in my case. Resoldering helped!
> 2 votes

---
Tags: programming, uploading, arduino-pro-mini, ftdi
---


# Question
Title: How to write array of functions in arduino library?
I've nine functions each of type void as follow:

```
void zero();
void one();
void two();
void three();
void four();
void five();
void six();
void seven();
void eight();
void nine();

```

I've put all these functions into an array pointer as follow (without any error):

```
typedef void (*num_func) ();
num_func functions[] = { zero, one, two, three, four, five, six, seven, eight, nine};

```

Now I'm writing an arduino library and wanting to achieve the same, but after hours of thinking I'm not able to achieve. Please help me how can I accomplish this in a library?

Thanks in advance.

# Answer
This was a bit fiddly to get right. I got inspiration from How do I create and use an array of pointer-to-member-function?

Based on my post about Function pointers / function callbacks / function variables I modified it to work with class functions:

```
class foo {

  public:

   void doAction0 ()
    {
      Serial.println (0);
    }

    void doAction1 ()
    {
      Serial.println (1);
    }

    void doAction2 ()
    {
      Serial.println (2);
    }

    void doAction3 ()
    {
      Serial.println (3);
    }

    void doAction4 ()
    {
      Serial.println (4);
    }

   // typedef for class function
   typedef void (foo::*GeneralFunction) ();

   // array of function pointers
    GeneralFunction doActionsArray [5] =
    {
      &foo::doAction0,
      &foo::doAction1,
      &foo::doAction2,
      &foo::doAction3,
      &foo::doAction4,
    };

};  // end of class foo

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Starting"));

  // test instance of foo
  foo bar;

  for (int i = 0; i < 5; i++)
    {
    // get member function pointer from array
    foo::GeneralFunction f = bar.foo::doActionsArray [i];
    // call the function
    (bar.*f) ();
    }  // end of for loop

}  // end of setup

void loop () { }

```

This compiles OK and prints:

```
Starting
0
1
2
3
4

```

---

## Amended answer

I was wondering why you needed to specify `bar` in this line above:

```
    foo::GeneralFunction f = bar.foo::doActionsArray [i];

```

The reason is that the code above had the array as non-static, and thus a copy belonged to each instance of the class. This doesn't make a huge amount of sense, so the modified code below makes the array `static` and `const`. That is, the array should be the same for every instance of `foo` and also never change.

Modified code below:

```
class foo {

  public:

   void doAction0 ()
    {
      Serial.println (0);
    }

    void doAction1 ()
    {
      Serial.println (1);
    }

    void doAction2 ()
    {
      Serial.println (2);
    }

    void doAction3 ()
    {
      Serial.println (3);
    }

    void doAction4 ()
    {
      Serial.println (4);
    }

   // typedef for class function
   typedef void (foo::*GeneralFunction) ();

   static const GeneralFunction doActionsArray [5];

};  // end of class foo

 // array of function pointers
const foo::GeneralFunction foo::doActionsArray [5] =
  {
    &foo::doAction0,
    &foo::doAction1,
    &foo::doAction2,
    &foo::doAction3,
    &foo::doAction4,
  };

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Starting"));

  // test instance of foo
  foo bar;

  for (int i = 0; i < 5; i++)
    {
    // get member function pointer from array
    foo::GeneralFunction f = foo::doActionsArray [i];
    // call the function
    (bar.*f) ();
    }

}  // end of setup

void loop () { }

```

This will also save RAM, as the array of function pointers only exists once, not once per instance of the class.
> 2 votes

# Answer
First you need a header file - let's say lib.h:

```
#ifndef LIB_H
#define LIB_H

typedef void (*num_func) ();
extern num_func functions[];

#endif

```

And then the implementation, lib.cpp:

```
#include "lib.h"

void zero();
void one();
void two();
void three();
void four();
void five();
void six();
void seven();
void eight();
void nine();

num_func functions[] = { zero, one, two, three, four, five, six, seven, eight, nine};

```

The functions could be declared as static (if you want to hide them) and they do need implementation. They are only forward declarations above. Below is a snippet of a sketch using the library (assuming that it is within the sketch folder).

```
#include "lib.h"

void setup()
{
  ...
}
void loop()
{
  ...
  // Call to the one() function
  functions[1]();
  ...
}

```

Cheers!
> 1 votes

---
Tags: programming, arduino-mega, c++, c
---


# Question
Title: How to update multiple outputs simultaneously
I need to update simultaneously all the outputs of a specific port.

I am familiar with using micro-processors assembly language. After initializing a port (Data Direction Register), I can write to that port and all outputs will update simultaneously.

In the Arduino commands : I am aware of how to configure pins, such as pinMode(pin, mode), to make a pin an output or input.

I know of the digitalWrite(pin, value) , but this only updates one pin per command.

For timing reasons, I need to update several (same port) outputs without any time delay.

Normally (using assembly language) , I would keep a register with the data I desire on the output port, and write that register's data to the port.

Is there a command I can use in Arduino to accomplish the same thing?
If not a single command, what other choices do I have?

I use Arduino micro, UNO, but I think the question might be valid for most Arduino

# Answer
Yes, the ports of an Uno are addressed in C/C++ as PORTB, PORTC, and PORTD respectively, each 8 bits wide. You can read them or assign to them. Other processors' ports have similar names. Of course the pins' port assignments and functions differ from one to the other, which is one reason for providing the single-pin pinMode() and digitalRead(), digitalWrite() functions. But where you need to deal directly with the hardware (and probably don't care about chip-to-chip portability), the registers are exposed with the above symbols.

Also note that most other CPU registers are exposed the same way - the ports' data-direction registers as DDRA, DDRB, DDRC. You may not care about setting them up simultaneously, but if you wanted to make all of your hardware accesses similarly (and save the flash space for the portable pin functions), you could.

Update:

> Is there a specific command I can use ? Such as Write PortD ?

Yes, you can use the PORTx names like any other C/C++ variable:
`PORTD = 0xFF;`
`PORTD ^= 0x02;`
`if( (PORTD & 0x40) != 0 ){`
, for just a couple of examples - just like real C! :-)

PS: Pighixxx makes absolutely top-notch pinout diagrams for boards & processors. Here is his diagram for the 28-pin DIP-packaged AtMega328p for instance. They're extremely useful when you're working with a chip at the port or board level.
> 4 votes

# Answer
If you need to do more than 8 (especially LOTS more), and timing is very critical, you can use a Serial In, Parallel Out (SIPO) chip, such as the 74HC595 - it also saves a lot of pins on the Arduino.

To use it, you need 3 pins connected to the Arduino. You send one bit to the chip from the Arduino for each output, then when you have them all set, you toggle the Latch pin - all output pins change at the same time. The chip has 8 outputs.

Another advantage of a chip like this is that you can daisy-chain them - with the same 3 pins, you can control as many pins as you like (subject to power availability, of course!).

Read https://www.arduino.cc/en/Tutorial/ShiftOut for more information on how to use them. They are dirt cheap (about US$1.26 each if you buy 10 from AliExpress, shipped to NZ, which is where I am).
> 3 votes

---
Tags: digital, timing, port-mapping, assembly
---


# Question
Title: 2 way communication between Arduino with XBee and Computer
I have an Arduino Uno with a Wireless SD Shield and XBee S1 and a PC with another XBee S1 connected to it. What I'm after is for me to be able to send a message from my computer and receive a message back from the Arduino (For now let's just say if the Arduino receives a "1" I want it to send an "A" back) Here is the code I have been practicing with (courtesy of SparkFun)

```
#include <SoftwareSerial.h>
SoftwareSerial XBee(0, 1); // RX, TX

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

void loop() {
  if (Serial.available()) {
    XBee.write(Serial.read());
  }
  if (XBee.available()) {
    Serial.write(XBee.read());
  }
}

```

(I have changed the pins from 2,3 to 0,1 as the latter is on the Arduino itself) I have set my Xbees up and have been able to get them to talk to each other when both connected to separate PC's, but I am having trouble getting the Arduino to send information to the other XBee. When I try and send data from the Arduino IDE both RX and TX Led's flash. Could anyone steer me in the right direction?

# Answer
> 2 votes
You don't need to declare an extra (software) serial port because the wireless shield connects the Arduino TX and RX on pins 0 and 1 directly to the TX and RX of the Xbee. So, Serial.available, Serial.read and Serial.write directly addresses the xbee. Just leave out the software serial from your code and it should work.

# Answer
> 2 votes
Pin 0 and 1 are the Hardware Serial of Arduino you cannot use it as the software serial and I also used that code once use pin 2 and 3 its issue regarding the configuration of your XBEE? Check your XBEE configuration XCTU

---
Tags: arduino-uno, xbee, softwareserial, ide
---


# Question
Title: Double clap sensor not working as intended
I have this double clap sensor code written, it seems it would work but it seems to trigger the double clap even on a single clap, any ideas?

```
int soundSensor = A1;
int relay = A2;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
int claps = 0;
long detectionSpanInitial = 0;
long detectionSpan = 0;
boolean clapState = false;
int doubleClap = 0;

//Light sensor
int photocellPin = A0;     // the cell and 10K pulldown are connected to a0
int LEDbrightness;

//int delayValue = 100;
int photoSensor = 0;

// sound sample
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;

//other
boolean isRelaysOn = false;
void setup() {
  pinMode(soundSensor, INPUT);
  pinMode(relay, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  turnRelayOff();
  Serial.begin(9600);
}

boolean state = false;
boolean lastState = true;
boolean lightTurnedItOff = false;
void loop() {

  /////////////
  // photo sensor
  ////////////////////

  photoSensor = analogRead(photocellPin) > 623;

  /////////////
  // clap sensor
  /////////////////////
  double sensorState = getSoundLevel();
  Serial.println(sensorState);
  double threshold = .2;

  if (sensorState > threshold)
  {
    if (claps == 0)
    {
      detectionSpanInitial = detectionSpan = millis();
      claps++;
    }
    else if (claps > 0 && millis()-detectionSpan >= 50)
    {
      detectionSpan = millis();
      claps++;
      Serial.println(" CLAP ADDED!!!!");
    }
  }

  if (millis()-detectionSpanInitial >= 400){

    if (claps == 2)
    {
      claps++;
      doubleClap = 1 - doubleClap;
      state = !state;
      Serial.println("TWO claps!");

      if(lastState == state ){
        relayControl(doubleClap);
        lastState = !lastState;
      }
    }
    claps = 0;
  }

  if(isRelaysOn == true && photoSensor == 1){
    turnRelayOff();
    lightTurnedItOff = true;
  }
  if(isRelaysOn == true && photoSensor == 0 && lightTurnedItOff == true){
    turnRelayOn();
    lightTurnedItOff = false;
  }

}

void relayControl(int doubleClap){
  /////////////
  // relay control
  /////////////////////

  if(doubleClap == 1){
    turnRelayOn();
    Serial.println("on");
    isRelaysOn = true;

  }
  else{
    turnRelayOff();
    Serial.println("off");
    isRelaysOn = false;
  };

}

void turnRelayOn(){
  int delayAmount = 100;
  digitalWrite(relay, LOW);
  delay(delayAmount);
  digitalWrite(relay2, LOW);
  delay(delayAmount);
  digitalWrite(relay3, LOW);
  delay(delayAmount);
  digitalWrite(relay4, LOW);
  delay(100);
  digitalWrite(relay4, HIGH);
  delay(100);
  digitalWrite(relay4, LOW);
}

void turnRelayOff(){
  digitalWrite(relay, HIGH);
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);
}

double getSoundLevel(){

  unsigned long startMillis= millis();  // Start of sample window
  unsigned int peakToPeak = 0;   // peak-to-peak level

  unsigned int signalMax = 0;
  unsigned int signalMin = 1024;

  // collect data for 50 mS
  while (millis() - startMillis < sampleWindow)
  {
    sample = analogRead(soundSensor);
    if (sample < 1024)  // toss out spurious readings
    {
      if (sample > signalMax)
      {
        signalMax = sample;  // save just the max levels
      }
      else if (sample < signalMin){
        signalMin = sample;  // save just the min levels
      }
    }
  }
  peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
  double volts = (peakToPeak * 3.3) / 1024;  // convert to volts

  return volts;
}

```

Serial monitor:

> 0.02 0.02 0.02 0.02 0.01 0.01 2.20 0.30 CLAP ADDED!!!! 0.13 0.09 0.04 0.02 0.02 0.01 0.02 TWO claps! on 1.11 0.06 0.05 0.07 0.15 0.10 0.03 0.10 0.06 0.03 0.04 0.06

# Answer
If your first clap rings for more than 50ms, the program counts it as a second clap. After detecting a clap, you need to wait for the sound to die down before you start listening for a second clap.
> 1 votes

# Answer
What you probably want to track is something more like:

* high sound period of highMin to highMax ms
* low sound period of lowMin to lowMax ms
* high sound period of highMin to highMax ms
* low sound period of at least lowDone ms (no max needed)

Anything not meeting those time bounds is not two claps, reset state and timers. If you get to the end of the fourth step, accept as two claps.

I have not tested timing of claps to estimate the periods needed; you need to tweak that with the hardware you are actually using; for example, different microphones may ring for different times after a sharp clap impulse.

States could be:

* waiting for start of first clap (sample until \> threshold)
* waiting for end of first clap (sample until \< threshold or timeout)
* waiting for start of second clap (sample until \> threshold or timeout)
* waiting for end of second clap (sample until \< threshold or timeout)
* got second clap
> 1 votes

# Answer
I have noticed that you have used analogue inputs as your digital outputs by connecting relays to them.

I think this is wrong. You should connect your digital signals to the digital pins.
> 0 votes

---
Tags: relay
---


# Question
Title: What is the best serial protocol for bidirectional communication with NodeMCU?
Except hardware UART. Main requirements are reliability and simplicity of use. Speed isn't as important.

Details:

I have an Arduino Pro Mini (ATmega328P 5V) controlled via UART.
I wish to connect an ESP8266 with stripped-down NodeMCU to offer a web interface for the same functionalities, sending \<=122 character strings to Arduino and possibly getting a short response.
I do not want to use Arduino for processing the interface (too little memory) or use the ESP only (need a stable clock and multiple analog inputs).

My research shows that:

* ESP8266 has obvious timing issues, having been designed for a different purpose.
* Controlling the ESP8266 from Arduino via hardware serial works fine, but I need it the other way around, too. Also, NodeMCU is rather chatty and I don't know how to suppress it, and I'd rather keep the hardware serial ports for programming.
* The same via SoftwareSerial is unreliable
* Personal experience shows OneWire works poorly on ESP8266 (though it may have been fixed)

I have no experience with I2C and SPI beyond polling a slave, and don't know about reliability on ESP8266.
The Arduino already works as an I2C master.
I'm assuming I2C is the way to go, but wanted to ask for opinions first.

**\[EDIT\]** Seems I have once again neglected to set up the proper context. The reason I'm asking is that ESP8266 *can't do very precise timing*, leading to communication problems. Hardware UART to hardware UART is shown to be reliable. For most other protocols, at least one side does bit-banging. I have not done or found extensive reliability tests for those options, and hope instead that the community can offer some insights. Can you?

# Answer
> 3 votes
So you are asking how to use an Arduino Pro Mini as a smart peripheral connected to a NodeMCU master, without making use of the hardware serial port on the latter.

In general, this is either going to operate slowly enough that you can guarantee reception, or you will need to use some kind of flow control or acknowledgement.

One question is whether the APM can always receive at any time, or whether it has to do things which would cause it to not respond for some while and possibly lose data.

Hardware I2c or SPI, with a software flow control protocol using additional pins, are probably your best bets if you cannot use async serial. For example the APM sets OK2SEND high when it's ready to receive (this is an APM output pin connected to a NodeMCU input pin). When NodeMCU detects this high, it writes to I2C and then sets HAVESENT high. When the APM detects & processes incoming data as I2C slave, it sets OK2SEND low. NodeMCU sees OK2SEND low (ack'ing the byte) and sets HAVESENT low. APM detects HAVESENT low which completes the handshake. When APM is ready for another byte, it sets OK2SEND high again. etc. Variants could send more than one byte per handshake, if performance needs that; APM asserting OK2SEND would be contracting to handle that number of bytes.

If you can guarantee that the APM will respond quickly enough to interrupts, you could use an interrupt driven I2C slave system on it, and simplify the above. The APM could be like a dedicated I2C peripheral, albeit a slow one.

# Answer
> 1 votes
While possibly not "the best", I have found I2C to be sufficient for my needs.

Simple to use, if a bit different conceptually (master-slave).

My tests have shown it to be reliable thus far, zero errors over 20 minutes (sending & receiving 20 bytes each time), as long as there were sufficient pauses between calls.

I am going to make the Arduino switch its i2c master/slave role based on the state of other pins. Master most of the time (to use a DS1307 RTC, etc), switching to slave whenever NodeMCU (which can only work as master) has something to say. Thanks to Zeph for the idea.

---
Tags: serial, esp8266, arduino-pro-mini
---


title: Programing uploading to Arduino due

text:
# Question
Title: Programing uploading to Arduino due
I am new to Arduino and bit blur on how it works. lack of info on the net about it. please help me with these questions!

1. Does Arduino due allow you to upload a program on programming port and then run it through Native port?
2. Can I work with SerialUSB instance in Programming port?

# Answer
> Does Arduino due allow you to upload a program on programming port and then run it through Native port?

You don't run a program *through* anything. You run it *on* the Due. Where you send text to is entirely up to you.

> Can I work with SerialUSB instance in Programming port?

I have no idea what you are asking there. Both the Programming port and Native port are capable of being used as virtual USB COM ports. They use CDC/ACM. One is directly connected to the SAM3X chip's USB peripheral, and the other is connected to the SAM3X's UART interface via another microcontroller as a USB to UART converter.
> 1 votes

---
Tags: arduino-due
---


# Question
Title: What Arduino board with WiFi should I choose
I want to implement an Arduino module with some sensors and send the info through WiFi to a server. I'm looking for the best board or component combination to make this. What is the best board or solution you would use in my case? Maybe Arduino Yun or Intel Edison Kit for Arduino...¿?

I've developed a sensor module with Redbear Blend board which use Bluetooth to communicate with an Android app to send sensor data, but now looking for WiFi connection.

Sorry if it's a stupid question, I'm new in this Arduino world. Thanks in advance!

# Answer
I'd recommend ESP8266 (model 07) based board.

* Can be programmed the same way as other Arduinos
* Cheap
* Enough storage for code
* Fairly low power
* Large community (more code examples and better library support)
> 3 votes

---
Tags: shields, wifi, arduino-yun
---


title: Sensor/servo shield for Arduino Mega

text:
# Question
Title: Sensor/servo shield for Arduino Mega
Is there Arduino shields with blocks of 4 pins that you can plug your servos into and use the fourth pin as signal pin to the Arduino Mega board?

# Answer
Do you mean something like a sensor shield? They have three pins (Vcc, GND, signal), not four (because servos have three pins), but they are designed for connecting a large number of servos

These can be found easily and cheaply all over the internet.
> 1 votes

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


title: ESP8266 Firmware Upgrade

text:
# Question
Title: ESP8266 Firmware Upgrade
Can I upgrade my ESP8266 firmware by connecting the pins in Arduino Uno, or do I still need a USB UART to Serial?

# Answer
Looking at the schematic of arduino UNO here you can see that Pin 0 and Pin 1 are connected to the same line of RX TX of the ATMEGA8U2. So in theory (and assuming the ATMEGA8U2 behaves like any usb to uart IC) if you remove or disable the ATMEGA328P, your arduino should behave like any cheap usb to serial. The way you can "disable" ATMEGA328P is by setting it in constant reset mode as explained here

By manually reseting and setting the esp into flashing mode, you should be able to upload the new firmware to it from arduino IDE for example by selecting the ESP device.

**Two notes on this**

**1** \- The TX line of the ATMEGA8U2 is the marked RX on arduino Uno board and RX line of the ATMEGA8U2 is the marked to TX on arduino Uno board. That means your ESP RX should connect to pin 0 on arduino and TX of ESP should connect to pin 1.

**2** \- You might need voltage level conversion on pin 0 as ESP is a 3.3V device although in schematic there is 1K resistor in that line
> 1 votes

---
Tags: esp8266, firmware
---


# Question
Title: GPS Receiver SKG13BL + Arduino - Having trouble receiving data
Here is my setup:

I'm trying to read the GPS data from SKG13BL which is connected to an Arduino Uno.

The GPS seems to be working fine as I could see the green status light blinks after a while (I think it takes time to fix the position).

I connected TTL of SKG13BL to UNO Digital pins 2 & 3 and connected the ground as well.

Here is the image of the connection:

I'm using the TinyGPS test with GPS device sketch to read the data. but I always get something like this,

> \**** \**** \******* \******* \**** \******* \******* \**** \******* \****** \***** *** 0 0.00 *** 30862 0 116
> \**** \**** \******* \******* \**** \******* \******* \**** \******* \****** \***** *** 0 0.00 *** 30885 0 116
> \**** \**** \******* \******* \**** \******* \******* \**** \******* \****** \***** *** 0 0.00 *** 30929 0 117
> \**** \**** \******* \******* \**** \******* \******* \**** \******* \****** \***** *** 0 0.00 *** 30952 0 117
> \**** \**** \******* \******* \**** \******* \******* \**** \******* \****** \***** *** 0 0.00 *** 30985 0 117
> \**** \**** \******* \******* \**** \******* \******* \**** \******* \****** \***** *** 0 0.00 *** 31019 0 117
> \**** \**** \******* \******* \**** \******* \******* \**** \******* \****** \***** *** 0 0.00 *** 31041 0 117
> \**** \**** \******* \******* \**** \******* \******* \**** \******* \****** \***** *** 0 0.00 *** 31086 0 117
> \**** \**** \******* \******* \**** \******* \******* \**** \******* \****** \***** *** 0 0.00 *** 31109 0 117

I tried swapping the pins, using external power source instead of Arduino's 3.3, but there is no change in the result, any advice would greatly help.

**Update 2/26**

I changed the pin here to 10 & 11, and using this code

```
#include <SoftwareSerial.h>
#include <TinyGPS.h>

SoftwareSerial mySerial(10, 11); // RX, TX
TinyGPS gps; // create gps object

long lat,lon; // create variable for latitude and longitude object

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
    //gps.encode(mySerial.read());
    if(gps.encode(mySerial.read()))
      { // encode gps data
      gps.get_position(&lat,&lon); // get latitude and longitude
      // display position
      Serial.print("Position: ");
      Serial.print("lat: ");Serial.print(lat);Serial.print(" ");// print latitude
      Serial.print("lon: ");Serial.println(lon); // print longitude
      }

  }

}

```

But this only displays the below, `lon` and `lat` not coming up in the feed even after waiting for an hour.

> $GPRMC,043721.000,A,1301.6666,N,07740.9169,E,0.13,343.86,260216,,,D\*61 $GPGGA,043722.000,1301.6666,N,07740.9169,E,2,7,1.36,902.9,M,-88.1,M,0000,0000\*72 $GPGSA,A,3,10,31,18,11,193,14,22,,,,,,1.62,1.36,0.88\*37 $GPGSV,4,1,13,41,73,157,43,31,72,187,37,10,47,048,33,14,41,003,28\*71 $GPGSV,4,2,13,18,32,088,16,193,30,107,29,22,27,330,21,21,26,154,\*46 $GPGSV,4,3,13,27,18,238,12,25,15,087,16,26,13,180,,08,11,268,\*7A $GPGSV,4,4,13,11,09,311,20\*43 $GPRMC,043722.000,A,1301.6666,N,07740.9169,E,0.26,343.86,260216,,,D\*64 $GPGGA,043723.000,1301.6665,N,07740.9169,E,2,7,1.36,902.9,M,-88.1,M,0000,0000\*70 $GPGSA,A,3,10,31,18,11,193,14,22,,,,,,1.62,1.36,0.88\*37 $GPGSV,4,1,13,41,73,157,43,31,72,187,37,10,47,048,33,14,41,003,28\*71 $GPGSV,4,2,13,18,32,088,16,193,30,107,29,22,27,330,21,21,26,154,\*46 $GPGSV,4,3,13,27,18,238,12,25,15,087,16,26,13,180,,08,11,268,\*7A $GPGSV,4,4,13,11,09,311,20\*43 $GPRMC,043723.000,A,1301.6665,N,07740.9169,E,0.33,343.86,260216,,,D\*62 $GPGGA,043724.000,1301.6664,N,07740.9170,E,2,7,1.36,902.9,M,-88.1,M,0000,0000\*7E $GPGSA,A,3,10,31,18,11,193,14,22,,,,,,1.62,1.36,0.88\*37 $GPGSV,4,1,13,41,73,157,43,31,72,187,37,10,47,048,33,14,41,003,28\*71 $GPGSV,4,2,13,18,32,088,16,193,30,107,29,22,27,330,21,21,26,154,\*46 $GPGSV,4,3,13,27,18,238,,25,15,087,16,26,13,180,,08,11,268,\*79 $GPGSV,4,4,13,11,09,311,20\*43

**Updated code on 3/1**

This one works perfectly and provides the latitude and longitude.

Thank you @slash-dev and @altinturk

```
#include <SoftwareSerial.h>
#include <TinyGPS.h>

SoftwareSerial mySerial(10, 11); // RX, TX
TinyGPS gps; // create gps object

long lat,lon; // create variable for latitude and longitude object

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {

char c = mySerial.read();
Serial.write( c );
if (gps.encode( c ))
      { // encode gps data
      gps.get_position(&lat,&lon); // get latitude and longitude
      // display position
      Serial.print("Position: ");
      Serial.print("lat: ");Serial.print(lat);Serial.print(" ");// print latitude
      Serial.print("lon: ");Serial.println(lon); // print longitude
      }

  }

}

```

Here is the output

> $GPGSA,A,3,14,20,21,18,29,15,10,,,,,,2.59,1.13,2.33\*0E $GPGSV,4,1,13,29,63,172,35,40,59,241,34,15,45,039,43,18,44,324,51\*7A $GPGSV,4,2,13,21,42,350,46,10,27,284,46,24,27,116,19,14,25,209,17\*76 $GPGSV,4,3,13,20,24,037,46,193,23,064,39,25,10,180,16,26,08,268,\*44 $GPGSV,4,4,13,16,01,294,\*42 $GPRMC,003218.000,A,1301.6703,N,07740.9225,E,0.02,0.00,010316,,,D\*6D
> **Position: lat: 1\******8 lon: 7\*****42**

# Answer
> 1 votes
Seems you are able to receive data properly (according to your the update.) I was using TinyGPS++, an advanced version of TinyGps (http://arduiniana.org/libraries/tinygpsplus/), maybe those can help you: Try

```
Serial.print("LAT=");  Serial.println(gps.location.lat(), 6);
Serial.print("LONG="); Serial.println(gps.location.lng(), 6);

```

GPS cannot get any data indoors. Put your gps close to a window or better -directly outside. First of everything you will get a date&time data on the output, then number of satellites, then the Lat/lon data. But GPS has to receive data indoors. On some chips there is a LED starts blinking once it gets a fix from any satellite. Keep an eye on it.

I realized this small issue when my phone (used for "calibration") couldn't get a fix by its embedded GPS without any cell/network assistance. You should try if you get any signals where you put your device.

# Answer
> 3 votes
You are consuming the received characters with the debug print:

```
Serial.write(mySerial.read());
//gps.encode(mySerial.read());
if(gps.encode(mySerial.read()))

```

Instead, do this:

```
char c = mySerial.read();
Serial.write( c );
if (gps.encode( c ))

```

Also, `SoftwareSerial` is a real CPU-killer. Try NeoSWSerial instead. It's much more efficient and reliable. Sometimes other interrupts, like `Serial.print`, can cause `SoftwareSerial` to be unreliable. Echoing the received characters may be enough to cause characters to be lost. NeoSWSerial is not nearly as susceptible.

And while you're at it, take a look at another library I wrote, NeoGPS. It's the fastest and smallest library out there, especially when you configure it to only parse the fields and messages that you use. For example, if you only need lat/lon, disable all the other fields (time, alt, speed, sats, etc.) and all the other messages (just RMC, no GGA, no GSA, no GSV). Saves lots of RAM and CPU time!

---
Tags: arduino-uno, gps
---


# Question
Title: What should I do to communicate with GSM module?
Sorry, im a beginner, i tried to program an automatic doorlock using sms. But, I dont understand what happen with this error, what should I do? Add library? The error said that Pstring wasnt declared, but i dont know how to declare this.

```
#include <LiquidCrystal.h>
#include "SIM900.h"
#include "sms.h"
#include "SoftwareSerial.h"
#include "sms.h"

SMSGSM sms;
boolean started=false;
char buffer[160];
char smsbuffer[160];
char n[20];
int pintu=5;
int buttonState;
int lastButtonState = LOW;
long lastDebounceTime = 0;
long debounceDelay = 50;
boolean st=false;
int buzzer=6;

void setup()
{
  pinMode(pintu,OUTPUT);
  pinMode(buzzer,OUTPUT);

  digitalWrite(pintu,LOW);
 if (gsm.begin(9600))
 {
  started=true;
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
  }
   if(started)
  {
   delsms();
   sms.SendSMS("08970869443","Pintu SMS Menyala");
  }
  else{digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(buzzer,LOW);
  }

   }

   void loop()
   {

   int pos=0;
  if (gsm.begin(9600))
  {
  if (started){
  pos=sms.IsSMSPresent(SMS_ALL);
  if(pos)
  {
   sms.GetSMS(pos,n,smsbuffer,100);
   delay(2000);
    if(!strcmp(smsbuffer,"bukapintu"))
    {
      PString str(buffer, sizeof(buffer));
    str.begin();
    str.print("Pintu Dibuka");
    digitalWrite(pintu,HIGH);
   // String a=str
    sms.SendSMS(n,buffer);
    }
    if(!strcmp(smsbuffer,"tutuppintu"))
    {
      PString str(buffer, sizeof(buffer));
    str.begin();
    str.print("Kunci Pintu Ditutup");
    digitalWrite(pintu,LOW);
   // String a=str
    sms.SendSMS(n,buffer);
    }
    delsms();
   }
   }
   }
   }

   void delsms()
   {
   for (int i=0; i<10; i++)
  {
     int pos=sms.IsSMSPresent(SMS_ALL);
    if (pos!=0)
   {
    if (sms.DeleteSMS(pos)==1){}else{}
   }
   }
   }

```

Error message :

```
     Arduino: 1.6.7 (Windows 10), Board: "Arduino/Genuino Uno"

      D:\Kuliah\Project\Skripsi\pintu_sms\pintu_sms.ino: In function 'void loop()':

      pintu_sms:67: error: 'PString' was not declared in this scope

       PString str(buffer, sizeof(buffer));

       ^

      pintu_sms:67: error: expected ';' before 'str'

       PString str(buffer, sizeof(buffer));

               ^

     pintu_sms:68: error: 'str' was not declared in this scope

     str.begin();

     ^

    pintu_sms:76: error: 'PString' was not declared in this scope

       PString str(buffer, sizeof(buffer));

       ^

    pintu_sms:76: error: expected ';' before 'str'

       PString str(buffer, sizeof(buffer));

               ^

     pintu_sms:77: error: 'str' was not declared in this scope

     str.begin();

     ^

     exit status 1
  'PString' was not declared in this scope

```

# Answer
> 1 votes
The compiler does not know what PString is. It is not declared in any of the libraries you have included.

You could rewrite to something like this.

```
strcat(buffer, "Pintu Dibuka");
n = strlen(buffer);
digitalWrite(pintu,HIGH);
sms.SendSMS(n,buffer);

```

Please change the other block in the same way.

There are more errors. You also need to change "int n\[20\]" to "int n".

That is a good start.

Cheers!

---
Tags: arduino-uno, arduino-ide, gsm
---


title: Send multiple sensor values over serial

text:
# Question
Title: Send multiple sensor values over serial
I want to send a JSON string over serial from arduiono device to my computer. The JSON string contains a sensor value array. To fill this array I use String.concat("value") function. But If I have more than 100 values I get the JSON string with an empty array and an error message:

```
{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[],"landscape": PUF}
VMDPE_1|3147_VMDPE

```

Is there any other way to send more than 100 values in one message? The arduino device is running with a battery and the communication is wireless. So I want to save energy and reduce the send interval.

**EDIT:**

After reading the answers I updated my sketch:

```
Serial.print("{\"deviceID\":\"ZB_ROUTER_1\",");
    Serial.print("\"sensorID\":\"MMA8451\",");
    Serial.print("\"sensorType\":\"accelerator\",");

    Serial.print("\"aX\":[");
    for (int i = 0; i < samples; i++)
    {
        if(i != 0)
        {
            Serial.print(",");
        }

        Serial.print(xArray[i]);
    }
    Serial.print("],");

    Serial.print("\"aY\":[");
    for (int i = 0; i < samples; i++)
    {
        if(i != 0)
        {
            Serial.print(",");
        }

        Serial.print(yArray[i]);
    }
    Serial.print("],");

    Serial.print("\"aZ\":[");
    for (int i = 0; i < samples; i++)
    {
        if(i != 0)
        {
            Serial.print(",");
        }

        Serial.print(zArray[i]);
    }
    Serial.print("],");

    Serial.print("\"landscape\":\"");
    Serial.print(orientation);
    Serial.println("\"}");

```

In the xArray, yArray and zArray, there are 50 double values stored. One double value needs 4B. So that shouldn't be too much. But there are problems when I receive the JSON string on my computer:

```
{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-1.17,-1.31,-1.26,-1.25,-1.16,-1.09,-1.40,-0.91,-0.94,-0.97,-1.39,-1.06,-0.91,-0.75,-0.78,-0.83,-0.72,-0.62,-0.74,-0.53,-0.82,-0.86,-0.84,-0.79,-0.79,-0.76,-0.83,-0.82,-0.97,-1.07,-0.92,-0.87,-0.97,-1.20,-1.51,-1.53,-1.82,-0.99,-1.04,-0.41,-0.54,-0.27,-0.24,-0.08,-0.02,-0.63,-0.{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[0.16,-0.04,-0.18,-0.03,0.01,-0.17,-0.10,-0.30,-0.31,-0.21,-0.16,-0.16,-0.15,-0.19,-0.17,-0.17,-0.17,-0.18,-0.16,-0.17,-0.17,-0.20,-0.18,-0.16,-0.17,-0.16,-0.15,-0.13,-0.20,-0.19,0.37,-0.88,-0.20,-0.05,-0.12,-0.21,-0.20,-0.17,-0.17,-0.17,-0.17,-0.17,-0.19,-0.17,-0.19,-0.16,-0.18,-0.17,-0.18,-0.17],"aY":[9.80,8.63,8.37,9.05,9.19,8.83,9.01,9.69,8.42,7.94,7.72,7.83,8.43,8.82,9.24,9.21,8.79,8.60,8.39,8.44,8.61,8.77,8.87,8.76,8.66,8.59,8.54,8.73,8.879,8.73,8.66,8.60,8.61,8.68,8.71,8.76,8.71,8.66,8.60,8.63,8.69,8.71],"aZ":[-4.81,-4..28,-4.02,-4.02,-4.29,-4.49,-4.67,-4.63,-4.46,-4.32,-4.28,-4.38,-4.42,-4.52,-4.58,-4-4.52,-4.52,-4.42,-4.39,-4.34,-4.40,-4.47,-4.51,-4.47,-4.44,-4.38],"landscape":" PDB{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-0.18,-0.17,-0.19,-0.20,-0.18,-0.17,-0.18,-0.19,-0.19,-0.20,-0.17,-0.18,-0.17,-0.18,-0.16,-0.18,-0.18,-0.18,-0.17,-0.16,-0.19,-0.18,-0.17,-0.17,-0.16,-0.18,-0.17,-0.18,-0.18,-0.18,-0.16,-0.19,-0.17,-0.16,-0.17,-0.18,-0.17,-0.17,-0.17,-0.16,-0.17,-0.19,-0.18,-0.18,-0.17,-0.18,-0.17,-0.18,-0.17,-0.18],"aY":[8.67,8.68,8.69,8.68,8.68,8.68,8.66,8.68,8.69,8.69,8.69,8.67,8.69,8.70,8.68,8.67,8.68,8.69,8.69,8.68,8.67,8.69,8.69,8.70,8.68,8.66,8.67,8.67,66,8.76,8.80,8.98,8.99,8.76,8.46,8.37,8.55,8.71,8.80,8.85,8.74,8.59,8.58,8.64,8.70,8.44,-4.43,-4.43,-4.44,-4.42,-4.43,-4.43,-4.43,-4.42,-4.44,-4.43,-4.44,-4.43,-4.41,-44.13,-4.20,-4.44,-4.58,-4.68,-4.60,-4.41,-4.31,-4.29,-4.40,-4.50,-4.52,-4.48,-4.41,-{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-0.18,-0.19,-0.22,-0.15,-0.15,-0.19,-0.23,-0.13,-0.16,-0.21,-0.20,-0.17,-0.15,-0.10,-0.16,-0.18,-0.24,-0.17,-0.12,-0.20,-0.28,-0.20,-0.13,-0.19,-0.21,-0.17,-0.18,-0.20,-0.19,-0.17,-0.17,-0.17,-0.17,-0.15,-0.18,-0.16,-0.18,-0.19,-0.18,-0.16,-0.17,-0.18,-0.19,-0.17,-0.19,-0.18,-0.17,-0.16,-0.17,-0.17],"aY":[8.67,8.55,8.61,8.73,8.82,8.73,8.66,8.54,8.54,8.60,8.67,8.60,8.77,8.88,8.79,8.57,8.60,8.51,8.79,8.72,8.83,8.72,8.66,8.68,8.79,8.76,8.67,8.58,75,8.78,8.63,8.63,8.70,8.79,8.77,8.72,8.71,8.67,8.67,8.66,8.70,8.70,8.70,8.69,8.66,87,-4.47,-4.45,-4.32,-4.36,-4.31,-4.41,-4.30,-4.37,-4.46,-4.42,-4.20,-4.39,-4.49,-4.4.40,-4.35,-4.36,-4.39,-4.41,-4.43,-4.40,-4.41,-4.39,-4.40,-4.40,-4.41,-4.42,-4.44,-4{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-0.19,-0.18,-0.18,-0.17,-0.17,-0.18,-0.18,-0.17,-0.19,-0.18,-0.18,-0.17,-0.17,-0.17,-0.18,-0.18,-0.18,-0.18,-0.20,-0.18,-0.16,-0.17,-0.17,-0.18,-0.18,-0.17,-0.18,-0.19,-0.17,-0.19,-0.19,-0.19,-0.17,-0.18,-0.16,-0.18,-0.18,-0.18,-0.19,-0.20,-0.18,-0.17,-0.17,-0.17,-0.18,-0.22,-0.18,-0.17,-0.17,-0.17],"aY":[8.69,8.68,8.69,8.68,8.69,8.68,8.69,8.70,8.69,8.69,8.70,8.68,8.69,8.69,8.70,8.70,8.69,8.67,8.66,8.62,8.73,8.80,8.79,8.75,8.68,8.57,8.60,8.66,8,8.67,8.66,8.69,8.62,8.67,8.76,8.75,8.71,8.71,8.70,8.66,8.67,8.66],"aZ":[-4.43,-4.4-4.41,-4.40,-4.41,-4.42,-4.43,-4.44,-4.47,-4.36,-4.30,-4.30,-4.39,-4.45,-4.51,-4.52,,-4.49,-4.42,-4.35,-4.32,-4.37,-4.38,-4.41,-4.42,-4.46,-4.43],"landscape":" PDB"}

```

Sometimes there is "aZ" missing, sometimes I get wired array values like `8.83.2` (values with two "."). Do I have to many `Serial.print` operations? The sending interval is 500ms.

# Answer
I have had a very similar problem and the Arduino core team has accepted a change from me to facilitate this functionality. It is a complex story so you may have to reread a couple of times.

## 1) Serial.print returns before the data is send over serial.

The first thing to realize is that when you do serial.print() the data is not actually send over serial. When your code looks like

```
serial.print("I'm dead");
resetArduino(); //This method does not exists in the arduino core

```

The message "I'm dead" will not be send over serial. That is because Serial print does not wait until the data has been delivered.

## 2) There is a software buffer used for serial.

The second thing to realize is that when you do serial.print() the data is not actually send but is put into a software buffer. A interrupted routine sends the data from the buffer over the "transport layer" (like in the osi model) here the serial connection. This buffer uses the same memory that your string is using. In other words you are storing the string 2 times. This is why I agree with majenko when he states

> Don't use String. Don't use concat(). Just print each bit as a separate Serial.print() function call.

## 3) If the software buffer is full serial.print will wait

If you do serial.print and the software buffer is full the function will not return until all data is in the buffer. In other words: If a sketch tries to send more data than is transmittable over the serial connection the behaviour of the sketch will change over time.

4) Serial is slow 115200 baut may seem lightning fast but it is slow compared to what your arduino can do. In other words: if you send lots of data you will need to calculate wether the serial connection can handle that amount of data.

## So how can you improve on the situation.

1. As majenko implied: Only use the buffer of serial.
2. Reduce the amount of data you send. Jason is not a good way to send lots of similar data over a serial line because you have to add the variable name each time. I have split my variable names from the data to do reduce the amount of data to send.
3. If you send bursts of data bigger than the software buffer; increase the buffer. This is the change Arduino core team accepted from me.you can set the define SERIAL\_TX\_BUFFER\_SIZE for changing the send buffer size and SERIAL\_RX\_BUFFER\_SIZE for changing the receive buffer size. The default is 64 which means 64 characters.
4. Only send changed data.
5. Preprocess your data so you can send less data
> 3 votes

# Answer
> Is there any other way to send more than 100 values in one message?

Yes. Don't use String. Don't use `concat()`. Just print each bit as a separate `Serial.print()` function call.
> 7 votes

# Answer
Maybe avoid doing the dynamic string manipulations?

```
Serial.print("{\"deviceID\":\"ZB_ROUTER_1\",\"sensorID\":\"MMA8451\",\"sensorType\":\"accelerator\",\"aX\":[");
for(i=0; i <10000; i++){
   if (! i==0) Serial.print(',');
   Serial.print(i);
}
Serial.print("],\"landscape\": PUF} VMDPE_1|3147_VMDPE");

```
> 2 votes

---
Tags: serial, sensors, string, accelerometer, wireless
---


# Question
Title: Arduino Leonardo Pro Mini will not begin sketch when connected to BIOS not an OS
I have an Arduino Leonardo that I am using to emulate a Keyboard using the keyboard.press function with the Keyboard.h libraries. I have gotten the Keyboard.press function to work on my windows and mac- the keystroke I used was CTRL N to test- this worked well. So my ultimate goal was to emulate a keystroke ,F1, on a PC that is not running an OS- meaning I want the sketch to run in BIOS. for context, This keystroke (F1) tells the computer to use the a bootable USB to run a certain MathWorks OS. The problem, when it is plugged in the Arduino shows that power is receieved by lighting the POWER LED but it does not begin the sketch. The RED LED that usually flashes ( TX or RX im not sure) when it is running a sketch is not happening (not illuminating). How can I troubleshoot this and what could be happening? I have read that maybe too much serial info is going to the board so it confuses the board and does not begin the sketch.

I appreciate all the following help!!

# Answer
Because the computer doesn't have a full OS at POST time any USB keyboards attached to the system have to operate in a special "Boot Keyboard" mode.

> Keyboards that implement the USB Boot Keyboard profile specified in the USB Device Class Definition for Human Interface Devices (HID) v1.11 and are explicitly configured to use the boot protocol will interrupt the CPU every time the keyboard is polled even if there is no change in state unless the USB controller overrides this behavior, and are limited to 6-key rollover (6KRO). This profile is intended to allow the BIOS to handle a USB keyboard in the absence of a USB-aware operating system. The recommended profile for keyboards that are not in boot mode in this specification limits keyboards to 6KRO and causes them to respond to an interrupt with a status report at least every half second even if there is no state change in the keyboard unless the USB controller overrides this behavior in order to implement typematic (the function that causes keys to repeat when they are held long enough). However, keyboards in non-boot mode are free to implement an alternative HID profile.
>
> -- Wikipedia

Since it was not expected that anyone would be using the Leonardo to operate in the BIOS that functionality has never been implemented. The choice was to implement the entire system, which would have left less room for your sketch, or to just implement the parts that the majority of people would find useful (that is keyboard, mouse, joystick, etc) and leave out the extra stuff, leaving as much room for sketches as possible.

They chose the latter, since as I am sure you are well aware: "The needs of the many outweigh the needs of the one".

For your rather specific case it may be easiest to butcher an old USB keyboard and work out which pair of inputs to the matrix, when connected together, perform the function you require and design some small interface circuit to allow the Arduino to trigger that function.
> 2 votes

# Answer
Thanks for the Input, you were quite right Majenko. The keyboard.press does not work in BIOS. The problem has been solved by a patch ( I'm not sure if that's the correct terminology) I found on github. By a Nicohood, here is the project if anyone find this having the same issues as me.https://github.com/NicoHood/HID?files=1
> 1 votes

---
Tags: arduino-leonardo, keyboard
---


title: Speed Control L298 motors

text:
# Question
Title: Speed Control L298 motors
Proceeding is the relevant part of the code for the problem I'm asking assistance with. I'm attempting to vary the speed of the robots motors with PWM. The left motor speed can be varied numerical. The right motor fails to move. Any ideas is appreciated. The motor speed code is at the end of the sketch. Any assistance is greatly appreciated.

```
//Below are the symbolic constants. Instead of having to type in a non-sensical pin number each time we want to do something we can write an easy to understand name which represents the pin, the compiler will then replace the names with the numbers
 #define LeftMotorForward 8
 #define LeftMotorBackward 9
 #define LeftMotorSpeed 10
 #define RightMotorForward 6
 #define RightMotorBackward 7
 #define RightMotorSpeed 5
 #define USTrigger 3
 #define USEcho 2
 #define MaxDistance 100
 #define LED 13

//Here we have created two 'objects', one for the servo and one for the ultrasonic sensor
 Servo servo;
 NewPing sonar(USTrigger, USEcho, MaxDistance);

//Below we are creating unsigned integer variables which we will use later on in the code. They are unsigned as they will only have postive values
 unsigned int duration;
 unsigned int distance;
 unsigned int FrontDistance;
 unsigned int LeftDistance;
 unsigned int RightDistance;
 unsigned int Time;
 unsigned int CollisionCounter;

 void setup()                                            //This block happens once on startup
 {
  Serial.begin(9600);                              //I have included the serial initialize but commented it out, if you want to debug and print information to the serial monitor just uncomment

  //Here we are setting the pin modes. As we will sending out signals from the pins we set them as outputs
  pinMode(LeftMotorForward, OUTPUT);
  pinMode(LeftMotorBackward, OUTPUT);
  pinMode(LeftMotorSpeed, OUTPUT);
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorBackward, OUTPUT);
  pinMode(RightMotorSpeed, OUTPUT);
  pinMode(LED, OUTPUT);
  servo.attach(11);                                    //The servo is attached to pin 4
 }

 void loop()                                           //This block repeats itself while the Arduino is turned on
 {
  servo.write(90);                                    //Rotate the servo to face the front
  scan();                                             //Go to the scan function
  FrontDistance = distance;                           //Set the variable FrontDistance to the value of the distance returned from the scan function
  Serial.println("Front distance = ");
  Serial.print(distance);
  if(FrontDistance > 40 || FrontDistance == 0)        //If there is nothing infront of the robot within 40cm or the distance value is 0 (which for the newping libary means no ping was returned) then...
  {
   moveForward();                                     //Go to the moveForward function
  }
  else                                                //Else (if there is something infront of the robot within 40cm) then...
  {
    CollisionCounter = CollisionCounter + 1;
    moveStop();                                       //Go to the moveStop function
    navigate();
  }
 }

 void moveForward()                                    //This function tells the robot to go forward
 {

  Serial.println("");
  Serial.println("Moving forward");
  //Turn on left motor
  digitalWrite (LeftMotorBackward, LOW);
  digitalWrite(LeftMotorForward, HIGH);
  //set speed
  analogWrite(LeftMotorSpeed, 100);

 // turn on right motor
  digitalWrite(RightMotorBackward, LOW);
  digitalWrite(RightMotorForward, HIGH);
// set speed
   analogWrite (RightMotorSpeed, 75);

```

# Answer
> 2 votes
You are not sending a speed command to the motor, you are sending it an analog voltage with the analogWrite. If that voltage is too low, the motor will stall. A higher value should make it spin faster. If you want the speed to be more tightly controlled, you will need encoders on the motors to sense how fast they are spinning, or use stepper motors.

# Answer
> 1 votes
First try commenting out the

```
 Servo servo;

```

line, and all other bits using the servo. If it works then there's your problem - use the Mega possibly as this allows more PWM outputs.

If it doesn't work with the Servo bits removed, then report back and include the Arduino model you're using.

Good luck!

# Answer
> 0 votes
I commented all references to servo, the same results. Comment out the servo code doesn't seem to make a difference. What's going on is when the speed is numerically controlled the motor speed varies. At 50 the right motors slows down and the left motor HALTS, Not sure what's going on.

```
//This function tells the robot to go forward
int value;
for(value = 0 ; value <= 75; value+=5)
    //if value is <=50 left motor does not spin. >75 both motors turn
    Serial.println("");
    Serial.println("Moving forward");
    analogWrite(LeftMotorSpeed, value);//int value has no effect on speed
    analogWrite(RightMotorSpeed, value);// same as LeftMotor)

    digitalWrite(LeftMotorBackward, LOW);
    digitalWrite(LeftMotorForward, HIGH);
    digitalWrite(RightMotorBackward, LOW);
    digitalWrite(RightMotorForward, HIGH);

```

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


title: Arduino PWM Pins Interrupt

text:
# Question
Title: Arduino PWM Pins Interrupt
I am creating pwm from an arduino pin with 50% duty cycle. I just want to know how can i detect its every falling edge using timer interrupt? I don't want to connect that PWM pin to an external interrupt pin. Please help me.

# Answer
> 3 votes
You can define an interrupt service routine (ISR) for each Timer and PWM pin that it handles. These are known as TIMERn\_COMPA\_vect, TIMERn\_COMPB\_vect and TIMERn\_COMPC\_vect. The Mega has six Timers (n=0..5).

```
ISR(TIMERn_COMPA_vect)
{
// Timer/Counter compare match A
}

```

Check the PWM configuration for how the pin is set, cleared or toggled.

Cheers!

# Answer
> 2 votes
Referring to the datasheet of ATMega328P: If you want to generate an interrupt every falling edge you must know if the Pin is inverse mode or not. As you can see from the timing diagram the Pin stays high until the compare unit matches (current value of the TCNCT == value stored in OCRn ) and then goes low in the normal mode or works as opposite in the inverting mode.

This could be regulated by changing the bits COMnx in the TCCRn register. If, for example: COM0 = 1 and COM1 = 1 the table says: Set OC0A on Compare Match, clear OC0A at BOTTOM, (inverting mode).

Now with these settings the falling edge happens when the timer overflow, so the ISR must occur when the timer reach its maximum value.

---
Tags: arduino-mega, pwm, interrupt, timers
---


# Question
Title: How is AVR Assembly in Eclipse or at Linux command line done?
I'm trying to learn AVR development in C and Assembly for the Arduino Uno (Atmel 328p microprocessor) in Linux.

I've found many good guides on how to install and setup the AVR plugin for Eclipse, and I've no problem building and uploading C code. However there doesn't seem to be any menu options for creating an assembler project, nor can I seem to find the correct syntax for using the cli avr-as for assembling my programs into a .hex file.

# Answer
> 1 votes
If you don't mind using make, I'd recommend copying the Makefiles from ChibiOS. For me it works quite well and it's much more aligned to my daily experience with Linux.

# Answer
> 0 votes
The Arduino IDE and the arduino eclipse plugin support assembly.
Taken from the platform.txt

```
"{compiler.path}{compiler.c.cmd}" {compiler.S.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.S.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

```

compiler.S.flags is empty and so is compiler.S.extra\_flags and builds.extra\_flags

leaving us with something like

```
avr-gcc -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {includes} "{source_file}" -o "{object_file}"

```

Which is something I think you can handle.

---
Tags: linux, assembly
---


title: HC-06 Bluetooth Module on Arduino Nano

text:
# Question
Title: HC-06 Bluetooth Module on Arduino Nano
I'm working on a project where I need to have Bluetooth capability on my Arduino Nano to send data from a sensor over to the computer. Unfortunately, I'm having a difficult time figuring out how to establish a connection from the HC-06 to the computer.

I've hooked up the HC-06 to my Arduino in a fashion similar to the picture shown below.

I've also been testing it with various code that I've found online that deal with tutorials on the HC-06. The current code I'm working with is below.

```
#include <SoftwareSerial.h>
SoftwareSerial BT(1, 0);

void setup()
{
  // set digital pin to control as an output
  pinMode(13, OUTPUT);
  // set the data rate for the SoftwareSerial port
  BT.begin(9600);
  // Send test message to other device
  BT.println("Hello from Arduino");
}
char a; // stores incoming character from other device
void loop()
{
  if (BT.available())
  // if text arrived in from BT serial...
  {
    a=(BT.read());
    if (a=='1')
    {
      digitalWrite(13, HIGH);
      BT.println("LED on");
    }
    if (a=='2')
    {
      digitalWrite(13, LOW);
      BT.println("LED off");
    }
    if (a=='?')
    {
      BT.println("Send '1' to turn LED on");
      BT.println("Send '2' to turn LED on");
    }
    // you can add more "if" statements with other characters to add more commands
  }
}

```

When I search for a connection on my computer, it finds the HC-06 and I can then attempt to establish a connection. I enter the pairing code of 1234. It then says that a connection has been established so I go into the Bluetooth Services tab where it tells me what COM port to use (either COM7 or COM4 depending on which computer I try it on. I've tried this on two separate computers.)

So, I open a PuTTY session and attempt to connect to the indicated COM port. About 50% of the time, it says that a connection could not be established to the indicated COM port. The other 50% of the time, I am able to open a PuTTY session but then nothing happens. The green LED on the HC-06 continues to blink away no matter what I try to do.

Any help would be VERY appreciated as I feel like I've tried everything I can think of.

Thank you!

# Answer
> 1 votes
I agree with TisteAndii's comment. Your voltage divider is in the wrong place. You are dividing down the 3.3V signal from the HC-06 to be a maximum of 2.269 volts. However the Nano requires at least 3.5V to be considered HIGH.

Plus, you are putting 5V from the Nano into the HC-06 which may damage it.

# Answer
> 0 votes
Try changing the order of the pins on the Software Serial declaration, the correct order is (Rx,Tx), so SoftwareSerial BT(0, 1); Or, just forget Software Serial altogether and remove the first two lines and change "BT" to "Serial" to use the hardware UART on those same pins which works better.

---
Tags: bluetooth
---


# Question
Title: Trying to verify that Arduino Pro Micro ISP is working
I'm trying to program an Arduino Pro Micro with another Arduino Pro Micro. The purpose is to verify that I can use this Pro Micro board reliably as an ISP to program another Arduino device that does not have a USB interface.

These are actually Pro Micro clones but they seem to work quite well using the Arduino Leonardo profile. I'm following this pinout.

Here is the photo of the setup:

The "red" Pro Micro is set up as ISP using the stock ArduinoISP sketch (didn't think anything needed changing). The "white" Pro Micro is the one I'm trying to program.

The pins are connected, 5V - 5V, GND - GND, MISO - MISO, MOSI - MOSI, SCLK - SCLK, Pin 10 - Pin 10 (reset? this might be wrong).

I've confirmed the ISP sketch is running by the green heartbeat LED. The three LEDs on the red board are connected to pins 7 (top), 8, 9 (bottom), with 9 being the heartbeat.

I loaded the Blink sketch and changed the LED pin to pin 9 since the default pin 14 on the white board is being used as the MISO pin for programming.

In the IDE, I set the board to Arduino Leonardo, port to the red board's port, programmer to "Arduino as ISP" and ran "Upload Using Programmer".

The only output I get is:

```
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

```

Since I'm really just beginning all of this, I'm a bit confused what might be wrong and what could be a next troubleshooting step. Any help appreciated.

# Answer
> 2 votes
As Mikael Patel notes, pin 10 on the programmer Pro Micro should run to RST on the target.

That might or might not fix the problem. In some previous instances of the “Yikes! Invalid device signature” \[,\] bad breadboard connections turned out to be the problem. I suggest you run a second (or even a third) set of jumpers in parallel with the first set. Of course use matching colors to avoid confusion.

---
Tags: isp
---


# Question
Title: esp8266 garbage out only when using SoftwareSerial
I'm trying to operate the esp8266. When I connect RX+TX pins to pins 1+2 on the Arduino, everything works fine. but when I'm trying to use software serial all hell breaks loose and the recieved data is garbadeged (It seems like everything is ok but I can't read the output data... more interesting, the output is not consistent!

example:

```
#include <SoftwareSerial.h>
SoftwareSerial esp8266(11, 10); // RX, TX
void setup() {
    // put your setup code here, to run once:
    esp8266.begin(19200);
    Serial.begin(115200 );
}

void loop() {
    esp8266.write("AT\r\n");
    String buffer;
    Serial.print("SENDING AT...");
    for(uint64_t time = millis();(time+1000) > millis();)
       for(;esp8266.available();buffer+=(char)esp8266.read());
    buffer.replace("\r\n"," ");
    Serial.println("RESPONSE:" + buffer);
}

```

And the output:

I've tried changing the SerialMonitor baud rate, the input pins, but results are all the same.

I've recently changed the MCU(uno) to a different and even a different esp module from a different supplier, I am still getting the same results! I can't be the first one to encounter such phenomena...

# Answer
> 2 votes
Try dropping the SoftwareSerial connection speed to 19200. Ie, esp8266.begin(19200). 115200 it is the absolute max the SoftwareSerial can theoretically handle. Also if you are not using all the change interrupt pins on your MCU (Uno/Nano?) then use any 2 pins from 10, 11, 12 or 13 rather than 3, 2 // RX, TX. Not sure about sendCommand function. If you just want to test the connection then it should be as simple as:

```
SoftwareSerial esp8266(10, 11); // RX, TX

void setup() {
    esp8266.begin(19200);
    Serial.begin(115200 );

    char buffer[50];
    esp8266.write("AT\r\n");
    esp8266.readBytes(buffer, sizeof(buffer));
    Serial.println(buffer);

...
}

```

Obviously once you need to open web pages and recieve responses then you will need a libary to handle IDP+ data. With a bit of coercion I got Adafruit\_ESP8266.h working with SoftwareSerial.

# Answer
> 0 votes
A quick thing to try out.

Try changing `Serial.begin(115200);` to `Serial.begin(9600);` and leave `esp8266.begin(115200);`.

I'm also completely new to Arduino, but I remember seeing the junk values when the serial monitor baud rate is set to a different value than the Arduino's Baud rate.

I was using Arduino Uno and if I set the baud rate to a value other 9600 in the serial window, I was seeing junk values in println function calls.

i.e Set `Serial.Begin(9600);` and the Serial Montior baud rate also `9600`.

# Answer
> 0 votes
From my experience, if you want to have a consistent data transfer over the softserial, you must disable (in Arduino) the global interrupts for the time of transmission. To disable global interrupts use cli() command, to enable it again use sei() command.

---
Tags: c++, wifi, softwareserial, esp8266, terminal
---


title: WiFi repeater using ESP8266

text:
# Question
Title: WiFi repeater using ESP8266
I have a ESP8266 and I wonder if it is possible to create a Wi-Fi signal repeater using this module.

* I can create a network so that devices connect it.
* I can connect to an existing network.

But I can not connect the network created with the network that I connected

Does anyone know how to do this? or you have any examples?

# Answer
> 0 votes
You can't have a single ESP8266 be both an access point and a client, at least not using the exposed API (recall that the Arduino libaries do not implement much functionality themselves, all they do is call the underlying RTOS API).

Also, a signal repeater is not a radio-only device. It would have to understand the low-level 802.11\* protocols and packet types so you don't end up with forwarding loops. You can't do it just by connecting a pair of 8266s back-to-back over SPI and blindly forward packets; there is a lot of networking code that would have to be written.

---
Tags: esp8266
---


# Question
Title: Arduino: Read frequency of input from audio jack
I want to trigger an arduino from a sound from an audio jack from a mobile phone. The audio is a 1 Khz sound that the mobile will play. I want to avoid accidental triggering of the audio by testing for specifically that frequency.

I've found several tutorials using analog read, but the output is not in hertz.

How do i get the output in Hertz?

```
int incomingAudio;

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

void loop(){
  incomingAudio = analogRead(A0);//read voltage at A0
  incomingAudio = (incomingAudio+1)/4 - 1;//scale from 10 bit (0-1023) to 8 bit (0-255)
  if (incomingAudio<0){//deal with negative numbers
    incomingAudio = 0;
  }
  PORTD = incomingAudio;
  Serial.println(PORTD);

}

```

# Answer
> 6 votes
You can measure a single "pure" frequency by counting the number of times that the pin changes, by using the inbuilt timers. Here is a sketch from my page about timers that accomplishes that:

```
// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

ISR (TIMER1_OVF_vect)
  {
  ++overflowCount;               // count number of Counter1 overflows
  }  // end of TIMER1_OVF_vect

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

ISR (TIMER2_COMPA_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");
  } // end of setup

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

```

Feeding in a 1 kHz sine wave (from 0V to 5V) I get this output:

```
Frequency Counter
Frequency: 1000 Hz.
Frequency: 1002 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1002 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.

```

There is the occasional mis-reading but it looks accurate enough. You might sample a few times, and if you get something between 990 and 1010, five times, you might consider that a match.

You will need to make sure that the input is in the range for triggering the input circuitry of the Arduino. It should be around 4 to 5V, and not higher than 5V (for a high). It also should not go negative.

Something like this will protect the input pin:

**Warning** \- audio from an audio jack will be AC and it **will** go negative. Make sure you use a suitable input protection.

---

## Amplification

After looking at Wikipedia - Line level it seems likely that the output from your phone will not be high enough (around 700 mV probably). Therefore a simple transistor amplifier will probably be required to raise it to a level that can be detected.

Inspired by this post on Electronics Stack Exchange, I made up a simple amplifier:

Testing out with around 500mV peak-to-peak input indicates that it successfully amplified it to 0 to 5V DC:

---

## Alternative method with analog comparator

Based on suggestions by Chris Stratton, there is another way of doing this.

You can use the analog comparator to detect an analog signal passing a threshold, like this:

I have set up the voltage divider to trigger at 0.265V, so that a 500 mV signal should provide an acceptable triggering range.

As for the sketch, at these frequencies we can do something simpler than what I posted before:

```
volatile bool counting;
volatile unsigned long count;

ISR (ANALOG_COMP_vect)
  {
  if (counting)
    count++;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

unsigned long startTime;

void loop ()
  {

  if (!counting)
    {
    startTime = micros ();
    count = 0;
    counting = true;
    }
  else
    {
    // is a second up? (1000000 microseconds)
    if (micros () - startTime >= 1000000)
      {
      counting = false;
      Serial.print (count);
      Serial.println (F(" Hz."));
      }  // end of a second being up

    }  // end of if

  }  // end of loop

```

# Answer
> 5 votes
If your signal is a pure 1 kHz tone, then you should use Nick Gammon's counting method, as it is the most straight-forward solution. If, however, you are picking the signal through a microphone, chances are you will also get some background noise, and this can make the counting method unreliable.

In such a case, you will have to use some kind of digital filter to extract the desired signal from the noise. I would recommend using homodyne detection, which is both simple and very robust against wide-spectrum noise: let *f* = 1 kHz be the frequency you want to detect, and *t* be the current time, then

* compute cos(2 π *f t* ) and sin(2 π *f t* ): these two periodic signals, in quadrature to one another, are called “the local oscillator”
* multiply your signal independently by the above cos() and sin()
* low-pass filter the two products, which gives you the I and Q demodulated signals
* compute the instantaneous power = I2 \+ Q2.

You know the phone is ringing when this power goes above some experimentally-determined threshold.

I know all this sounds like heavy math, but it need not be:

* All the computations are amenable to efficient fixed-point implementations, and you can do the math in parallel with the analog-to-digital conversion.
* The scheme works even with crude approximations of the sin() and cos() functions. Even square waves (sin() and cos() being always +1 or −1) work quite decently.
* The low-pass filter can be implemented as an exponential moving average, which is only a bit shift, an add and a subtract.

I can try to write some sample code, but I would go through the trouble only if there is interest. If your signal is so clean that Nick Gammon's method works reliably, there probably is no point.

---

**EDIT**: I wrote a program to demonstrate this approach, just for the fun. It's available as a GitHub gist: homodyne.ino. I am not copying the whole program here, just adding some explanations:

The first thing is to take care of the sampling frequency. Whenever one wants to do signal processing, it is very desirable to sample at a fixed and known frequency. This is next to impossible to achieve by looping over `analogRead()`, because the CPU time needed to go through the loop is hard to predict, as it can be influenced by interrupts and by conditional branches. `analogRead()` is also highly inefficient, as it locks the CPU in a busy loop while it waits for the analog-to-digital converter (ADC) to do its job.

The solution is to put the ADC in the so called "free running mode". In this mode, it starts a conversion as soon as the previous one is finished, which gives a very steady sampling rate of 9.615 kHz (one sample every 104 µs). The samples are handled by an interrupt service routine called `ISR(ADC_vect)` which gets triggered every time a sample is ready. This is also where all the signal processing is done.

Below is a detailed explanation of every line of code in the ISR:

```
int8_t sample = ADCH - 128;

```

Reading the ADC result is the first thing to do in the ISR. Since we do not need the full 10 bit resolution, the ADC was configured to left-adjust its result. Then we get an 8-bit result by just reading the high byte of the ADC data register. We subtract 128 to remove the DC offset and get a signed number in the range \[−128 .. +127\].

Next, we update the phase of our local oscillator:

```
static uint16_t phase;
phase += PHASE_INC;

```

We need not worry about possible overflows: since the phase is kept in units of 1/216 cycles, the increment automatically works modulo one cycle. The phase increment should theoretically be 6815.744, which is rounded to 6816. This makes the local oscillator fast by 0.0376 Hz, which is negligible given the accuracy of the Arduino clock. The phase could be kept in an 8-bit variable, but the rounding error would then make the oscillator fast by 14 Hz, which can be borderline unacceptable.

Next we need to build two square waves in quadrature, which will be used as rough approximations of sin() and cos(). But since the most significant bit of the phase is on during half of the cycle, it can be used as one of our square waves. The other wave is obtained in a similar way, after adding 1/4 cycle to the phase. So here is how we multiply our sample by the square waves:

```
int8_t x = sample;
if (((phase>>8) + 0x00) & 0x80) x = -1 - x;
int8_t y = sample;
if (((phase>>8) + 0x40) & 0x80) y = -1 - y;

```

The expression `phase>>8` is only meant to hint the compiler that it needs only to consider the most significant byte of the phase. This should normally not be needed, but I noticed that, without this hint, gcc generates suboptimal code. The `-1` in the above lines are for avoiding a possible overflow.

Next comes the low-pass filter:

```
signal_I += x - (signal_I >> LOG_TAU);
signal_Q += y - (signal_Q >> LOG_TAU);

```

Where `signal_I` and `signal_Q` are `volatile int16_t` globals, and `LOG_TAU` is 6. This filters with a time constant

> τ = 64 × 104 µs = 6.656 ms

which translates to a −3 dB bandwidth of

> Δf = 1/(2πτ) = 23.9 Hz.

which is fairly narrow for a 1 kHz signal. The significance of τ is that, once the tone starts, it takes the filter about 2.3 τ ≈ 15 ms to reach 90% of its final output. Both τ and Δf can be changed by simply changing `LOG_TAU`.

This ISR takes about 176 CPU cycles (11 µs, including the 4 cycles needed to put the CPU in interrupt mode) every 1664 cycles (104 µs). This amounts to about 10.6% of the available CPU power. And since everything is done inside the ISR, the program is free to do whatever else needs to be done while the data acquisition and digital filtering happens in the background.

I tested the program by sending it a sine wave of 4.36 V peak-to-peak amplitude. The reported power fluctuated quite a bit, but here are the approximate average readings as a function of the input frequency:

```
frequency  |  power
-----------+-------
   929 Hz  |   480
   976 Hz  |  2400
  1005 Hz  |  4600
  1028 Hz  |  2700
  1079 Hz  |   480

```

---
Tags: arduino-uno, analogread, input
---


# Question
Title: Strange behavior on 74HC595 Shift Register IC when its GND pin is used
I was following a tutorial similar to this: https://www.arduino.cc/en/Tutorial/ShiftOut

That is, an array of 8 LEDs that lit up accordingly to the binary representation of a number, which was given in a loop from 0 to 255.

The problem is that when invoked shiftOut() over certain numbers (such as 5, 9 or 13), the LEDs didn't lit as expected.

I even tried replacing the IC, but what finally solved this issue was to disconnect IC's pin 8 (GND) and let only pin 13 (OE) connected to Arduino's ground pin.

**Does anyone know the reason this strange behavior happens on 595 IC?**

Here's a video showing the circuit finally working (without IC's GND pin connected): https://www.youtube.com/watch?v=NGfpk-kjemo

# Answer
Disconnecting the ground pin was not a solution.

It is hard to be certain from video but the resistor values are likely too small because I can't see any color on the bands. They are 100?

Look closely at the driver data sheet. It may say an output pin maximum current is +/-35 mA which would suggest that the 100 ohm resistor is okay.

For example, a red LED has a of around 1.6 V. You are using Vcc=3.3, so a 100 ohm resistor limits the current to \<17 mA ((3.3-1.6)/100). The actual current will be a somewhat smaller as the Vf increases with current..

But you also stay within the maximum Icc and Ignd on the data sheet. These limits are not necessarily 8 x 35 mA. For example an NXP max Icc is 70 mA. That means you cannot drive all the outputs at maximum current, just 2. This is a logic chip, not a driver.

There is other hint that you should not using all the outputs at the max current spec in the section where the Voh and Vol are described. The current at which the voltage is specified is 6 mA, which is the maximum you should use if all output are going to source or sink at the same time.

A common LED current is 5 mA, so this chip could drive 8 simultaneously. If you want high brightness, you need to add a driver such as ULN2003.

Note that the schematic shows red LED's. **The color is important**. Different LED's have different forward voltage. The blue LED have the highest in the range of 3.3 V and higher. So with a Vcc=3.3 there is barely enough voltage to light the blue LED. The red and yellow have much lower forward voltage. When the chip tries to light the red and blue at same time, the output voltage is dropping enough that the blue is not visible, but the red is easily lit.

From the video, it looks that you have the same resistor on all the LED's. On different color LED's this will not achieve the same brightness on all LED's. You need different resistors for each color if you want them the same brightness.

The solution is

* Up the Vcc to 5V so that you can reliably light the blue LED's.
* Increase the resistor values start with 510 for red and 220 for blue. This should be about 6 mA for both.
> 2 votes

---
Tags: shift-register
---


# Question
Title: Is my Arduino board defect? No matter what program I upload the pin 13 turns on and off 3 times and that's it
Just trying to find out if my Arduino UNO R1 board is broken or not.

First of all, everything seems normal, Arduino board shows "on" (green) when I plug it on my computer, I also can verify and upload programs to my Arduino board. But, no matter what program I upload the pin 13 turns on and off 3 times and that's it. I'm checkin it by using a LED. Eg. if I want to use another pin (ex. 7, 8, 12) it doesn't work, or even to write a program for turning on/off 9 times pin 13 doesn't work...

Note: I noticed that pin 8 turns the LED for less than a 1/2 a second.

I already tried to restart board by bridging the reset pin and also by pushing reset directly on the board, I also reinstalled Arduino Genuino Application. I thought to update Atmega8U2 firmware but accordingly to Arduino site I don't need to update since I have firmware rev. 0.01.

It would be also great not to have to buy a new Arduino UNO. Thanks for your help

Edit: Here is how I'm trying to make pin 12 work

```
int ledPin = 12;

void setup()
{
    pinMode(ledPin, OUTPUT);
}

void loop()
{
    digitalWrite(ledPin, HIGH);
    delay(2000);
    digitalWrite(ledPin, LOW);
    delay(2000);
}

```

# Answer
> 1 votes
The best way to check if Arduino is working or not is to install Firmata. Here's the necessary steps:

1) Download Firmata application from the official website.

2) Connect Arduino to the computer

3) Open the Arduino IDE and burn the example Standard Firmata \[File - Examples - Firmata - Standard Firmata\]

4) Open the application, leaving the Arduino connected.

5) Chose the right serial port and debug every pin =D

---
Tags: arduino-uno, pins
---


# Question
Title: Sending data from Arduino to the server where arduino (sketch) acts as a client
I want to make simple client-server program where arduino behave as a client. For example I have a LED connected in arduino board that is controlled by a switch. With the switch I can turn off and on the LED. Now I want to send the status of that LED to another computer wirelessly (let's say within the Local network). That computer will act as a server and update the change as soon as the LED changes its status. I am not expecting any complete code, I just want to know how could it be done in general? May be some links can help me? Because this is my first time working with client-server in arduino sketch, I need some kind of guidelines. Thank you.

# Answer
A simple HC-05 module will give you a wireless bluetooth connection. They're fairly simple to setup, and you can write data to them the same as one would the Arduino serial console. Obviously they can read data too.

```
SoftwareSerial bt_serial(2, 3); // RX | TX
bt_serial.begin(9600);

[...]

if (led_state != last_led_state)
{
    if (led_state == HIGH)
        bt_serial.print("1");
    else
        bt_serial.print("0");
    last_led_state = led_state;
}

```

On the "server" side, a simple program reading the mapped bluetooth serial port would do the job. For example, some python code:

```
import serial
import sys

serial_port = serial.Serial(port='COM8:', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE)

try:
    serial_port.open()
except:
    print("Failed to open port")
    sys.exit(2)

while (True):
    try:
        led_state = serial_port.read()
        if (led_state != 0):
            print("LED is on")
        else:
            print("LED is off")
    except:
        pass

serial_port.close()   # yes, it never gets here

```
> 1 votes

# Answer
Even though I like Kingsley's answer I thought I'd add to this using Wi-Fi becuase you had mentioned LAN.

These two links should be enough to help you: WifiChatServer and C# Telnet Library

Those links can sort of be dissected to fit your needs, but if you need some actual code just tell me.

Now I am aware that **the Arduino is acting as a server and the computer acts as a client**, but I believe this setup is better because it's easier to manipulate connecting to servers on the computer rather than on the arduino side.
> 1 votes

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


title: Debugging with ISP

text:
# Question
Title: Debugging with ISP
I would like to connect the Atmega328p chip to my desktop, through the USB, so I can run teraterm or hyperterminal for debugging purposes. I have already ordered a USB to TTL serial cable but it won't be arriving for about a week. I recently bought a usbASP ISP to program the chip on my Arduino. My question is: can I use the usbASP in place of the TTL cable? or is there some conditioning circuit in the usbASP that won't allow this?

It seems for the usb to ttl, all that is required to interface with the chip is VCC, GRD, RX and TX. So, which pins are the RX and TX?

Hope my question makes sense, they usually don't! thanks in advance!

# Answer
There *is* provision in the USBasp specification for a UART connection, **however**, not all manufacturers copy the original schematic exactly, and no firmware actually contains the appropriate code for CDC/ACM required in order to enable it. And even if they did, technically low-speed CDC/ACM is a violation of the USB protocol and not all operating systems will acknowledge it.

As for your title of "Debugging with ISP", if you have an Atmel programmer and are using Atmel Studio then you *can* perform debugging over ISP (actually debugWIRE, but they use the same connections).
> 2 votes

---
Tags: isp, debugging
---


# Question
Title: Weird stepper motor behaviour on RAMPS in arduino
Following this tutorial:

http://www.instructables.com/id/Complete-newbie-step-by-step-3D-printer-with-all-p/?ALLSTEPS

I connected DVD stepper motor to RAMPS 1.4 on arduino with Marlin software with this settings:

```
 //#define DEFAULT_AXIS_STEPS_PER_UNIT   {80,80,4000,500}  // default steps per unit for Ultimaker

 #define DEFAULT_AXIS_STEPS_PER_UNIT {215.12,215.12,8034.69,196.52}

 // #define DEFAULT_MAX_FEEDRATE          {300, 300, 5, 25}    // (mm/sec)

 #define DEFAULT_MAX_FEEDRATE {100, 100, 2, 25}

 // #define DEFAULT_MAX_ACCELERATION      {3000,3000,100,10000}    // X, Y, Z, E maximum start speed for accelerated moves. E default values are good for Skeinforge 40+, for older versions raise them a lot.

 #define DEFAULT_MAX_ACCELERATION {200,200,50,5000}

 #define DEFAULT_ACCELERATION          100    // X, Y, Z and E acceleration in mm/s^2 for printing moves

 #define DEFAULT_RETRACT_ACCELERATION  100    // E acceleration in mm/s^2 for retracts

 #define DEFAULT_TRAVEL_ACCELERATION   100    // X, Y, Z acceleration in mm/s^2 for travel (non printing) moves

```

I put a video at vid.me (hopefully with sound) showing stepper behaviour when I press +1mm,-1mm,-1mm,-1mm,-1mm,-1mm,-1mm,+1mm,+1mm,+1mm,+1mm on Pronterface software.

# Answer
> 1 votes
The video you show shows movement of far more than 1mm. This indicates that the steps per unit is far different than you are configuring the Marlin software for. With a +/-1mm and 212 steps per mm, there should have been 212 steps sent to your stepper.

Recalculate your steps/mm values and slow down the feed rate to get something reliable.

For experimenting, in Pronterface, set the feedrate of 10mm/sec (600mm/min) or 1mm/sec (60mm/min) to slow things down so you can hear or count the steps with your ear, then choose smaller steps, like +0.1mm and see if you get the planned displacement. If, at a really slow speed, you don't get the corresponding movement, then your steps/mm need adjustment to match your system.

Eyeballing it, I'd say the called-for 1mm or 212 steps is moving the stage about 10mm, so you would need numbers more like this for the x and y axes:

```
#define DEFAULT_AXIS_STEPS_PER_UNIT {21 ,21 ,8034.69,196.52}

```

---
Tags: arduino-mega, motor, stepper
---


# Question
Title: Send stepper to position and back AccelStepper
At the moment I am working on a code that should send a plateau to a certain position and back. The plateau is being moved by the stepper, in my case a Nema 17 with a Polulu DRV8825 driver. Everything is hooked up correctly. My goal is to press '4' on the keyboard and that then the stepper moves to a certain position. However, I am not succeeding in this. I am using AccelStepper and at the moment I have the following code:

```
#include <AccelStepper.h>

AccelStepper stepper(1, 5, 4);

int spd = 1000;    // The current speed in steps/second
int sign = 1;      // Either 1, 0 or -1
int buttonState = 0;

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(1000);
  stepper.setSpeed(1000);
}

void loop()
{
  char c;
  if (Serial.available()) {
    c = Serial.read();
    if (c == 'f') {  // forward
      sign = 1;
    }
    if (c == 'r') {  // reverse
      sign = -1;
    }
    if (c == 's') {  // stop
      sign = 0;
    }
    if (c == '1') {  // super slow
      spd = 100;
    }
    if (c == '2') {  // medium
      spd = 900;
    }
    if (c == '3') {  // fast
      spd = 1000;
    }
    if (c == '4') {
      //not working, does anyone know how to do this?
      stepper.moveTo(500);
    }
    stepper.setSpeed(sign * spd);
  }
  stepper.runSpeed();
}

```

Does anyone have tips or know how to achieve this?

Thanks is advance!

# Answer
Gerben's comment:

> You need to call stepper.run() instead of runSpeed, for moveTo to work.

provides the answer. The updated code is:

```
#include <AccelStepper.h>

AccelStepper stepper(1, 5, 4);

int spd = 1000;    // The current speed in steps/second
int sign = 1;      // Either 1, 0 or -1

int buttonState = 0;

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(1000);
  stepper.setSpeed(1000);
}

void loop()
{
  char c;
  if (Serial.available()) {
    c = Serial.read();
    if (c == 'f') {  // forward
      sign = 1;
    }
    if (c == 'r') {  // reverse
      sign = -1;
    }
    if (c == 's') {  // stop
      sign = 0;
    }
    if (c == '1') {  // super slow
      spd = 100;
    }
    if (c == '2') {  // medium
      spd = 900;
    }
    if (c == '3') {  // fast
      spd = 1000;
    }
    if (c == '4') {
      //not working, does anyone know how to do this?
      stepper.moveTo(500);
    }
    stepper.setSpeed(sign * spd);
  }
  stepper.run(); //You need to call stepper.run() instead of runSpeed, for moveTo to work. – Gerben
}

```
> 1 votes

---
Tags: arduino-uno, stepper
---


# Question
Title: Is this a USBasp I can use with Arduino?
I bought the following USBasp off of Aliexpress.

The Arduino UDE doesn't recognize it. When I try to run avrdude with it, it says:

```
avrdude -cusbasp -Pusb -patmega328p
avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'

```

Looking at the USB enumeration, it says:

USBHID:

```
  Product ID:   0xc8b4
  Vendor ID:    0x03eb  (Atmel Corporation)
  Version:  1.00
  Speed:    Up to 1.5 Mb/sec
  Manufacturer: zhifengsoft
  Location ID:  0x14200000 / 8
  Current Available (mA):   1000
  Current Required (mA):    100
  Extra Operating Current (mA): 0

```

Looking online, I see one blog post (http://www.sciencetronics.com/greenphotons/?p=938) about a device with the same VID/PID, and it says it can be reprogrammed but is not clear how to do it.

In particular, I know there is a jumper that I need to set to put it in self-programming mode but I can't figure out where to put this jumper. Once the jumper is in, I understand I just match the SPI pins and program it using the firmware.

Can someone help?

# Answer
That's not a USBasp, that's some other programmer that has co-opted Atmel's vendor ID invalidly. If you want to use it then you will need to find and use some program called "ProgISP" that is only available for Windows.

That particular device does not show the jumper required for reprogramming, so I wouldn't attempt it (and in fact I would find the nearest bin to toss it in and get a couple from Baite and/or LC Tech instead).
> 3 votes

---
Tags: isp
---