title: Timer3 Arduino maximum period

text:
# Question
Title: Timer3 Arduino maximum period
At the moment I'm trying to learn microcontrollers with Arduino, and have a problem with the timer.

Arduino works at 16MHz clock, and the best prescaler is 1024, which means the timer increments the value every 64 us. Timer 3 is a 16 bit timer, which gives us a maximum time of 64\*65535= 4194240, ca. 4s

But what if I want to do a job every 8 seconds? Any idea?

Here's my code:

```
TCCR3A = 0;
TCCR3B = 0;
TCCR3B |= (1<<WGM32); //CTC
TCCR3B |= (1 << CS32);
TCCR3B |= (1 << CS30);// 1024 prescaler
TIMSK3 |= (1<<OCIE3A);
sei();

```

# Answer
> 2 votes
You can't - not directly. Instead you do a job at a higher frequency which just counts. When it has counted enough you do your other job.

For instance, you might trigger your interrupt once a second. That interrupt just adds 1 to a count and returns. Unless that count just hit 8, when you reset the count to 0 and run your 8 second routine.

# Answer
> 0 votes
You know that the inbuilt function `millis()` would let you achieve that goal?

For example:

```
unsigned long startTime;

void loop ()
  {
  if (millis () - startTime >= 8000)
    {
    startTime = millis ();  // reset start time to now
    // do something that needs doing every 8 seconds
    }

  // do other stuff

  }  // end of loop

```

# Answer
> 0 votes
If the 5% error (~4.2 sec vs. 4.0 sec) isn't a problem, 2 counter overflows will give 8 seconds with the same 5% error, or ~8.4 sec. If you need higher accuracy, either start the timer with a slightly smaller initial counter value, (62500 * 64 = 4000000 uSec), choose a divider value that naturally overflow at convenient sub-multiples of the intervals your program will need, and again count N overlows of the timer before your code responds.

---
Tags: timers
---


# Question
Title: Why does static member std::map reset ESP8266 when outside the .ino file?
Here's an example of a class which crashes the ESP8266-03 causing it to reset:

Test.hpp file:

```
#include <map>

class Test {
public:
    int data() const;

    Test(int x);
    ~Test();
protected:
    int _data;

    static std::map<int, Test const *>thing;

    static void _Reserve(Test const * const t);
};

```

Test.cpp file:

```
std::map<int, Test const *> Test::thing;

int Test::data() const
{
    return this->_data;
}

void Test::_Reserve(Test const * const t) {
    Test::thing[t->data()] = t; // Works fine if this line is removed.
}

Test::Test(int x): _data(x)
{
    Test::_Reserve(this);
}

Test::~Test() {};

```

Project.ino:

```
#include "ESP8266WiFi.h"
#include "Test.hpp"

Test test(2);

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

void loop() {
    Serial.print("Timer: ");
    Serial.println(millis());
    delay(1000);
}

```

The following **does NOT** crash the ESP8266-03 and prints the time as it should:

```
#include "ESP8266WiFi.h"
#include <map>

class Test {
public:
    int data() const
    {
        return this->_data;
    }

    Test(int x): _data(x)
    {
        Test::_Reserve(this);
    }
    ~Test() {};
protected:
    int _data;

    static std::map<int, Test const *>thing;

    static bool _Reserve(Test const * const t) {
        Test::thing[t->data()] = t;
    }
};

std::map<int, Test const *> Test::thing;

Test test(2);

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

void loop() {
    Serial.print("Timer: ");
    Serial.println(millis());
    delay(1000);
}

```

When the first version is uploaded to the board, I get the following in the serial monitor:

```
 ets Jan  8 2013,rst cause:1, boot mode:(1,7)

 ets Jan  8 2013,rst cause:4, boot mode:(1,7)

wdt reset

```

When I reset it and boot it regularly, no upload mode, the following repeats every ~1 second:

```
 ets Jan  8 2013,rst cause:1, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld

```

# Answer
> Why does static member std::map reset ESP8266 when outside the .ino file?

What happens if the Test() constructor is run before the map constructor? This is the problem: you are assuming order of execution.

Use a Singleton pattern or init() member function to force the ordering that is required.

Cheers!
> 0 votes

---
Tags: c++, arduino-ide, esp8266, class, debugging
---


title: MPU6050 safe to use with glue?

text:
# Question
Title: MPU6050 safe to use with glue?
My current project involves embedding an MPU6050 accelerometer into straps, one of which goes below the knee, the other above the knee.

I need to fit the sensor into the strap and currently i have 6-core multi-threaded wire soldered directly into the board. This doesn't facilitate the greatest of long term stability, as too much strain and the wires will just pull out and break.

What I am wondering is if it is OK to:

1. cover the wire side of the board in glue from a hot glue gun? Would this have any possible conductivity issues or risk damaging the wires or board itself?
2. If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance. This would leave me with a really solid sensor for embedding if so!

Any answers to the above questions would be greatly appreciated and I would be extremely grateful for any alternative options as well. I would like to keep the wires soldered into the board as it is extremely tidy and makes for easier embedding than if I were to use another connector.

# Answer
> 0 votes
1) I do not see any problem here - I myself used hot glue to fix and isolate power source of robot from the copper side. It does not leak any (measurable by my tools) current, does not show any sign of detorations and works well both electrical and mechanical way. I used it only on copper side, where was risk of shortcuts and where were no heat dissipators (as it isolate also heat). But I think, that the MPU does not generate so much heat, to be worry about - body proximity and weather on summer would affect it more.

2) Hot glue is not as hot as soldering lead/tin so short contact with the MCU should not harm it. (You can shortly touch hot glue to manipulate it and not get burned, so it is not so hot). Anyway I would apply it as fast as possible and would leave it cool down before swithing it on (the working and the storing temperatures are different case). Be carefull with the wires, as the isolator can be melted, if heated by hot glue and moved at the same time. Also take in mind, that the hot glue should be little around the whole, to isolate from humidity. And that it would be complicated to solder anything after the glue is applied - so have all contacts (you may possibly need access) somehow lead out of the glue. And try the construction before applying the glue, to be extra sure, that nothing is missing and everything works.

I personally would place the MCU on some kind of PCB and solder the wires to the PCB organized the way the wires would continue to form "cable" and to have extra sure there is no force on the connection of MCU pins. Also I would fixed the whole cable to the PCB with something, so the solder itself is not under any force, as it is the most probabely place to broke there. An I would ensure, that the cable goes smoothly away from the PBC, as it would be bad, if it would be bent ower sharp edge at the place where it leave its glue support.

# Answer
> 1 votes
> Would this have any possible conductivity issues

Nope.

> or risk damaging the wires or board itself?

Nope.

> If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance.

Sure.

This is known as "potting". You can get special potting compounds, but hot glue is just as good.

---
Tags: arduino-uno, mpu6050, project
---


# Question
Title: Use Raspberry and Arduino IDE to programm ESP8266
I currently use Arduino IDE to generate binaries for ESP8266. Afterwards I copy the binaries with SFTP to my Raspberry Pi and flash the binaries using esptool.py.

These are lots of steps I need to do manually. Is it possible to automate this and use the Raspberry Pi as a programmer known to the Arduino IDE?

The goal is, that the "Upload" button in Arduino IDE does the full job.

# Answer
I was able to find a solution based on this post: http://www.linuxquestions.org/questions/linux-networking-3/serial-over-lan-from-linux-to-windows-825334/#post4062960

Following steps are necessary.

* Install `com0com` and `com2tcp` on the Windows machine and `socat` on the Raspberry.
* Then add a virtual COM-pair (`COM0 <-> COM25`) on the Windows machine with the help of `com0com`.
* Execute following command on the Raspberry. `socat file:/dev/ttyAMA0,raw,echo=0,b115200 tcp-l:3016,fork&` (adjust the device `/dev/ttyAMA0`, baudrate `b115200` and port `3016` according your needs)
* Start `com2tcp` on the Windows PC with following command. `com2tcp --baud 115200 --ignore-dsr \\.\COM25 192.168.0.1 3016`
* Now you can use `COM0` in Arduino IDE to flash the ESP8266 attached to `/dev/ttyAMA0` on the Raspberry
> 0 votes

# Answer
Have you tried installing Python for Windows?

http://docs.python-guide.org/en/latest/starting/install/win/

In theory it should work and you should be able to run esptool.py on a Windows command line like you do on your Pi (provided that your usb to serial in recongnized by Windows).

If esptool.py fails to run under Python for Windows I would first suggest to open a ticket with the esptool maintainer and then try under a cygwin environement (https://www.cygwin.com).
> 0 votes

---
Tags: arduino-ide, esp8266, uploading, raspberrypi
---


# Question
Title: Adapt Dynamixel library to different shields
I have been playing around with this shield for a couple of days now and I have to agree with some statements made in the comments that the "library" lacks many functions.

However I have discovered the following library which was built for the Dynamixel shield: https://github.com/zcshiner/Dynamixel\_Serial

I wanted to know since I am using an Arduino Uno, which parameters I would have to change to make it work.

Sorry I am not very fluent in C++. I have tried just changing the direction pin to 10 but it's obviously not sufficient.

Shield to be dealt with: https://dfrobot.com/index.php?route=product/product&product\_id=958

The following code should work afterwards:

```
#include <dynamixel_serial.h> // Library needed to control Dynamixel servo

#define SERVO_ID 0x01 // ID which we will set Dynamixel to
#define SERVO_ControlPin 0x0A // Control pin of buffer chip, NOTE: this does not matter because we are not using a half to full control buffer.
#define SERVO_SET_Baudrate 57600 // Baud rate speed which the Dynamixel will be set to (57600)
#define CW_LIMIT_ANGLE 0x001 // lowest clockwise angle is 1, as when set to 0 it sets servo to wheel mode
#define CCW_LIMIT_ANGLE 0xFFF // Highest anti-clockwise angle is 0XFFF, as when set to 0 it sets servo to wheel mode

void setup() {
  delay(1000); // Give time for Dynamixel to start on power-up
  Dynamixel.begin(SERVO_SET_Baudrate); // We now need to set Arduino to the new baud rate speed
  Dynamixel.setDirectionPin(SERVO_ControlPin); // Optional. Set direction control pin
  Dynamixel.setMode(SERVO_ID, SERVO, CW_LIMIT_ANGLE, CCW_LIMIT_ANGLE); // set mode to SERVO and set angle limits
  Serial.begin(115200);
  Serial.println("Setup Done!");
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  Dynamixel.servo(SERVO_ID,0x001,0x100); // Move servo to angle 1(0.088 degree) at speed 100
  delay(4000);
  Dynamixel.servo(SERVO_ID,0xFFF,0x3FF); // Move servo to max angle at max speed (1023)
  delay(4000);
}

```

# Answer
> 1 votes
You are setting the baudrate to 57.6K however, you need to communicate with the Dynamixel at the baudrate it is set to. I believe the Dynamixel comes with a preset baudrate of 1Mbs. The first thing thing I would do is to change your 57.6K to 1Mbs and try that. This is assuming the ID is actually 1 (also a default)

Here are two links for info on Arduino baud rates and Dynamixel serial communications.

Controlling AX-12 Servos

How high of a baud rate can I go (without errors)?

---
Tags: shields, servo
---


# Question
Title: Reading updated serial data from ESP8266
I have connected my ESP8266 to my Arduino Uno on pin 2 & pin 3 as RX & TX. I adjusted the baud rates and I have no issue receiving the data from the ESP8266.

The ESP8266 gets connected as a client to a server and grabs the likes count of a Facebook page. The data on the ESP8266 serial port is updated correctly every time the ESP sends a get request to the server to get the updated likes count of a particular Facebook page.

Unfortunately I'm not receiving this updated likes count on my Arduino serial port. I'm always receiving the same likes count. I have to close the serial window and open it again to receive the new count. Or reset the Arduino itself to receive the new likes count.

So why isn't it posting the latest likes count sent from the ESP to the Arduino instantly without having to reset the Arduino? Maybe I have an issue in the `void loop()`.

Because I display this data on an external display and I need it to be updated without me needing to reset the Arduino every time to receive the latest count.

```
void loop() {
  char c;
  while (esp8266.available() && c != '\n') {
    c = esp8266.read();
    response += c;
  }
  //If end of line
  if (c == '\n') {
    //Getting the likes string only
    if(likes = response.substring(response.indexOf("Likes:")+6, response.indexOf("::"))) {
      //Filtering some unneeded strings
      if((strstr(likes.c_str(), "URL")) == NULL) {
        currentLikes = atol(likes.c_str());
        Serial.print(currentLikes);
        //Printing likes count on serial port
      }
      Serial.println();
    }
  }
}

```

# Answer
> 1 votes
Thank you everyone I had to just clear the response string every time.

I have just added `response = "";` after the `Serial.print(currentLikes);`

---
Tags: arduino-uno, esp8266, softwareserial
---


# Question
Title: Touch-screen, 3 H-bridges and 3 sensors on Arduino Nano 3.0
I am using an Arduino Nanao andI am wondering if there is a way to connect an 2 inch touchscreen, 3 H-bridges (it takes 3digital pins to power one of them and 1 additional to control the voltage) and have 3 analog pins left for sensors?

# Answer
> 0 votes
I think, that there is at least one I2C touchscreen (eg. https://www.adafruit.com/product/1947 )(I2C need 2 pins - SCL(A5)+DATA(A4) - given by HW) and if you need 3x3=9 digital pins for setting direction, you can use also I2C multiplexer on the same 2 pins (http://playground.arduino.cc/Code/I2CPortExpander8574). So you are left with need for 3 PWM pins from (D3,D5,D6,D9,D10,D11).

So there is a way for sure.

---
Tags: arduino-nano, h-bridge
---


title: Arduino Leonardo clone voltage question

text:
# Question
Title: Arduino Leonardo clone voltage question
I'm planning my first Arduino project which involves a MPU-6050 accelerometer(3.3V) and a RGB led(5V). I've found this Arduino Clone but i'm not sure if it has 3.3V and 5V outputs that I can use. The pins do exist on the original Leonardo board but i'm not sure if the clone contains them as well.

# Answer
That has a 5V pin (Vcc) but no 3.3V. Also the 5V pin can't provide more than a few hundred mA.

Better specifications are here: https://www.sparkfun.com/products/12640
> 0 votes

---
Tags: arduino-leonardo
---


# Question
Title: Reading serial buffer taking newline character instead of user input
I am trying to compare whether the user input matches a user ID or not. When I read the input from serial, the program is taking the last character which is newline char '\n' and moving it into the char data value to compare against the stored user ID and I don't understand why it's taking the '\n' value instead of the actual user input.

```
int Gled = 7;
int Rled = 8;
int wait = 5000;
char UserID = "12345";
char data;
char incoming;

void setup() {
  Serial.begin(9600);
  pinMode(Gled,OUTPUT);
  pinMode(Rled,OUTPUT);
  Serial.println("Please Enter your username or ID:");
}

void loop() {
  if(Serial.available()>0) {
    while(1) {
      data=Serial.read(); //read user input and move to data char
      if(data !='\n')
        incoming = data; //if data doesn't equal newline data = incoming
      if (data == '\n')
        break; // newline char detected break
      if (data == -1) //continue reading all of user input
        continue;
      Serial.print(data);
      Serial.print(incoming);
    }
    Serial.println(incoming);
    if(incoming == UserID) { //if user input matches run statement
      digitalWrite(Gled, HIGH);
      Serial.println();
      Serial.println("Access Granted");
      Serial.println("Hello User Name");
      delay(wait);
      Serial.println("Login time exceeded, you are now logged out.");
      Serial.println("Reenter your UserID to log back in.");
      digitalWrite(Gled, LOW);
      Serial.end();
      Serial.begin(9600);
    } else if(incoming != UserID){
      //user input doesn't match run statement
      digitalWrite(Rled, HIGH);
      Serial.println();
      Serial.println("Access Denied");
      Serial.end();
      delay(wait);
      Serial.begin(9600);
      digitalWrite(Rled, LOW);
      Serial.println("Please Enter a Valid ID to Continue.");
    }
  }
}

```

# Answer
> 1 votes
```
if(data !='n')

```

This should be

```
if(data !='\n')

```

**NEXT**.

```
data=Serial.read();

```

only reads ONE character. You should add to a buffer, not assign a single character.

---
Tags: serial, input
---


title: Digital Band pass filter on Arduino

text:
# Question
Title: Digital Band pass filter on Arduino
I am working with sensors on Arduino and would like to filter the sensor's output to a certain band of frequencies.

I found many examples online on how to implement simple digital low-pass filters in Arduino code, but not for band pass filters.

Is it even possible to achieve this in the scope of an Arduino program? If anyone can share some tutorial for this, that would be much appreciated.

# Answer
A band pass filter simply means that it a filter between a certain interval of frequencies thus it can be made from a high pass filter and a low pass filter

e.g. this fact is mentioned here http://www.electronics-tutorials.ws/filter/filter\_4.html

as well as lots of other web pages which a search by you can find. So yes a band pass filter can be implemented on arduino if you can implement the corresponding high pass and low pass filter too.
> 1 votes

---
Tags: signal-processing
---


# Question
Title: How do I use Sound Sensor LM393 + Speaker in Arduino
I have this voice sensor:

I need to know how bytes pass through soundsensor into arduino and get this bytes and put out in a speaker.

I read on the net a Lib PCM thats converts chars in voices, but how do I extract bytes from sound sensor in analog-in?

# Answer
> 2 votes
Oh, the joys of buying something off the Internet with no datasheet, no part number and no clue how to use it. And then expecting somebody else to tell you how it works.

That module looks like a KY-038, made by Keyes. No guarantees, though, because I'm not telepathic.

Bytes don't "pass through the soundsensor". Bytes don't pass anywhere, in fact. That board has an analogue output, `A0`, which is the amplified audio sensed by the microphone. It swings between 0 and 5 volts, and is 2.5V when no sound is being picked up. The board also has a digital output, `D0`, which is **active-low** when the intensity of the sound picked up by the microphone exceeds a thershold. I have no idea what this threshold is or what volume it represents, or if it can be changed.

Have a look at the pages on AnalogRead() for information on how to convert analogue audio to a digital signal.

I don't know what you mean by "a Lib PCM thats converts chars in voices" - 'chars' as in the C-type `chars` or do you mean literal 'characters from a voice', i.e. speech recognition? I cannot tell if you have misunderstood something or there's an unfortunate translation coincidence which is confusing matters.

# Answer
> 4 votes
This post was awhile ago, but I wanted to offer some more definitive info for others like myself who were trying to identify it. What you have there is the Keyes KY-037 "high-sensitivity voice sensor" module. Mine came with the Inland Arduino Uno RFID Learning Kit.

Apparently the KY-037 and the KY-038 are the same except the KY-037 has a higher sensitivity microphone. I could not find any specs to quantify what that sensitivity difference is, however. Both have a LM393 voltage comparator on the board. The same Arduino code ought to work for both.

Here are a few helpful links I found, some also showing a bunch of the other Keyes modules and how to use them:

http://linksprite.com/wiki/index.php5?title=Advanced\_Sensors\_Kit\_for\_Arduino

http://brd4.braude.ac.il/~ksamuel/ElIn.31361/Lectures/022-Basic%20Definitions%20and%20Concepts%20Sensors%20and%20Actiators%202013-10-10.pdf (Page/slide 40)

http://tkkrlab.nl/wiki/Arduino\_37\_sensors

---
Tags: arduino-uno, sensors, sound, tmrpcm
---


title: Loading local libraries

text:
# Question
Title: Loading local libraries
I'm new to Arduino/C development (coming from a JavaScript/Ruby environment), but I was wondering if it was possible to include a library from a custom folder within a sketch?

So this is my situation;

```
project.ino
libs/
  MyNewLib/
    MyNewLib.h
    MyNewLib.ccp

```

Now my question is: how can I include my custom library? I've tried several variations on this;

```
# project.ino

#include <libs/MyNewLib/MyNewLib.h>
#include "libs/MyNewLib/MyNewLib.h"
#include <./libs/MyNewLib/MyNewLib.h>
#include "./libs/MyNewLib/MyNewLib.h"

```

But none of them works. Can anyone tell me if this is possible? I've looked into this question around the web, but I can't find any satisfying answer. Hopefully you guys can help.

Cheers.

**UPDATE**

I'm aware you can put your libraries in your global libraries folder, but I want them in my local project folder. I want to share them through git with my team.

# Answer
> 8 votes
Okay, here is how it works, and I checked it to make sure.

Sure you can use hard paths, but every programmer *hates* using hard paths. They are not portable at all, and they lock your program in place. You use soft or hard links to the files in the project (look up the man pages on "ln"). But,... talk about ugly! So the question is how to do it "correctly"? The key is learning with what parameters and in what path the C/C++ compiler runs.

You will find the conclusion is NOT intuitive at all. Cutting to the chase: *relative paths **don't** work correctly.* Now, why?

But first, let me explain why anyone would want to place program files *outside* the project directory. Programmers like writing program classes, structs, methods, functions, macros, etc., once. As soon as the programmer solidifies the program fragment, he/she wants to put the files in a common tree and move on. Every program thereafter could use that private library. Also, by having the files in a central place, you won't have multiple copies and versions of each. One private library for many private programs.

As of 1.6.13 (Teensy does not yet support 1.8.\*), relative includes start from the *library*, not your directory. It appears that the ano-to-C filter (remember that Arduino does a "conversion" to the target then calls the C/C++ compiler) starts where you installed your Arduino tree. In my case, I installed in "~/bin/arduino". Teensy's home is "./hardware/teensy". The entire home path for the libraries is "~/bin/arduino/hardware/teensy/avr/libraries" where you will find all the support program trees.

In a source file, the '#include "test.hpp"' statement correctly picks the file from your current directory. HOWEVER, if you use '#include "../test.hpp",' the include path does *not* start in your project directory. Instead it starts in "./libraries"! So the resulting path is:

`#include "../test.hpp" ==> ./arduino/hardware/teensy/avr/libraries/test.hpp`

In conclusion there is no clean way of making your own tree of tools in a nearby directory. The only course is to commit your work in the Arduino library and be aware of those rules as well.

# Answer
> 5 votes
I recently tested this local library structure. It works with:

```
#include "libs/MyNewLib/MyNewLib.h"

```

The Arduino IDE 1.6.7 build pre-processing will even pick up the source code for the library.

Cheers!

# Answer
> 3 votes
The Arduino plugin for Visual Studio supports local libraries you can find the plugin here

# Answer
> 2 votes
I am just back to using the arduino after some time away and am somewhat bewildered by similar issues and confused by different info from different sites and for different versions of the ide.

What I have found is that if you have a sketch in a directory, then shut down the Ide you can drop .h, .cpp... files in the directory and the ide, when restarted, will open them with the sketch.

Include them by using simple quotes on the file names, no path, no angle brackets.

I am sure this is only part of the full answer, but it has gotten me started.

# Answer
> 2 votes
As far as I know, you can include your libraries from a custom location by using their absolute path.

Since absolute paths could be boring from a code-portability point of view, you could define some macros to get the absolute path from a given relative one. In this way, you would just have to fix the 'project root' path when passing from a device to another.

Define your project's root folder :

```
    #define PROJECT_ROOT C:\path\to\your\project\folder

```

Define a relative-to-absolute macro 'transformation' :

```
    #define TO_STRING(s) #s
    #define ABSOLUTE_PATH(root, relative_path) TO_STRING(root\relative_path)
    #define RELATIVE_PATH(library) ABSOLUTE_PATH(PROJECT_ROOT, library)

```

Include your files using the relative path :

```
    #include RELATIVE_PATH(some\file\relative\path.h)
    #include RELATIVE_PATH(another\file\relative\path.h)

```

I hope it will be useful.

# Answer
> 1 votes
The simplest way I've found to do this is store the libraries in your local sketch directory and create a symbolic link in the \[HOME\]/Arduino/libraries directory. Then you can check them in to Git easily with your sketch/project and Arduino's still happy because the libraries are accessible in the global folder.

Maybe even create an install script that creates these links automatically and check that into Git too.

# Answer
> 0 votes
Another really bad fix - create a file called `libraries.cpp`, which contains:

```
// force the linker to build the libraries
#include "libraries/LIB1/src/FILE1.cpp"
#include "libraries/LIB1/src/FILE2.cpp"
#include "libraries/LIB2/src/FILE1.cpp"

```

Of course, this only works if the library does not itself contain any includes...

---
Tags: library, sketch, system-design
---


# Question
Title: How to generate Chirp Signal using Arduino
i would like to generate Chirp Signal (Frequency Sweep) using Arduino. i have searched a lot in internet but didn't find anything.

Basically, any parameters is also ok. But the concept is what i am searching for. The signal will be sent to the DAC of the Arduino board.

Edit I would like to generate sine wave signal from 3kHz up to 100kHz sweep frequency with amplitude peak to peak 1.5 volt.

thanks for your support.

# Answer
If you're ok with starting with square wave signals, this can be done on an Arduino. You need to do the following:

1. Configure a 16-bit Timer to **CTC** mode
2. Select the right prescaling
3. Add a RC low pass filter to the output and voltage divider

## Configure a 16-bit Timer to **CTC** mode

Assuming I'm using **Timer 1** and **OCR1A**:

```
TCCR1A |= (1<<COM1A0); // Toggle OC1A on match
TCCR1B |= (1<<WGM12); // Clear to Compare mode
TCCR1B |= (1<<CS10); // No prescale

```

## Select the right prescaling

In case you're wondering, prescales are used when the MCU clock is much faster than the output you desire. Without prescaling, the highest frequency is 16MHz/2 = 8MHz, and the lowest frequency would be 8MHz / 2^16 = 122Hz . Which covers the range of frequencies that we want.

Setting OCR1A value to 80 gives you a frequency of 100kHz Setting OCR1A value to 2667 gives you a frequency of 2.9996kHz

You can then control the chirp like so:

```
// Linear rise in wave period
int x = 10;
for (int x=80; x < 2668; ++x){
  OCR1A = x;
  delay(10); // 10ms delay
}

```

## Add a RC low pass filter to the output and voltage divider

Making the perfect sine waves may be too troublesome, so we'll resort to the poor man's sine wave.

Here's the poor man's implementation by TI (still require quite a few parts.)

Personally, I'm cheap so I'd go for the RLC approach. ;-)
> 3 votes

# Answer
Recommend to use a VCO PLL as external hardware device to get the wanted variable-frequency signal. The DAC output from Arduino can control the voltage to external VCO PLL module. Here is the link for an app note for VCO PLL from Vectron.

http://www.vectron.com/products/vcxo/vcxo.pdf

Hope it helps.
> 2 votes

# Answer
Since you mentioned SINE wave, I think you're seeking a SWEEP signal. A chirp is a much more complex sound.

To get a sine wave sweep, you probably want a sine function that doesn't use up most of the Arduino executable space.

You can use one of the compact sin(theta) functions that leverage a simple table of values. Just pull the code you need from the cordic.c here: https://people.sc.fsu.edu/~jburkardt/c\_src/cordic/cordic.html. C runs in Arduino sketches almost out of the box. You may or may not need some things from the cordic.h. That's why I said "almost". The cordic\_prb.c test file has a function test002() that shows you how to call the sine function.

Letting theta = t * (t + k), you will get your sweep, with your instantaneous frequency, f = 2 * pi * (t + k). You will need to calculate the correct k and set t\_max to end your loop. This can be obtained from the above formula and your f\_min of 3kHz and f\_max of 100kHz.

You can use a linear translation to get the sample in the range of values that you want: s = s\_center + s\_peak * sin(theta) / 2, but you will need to calculate your s\_ave and s\_peak from your center voltage, V\_center, and your peak to peak voltage, V\_peak. So there are two translations. This second one depends on the Voltage range of your Arduino board DAC.

Record your sample and voltage range for the board and then Work backward from Voltage range to V\_center and V\_peak to s\_center and s\_peak to your two coefficients to multiply and add to your sin(theta) result.

It's just a little algebra and some integration of some code, and you've got your SWEEP generator.

Also remember that boards like the Uno and Mega do not have a real D-to-A converter, so they will only give you a rectangular wave that has digital noise over the primary harmonic that approximates your sweep. Use the Due to avoid lots of digital noise. That's the down side of the pulse width modulation of the lower end Arduino chips.

Either way, you may want to attenuate higher frequencies from any type of D-to-A conversion with a simple passive (RC) or active (op amp) low pass filter.
> 0 votes

---
Tags: arduino-leonardo, signal-processing
---


# Question
Title: EPS8266 ESP-01 Blue led stays lit unless 3.3v logic divider is bypassed, works when reconnected
I am having a very weird and frustrating issue with this ESP01. I am creating a shield on protoboard, and everything checks out as far as I can tell. I am using a 3.3v voltage divider (1k and 2.2k) from arduino TX to ESP RX.

When I connect the ESP straight to the arduino Mega 2560, it works fine. When I connect the ESP to my protoboard, the blue led stays lit. Now here's he weird part.

I broke out the protoboard header with jumpers to the ESP, 3.3v to vcc and ch\_pd, gnd to gnd in my header. Bypassing the logic voltage divider on my protoboard results in a working ESP8266.

While still powered up, I moved the Tx/Rx to the header, through the voltage divider, and it still works! But when I disconnect USB from the Arduino, then reconnect, the blue led stays lit, until I bypass the voltage divider, connect to the ESP, then connect back to the divider.

I am currently testing my code with a simple serial relay sketch, ESP on Serial3. I have nothing else connected to ESP besides vcc, ch\_pd, gnd, tx and Rx. I am connecting to the arduino and ESP on 115200 baud. The ESP replies without garbage on 115200 when connected straight to Serial3 rx/tx

I thought insufficient power may have been an issue, using the mega's 3.3v for vcc, so I built a voltage regulator circuit converting a 9v battery to 3.3v (well 3.75, using an LM317T with R1=330ohm/R2=660ohm because it's what I had on hand) and there was no change in performance, besides the LEDs being slightly brighter. The ESP still functioned with RX/TX straight to the mega while connected to the 3.75v supply.

I know pics would help a lot, and I can post some later tonight after work. My wife, sensing my frustration, told me to set everything down and go to work so I wouldn't break anything, so I am asking around for possible fixes for when I get home.

I appreciate any and all replies, and will provide any necessary clarification.

Thanks, Vl4d

# Answer
> 1 votes
A wiring diagram would help.

Also, measure the 3.3v regulator's output, especially under load; 9v batteries are best in low-drain long-life applications like smoke detectors. Another supply, perhaps Arduino's 5v supply, might be a better source for the 3.3v regulator.

# Answer
> 1 votes
I would also check the ground on the components. All of the ground pins need to be connected together. IC's get flakey with grounding issues.

---
Tags: serial, arduino-mega, esp8266
---


# Question
Title: which spi mode shall i use given this timing diagram
I need some help to ensure my understanding of how this is supposed to work.

I want to know given the attached serial timing diagram which spi mode should I use?

Based on my newly found knowledge I believe it should be mode 1 How do you use SPI on an Arduino?

Is this correct?

# Answer
> 1 votes
We can see from your diagrams that the starting state of the clock line after the CS goes active is low indicating a CPOL of zero. Also, we see that data changes after the falling edge of the clock indicating the CPHA is also zero. This infers, according to this reference, that the SPI mode is zero.

# Answer
> 0 votes
If you look at the diagram you showed, it makes sense to use mode zero.

Clearly you need mode 0 or mode 1 because the clock is normally low.

Now looking at the change of the data vs the clock, it makes sense that you sample on the leading edge (mode 0) - the red lines - because the diagram shows that the data is held steady for a while after the clock changes (from low to high).

It wouldn't make sense to sample on the trailing edge because immediately after that (the blue line) the data changes.

---
Tags: arduino-uno, spi
---


# Question
Title: Why use an int variable for a pin when const int, enum or #define makes much more sense
Why do people use a variable to specify a pin number when the pin is unlikely to change throughout the execution of the code?

Many times I see an `int` being used for a pin definition,

```
int led = 13;

```

when the use of a `const int`

```
const int led = 13;

```

or `enum`, or `#define`

```
#define LED 13

```

makes much more sense.

It is even in tutorials on the Arduino site, for example, the first tutorial that most people run, Blink.

I read somewhere that `const int` is preferred over `#define`. Why isn't this encouraged right from the beginning, rather than allowing people to develop bad habits, from the outset? I noticed it a while back, but recently it has started to irritate me, hence the question.

Memory/processing/computing wise is a `const int`, `enum`, or for that matter `#define`, better than a plain `int`, i.e. occupies less memory, stored in different memory (Flash, EEPROM, SRAM), faster execution, quicker to compile?

---

This may appear to be a duplicate of Is it better to use #define or const int for constants?, but I am addressing the question of why people use variables, and how does the performance improve when they don't, rather than which type of constant is better.

# Answer
```
const int led = 13;

```

That is the correct method. Or even:

```
const byte led = 13;

```

How many pins do you have?

Some of the tutorials did not quite go through as much quality control as they might have.

Performance will be better using `const byte`, compare to `int` however the compiler may be smart enough to realize what you are doing.

What you can do is gently encourage people to use more efficient techniques by using them in your own code.

---

### Responses to comments

1. A commenter has suggested that `byte` is not standard C. This is correct, however this is an Arduino StackExchange site, and I believe using standard types supplied by the Arduino IDE is acceptable.

In Arduino.h there is this line:

```
typedef uint8_t byte;

```

Note that this is not exactly the same as `unsigned char`. See uint8\_t vs unsigned char and When is uint8\_t ≠ unsigned char?.
2. Another commenter has suggested that using byte will not necessarily improve performance, because numbers smaller than `int` will be promoted to `int` (see Integer Promotion Rules if you want more on this).

However in the context of a **const** identifier, the compiler will generate efficient code in any case. For example, disassembling "blink" gives this in the original form:

```
00000086 <loop>:
  86:   8d e0           ldi r24, 0x0D   ; 13
  88:   61 e0           ldi r22, 0x01   ; 1
  8a:   1b d1           rcall   .+566       ; 0x2c2 <digitalWrite>

```

In fact it generates the same code whether the `13`:

* Is a literal
    * Is a `#define`
    * Is a `const int`
    * Is a `const byte`

---

The compiler know when it can fit a number into one register and when it can't. However it is *good practice* to use coding that indicates your *intent*. Making it `const` makes it clear that the number won't change, and making it `byte` (or `uint8_t`) makes it clear that you are expecting a small number.

---

### Confusing error messages

Another major reason to avoid `#define` is the error messages you get if you make a mistake. Consider this "blink" sketch which has an error:

```
#define LED = 13;

void setup() {
  pinMode(LED, OUTPUT);      // <---- line with error
}

void loop() {
  digitalWrite(LED, HIGH);   // <---- line with error
  delay(1000);
  digitalWrite(LED, LOW);    // <---- line with error
  delay(1000);
}

```

On the surface it looks OK, but it generates these error messages:

```
Blink.ino: In function ‘void setup()’:
Blink:4: error: expected primary-expression before ‘=’ token
Blink:4: error: expected primary-expression before ‘,’ token
Blink:4: error: expected `;' before ‘)’ token
Blink.ino: In function ‘void loop()’:
Blink:8: error: expected primary-expression before ‘=’ token
Blink:8: error: expected primary-expression before ‘,’ token
Blink:8: error: expected `;' before ‘)’ token
Blink:10: error: expected primary-expression before ‘=’ token
Blink:10: error: expected primary-expression before ‘,’ token
Blink:10: error: expected `;' before ‘)’ token

```

You look at the first highlighted line (line 4) and *don't even see* a "=" symbol. Plus, the line looks fine. Now it's fairly obvious what the problem is here (`= 13` is being substituted for `LED`), but when the line is 400 lines further down in the code, it isn't obvious the problem is with the way LED is defined.

I've seen people fall for this many times (including myself).
> 20 votes

# Answer
As Ignacio has rightly states, it's basically because they don't know better. And they don't know better because the people who taught them (or the resources they used when learning) didn't know better.

Much of the Arduino code and tutorials are written by people who have never had any training in programming and are very much "self taught" from resources by people who themselves are very much self taught with no proper training in programming.

Many of the snippets of tutorial code I see around the place (and especially those that are only available within YouTube videos --- urgh) would be a fail mark if I were marking them in an exam.

Yes, a `const` is preferred over a non-const, and even over a `#define`, because:

* A `const` (like a `#define`, unlike a non-const) does not allocate any RAM
* A `const` (like a non-const, but unlike a `#define`) gives the value an explicit *type*

The second point there is of particular interest. Unless specifically told otherwise with embedded type-casting (`(long)3`) or a type suffix (`3L`) or the presence of a decimal point (`3.0`), a `#define` of a number will always be an integer and all mathematics performed on that value will be as if it were an integer. Most of the time that's not a problem, but you can run into interesting scenarios when you try to `#define` a value that is larger than an integer can store, such as `#define COUNT 70000` and then perform a mathematical operation with other `int` values on it. By using a `const` you get to tell the compiler "This value is to be treated as this variable type" - so you would instead use: `const long count = 70000;` and all would work as expected.

It also has the knock-on effect that it checks the type when passing the value around the place. Try passing a `const long` to a function that expects an `int` and it would complain about narrowing the variable range (or even completely fail to compile depending on the scenario). Do that with a `#define` and it would just silently carry on giving you the wrong results and leave you scratching your head for hours.
> 20 votes

# Answer
As a 2-week newbie to Arduino I'd pick up on the general idea of Arduino being occupied by non-programmers. Most sketches I have examined, including those on the Arduino site, show a total lack of order, with sketches that do not work & barely a coherent comment in sight. Flow charts are non-existent, and the "Libraries" are an un-moderated jumble.
> 2 votes

# Answer
My answer is... they do it because it works. I'm having a hard time not asking a question in my answer such as "why does it have to be 'wrong'?"
> 0 votes

---
Tags: variables, c-preprocessor, constants
---


# Question
Title: What does the following code in Morse Code Arduino mean?
```
  struct node *root, *currentNode;
  root = (struct node*)malloc(sizeof(struct node));
  root->value = '\0';
  root->next = 0;
  currentNode = root;

```

# Answer
> 1 votes
> What does the following code in Morse Code Arduino mean?

Step by step:

```
  struct node *root, *currentNode;

```

Pointer variables `root` and `currentNode`. Pointers to `struct node`.

```
  root = (struct node*)malloc(sizeof(struct node));

```

Allocate memory for a `struct node` and assign `root` pointer.

```
  root->value = '\0';
  root->next = 0;

```

Assign `struct node` members using the `root` pointer. Assign `value` member to character 0. Assign `next` to zero, NULL, i.e. often marks end of list.

```
  currentNode = root;

```

Last assign `currentNode` to point to the save value as `root`, i.e. the allocated `struct node`.

Next question?

# Answer
> 0 votes
What's missing from this tiny code excerpt is the definition of 'struct node'. From the name, 'node', the member name, 'next', and the way these are being assigned, it's very likely that these 'struct node's are part of a linked list structure; a collection of data that is arranged, not by location as in an array, but by each node having a pointer (memory address) to the next one in sequence. One fixed memory location (apparently 'currentNode') points to the first datum; that one points to the next, and so on until the last one in sequence whose pointer value iz zero (or NULL, the symbol commonly used for an invalid pointer value).

Sorting a list is quicker than sorting an array or a collection of arrays of data, because only the pointers need to be changed; no data needs to be moved. Adding or deleting data in the middle of the list benefits even more; in an array you'd have to move all of the data following the add- or delete-point to create or close a gap for the new or removed datum.

Look at the rest of the code. It's quite likely that is how the 'node's are being used. Also read about linked lists, if that is a new concept.

---
Tags: sketch
---


title: High Frequency Sine Wave Generation

text:
# Question
Title: High Frequency Sine Wave Generation
I'm new to the world of Arduino and I'm working on a wireless charging project that needs a 5.7MHz sine wave. I've tried using a Due and changing the PWM and DAC, but I can't get a clean sine wave at that frequency using anything I've found online. My signal is either way too low, or too high and horribly distorted.

Any help would be appreciated. I have access to a Mega, Due, Uno, and Mini.

# Answer
To generate a **square wave**, you only need to update the output at a rate of two points per cycle. (*Technically, when the Arduino's PWM output is configured for 50% duty cycle, that's a square wave at some frequency.*)

But to generate a clean **sine wave** (without a lot of **distortion**), you need to update a lot more frequenclly than two points per cycle. Personally I wouldn't want to go much below 20 points per cycle.

Imagine the sine wave is generated by a wheel that spins at some rate. Viewed from the edge, a point on the edge of the wheel traces out a sine wave. Viewed from the axle, you see the point going around in a circle.

Now instead of spinning the wheel continuously, suppose the wheel moves in steps of 30 degrees, 12 steps for a complete turn. Instead of a continuous sine wave, you get discrete steps of 0, 0.5, 0.866, 1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5, 0, 0.5, ... Although this sequence approximates an ideal sine wave, it's pretty coarse because the steps are so large.

Now try 15 degrees per step (24 steps per cycle). Now you get 0, 0.259, 0.5, 0.707, 0.866, 0.965, 1, ... Much smoother, although the steps are still fairly noticeable.

So there will be less **phase error**, the more steps there are per cycle of the signal. That's not the only source of distortion however. There is also round-off error due to the limited resolution of the Digital-to-Analog Converter (DAC). For example, the value 0.866 I mentioned above should actually be an irrational value, half the square root of 3. Since it's an irrational number, there's no way for a real DAC to get this value exactly right. DAC output step values are ideally based on powers of two (1/2, 1/4, 3/4, 1/8, 3/8, 5/8, 7/8, etc.). And furthermore a real DAC can have offset error, gain error, non-linearity, as well as uncertainty about precisely when the new programmed value is reached.

There's also **frequency error** when the system's highest-frequency master clock is divided by an integer. If the Arduino UNO's master clock frequency is 16MHz, and the SPI setup function `setClockDivider()` is used to divide the master clock by 2, that's 8MHz. Divide by 3 and you get 5.333MHz. Divide by 4, that's 4MHz. Divide by 5, that's 3.2MHz. There's no way to get a clock frequency that's between these discrete steps. For small divisors, there's a big jump between steps. So if you needed to be able to smoothly adjust the frequency, you'd need a much higher master clock frequency. And, if you needed to configure the 16MHz Arduino UNO to an SPI clock frequency of exactly 5.7MHz, that's just not possible -- setClockDivider(2) is too fast, setClockDivider(3) is too slow, and setClockDivider(2.807017543859649) isn't supported by the hardware.

If your system could write to a DAC at an **update rate** of 12MHz, then 12 points per cycle gives a 1MHz output, and 24 points per cycle gives a 500kHz output. Or taking it the other way round, if you need to generate a 5.7MHz output waveform, then the DAC update rate needs to be somewhere around 100MHz to get a clean, low-distortion waveform. This is probably beyond the limit of what you can directly synthesize in software using something like an Arduino or a Raspberry Pi. A 16MHz Arduino UNO could maybe synthesize a few 100kHz using software synthesis, but at 1MHz there's going to be significant distortion.

Software-controlled`Direct Digital Synthesis` is very sensitive to timing, so the actual DAC update would need to be implemented in an **interrupt service routine**, run by a periodic timer. ( See https://electronics.stackexchange.com/questions/26363/how-do-i-create-a-timer-interrupt-with-arduino ) If you just used a while loop with a delay statement, then whenever the code needs to do something else, the waveform would just freeze up. This is more of a problem if the Arduino is trying to manage several other tasks at the same time as it is synthesizing the waveform.

**Hardware** `Direct Digital Synthesis` (DDS) is possible. Same principles. There needs to be a `phase accumulator`, which is just a counter that keeps track of the phase angle of the "wheel" that's generating the sine wave. *(The phase accumulator needs to be modulus 360 degrees or 2 pi radians, but there's no requirement to count in 1 degree steps. Better to divide the circle into 2^N slices so that 360 degress maps to the natural counter overflow value.)* And there also needs to be a lookup table with the sine value for each of those steps. This lookup table only needs to cover 90 degrees of the sinewave, because the waveform is symmetrical -- the other three quadrants can be found by 2's complementing the values and indexing from the other end of the table. Or, the sine can be approximated by a polynomial calculation. More steps x more DAC resolution requires a deeper, wider lookup table. There are integrated circuits available that perform the timing-critical actions, all the software needs to do is send some initial configuration to set it up. Changing the frequency only requires configuring a new frequency divisor value into the DDS chip, so the Arduino can manage other things without causing distortion.

If the original problem only needs one **fixed frequency under 200MHz**, and doesn't need any adjustment to that frequency, then the hardware gets a whole lot simpler. The crystal oscillator circuits that we use to generate the timing for digital circuits, are in fact analog to begin with. You can contact a crystal vendor and request a custom **AT cut crystal**; google `custom quartz crystal frequency` for quartz crystal vendors. Construction requires a careful printed circuit board layout; the white solderless breadboard commonly used in Arduino projects just doesn't work well above 10MHz. Granted, this fixed-frequency solution doesn't involve Arduino in any way, but if it solves the problem, that's what's important.
> 5 votes

# Answer
I wonder for which purpose you would use a micro controller at all.

If you need a fixed frequency circuit, you could design just that.

If you need a generator with variable frequency, that would justify the Arduino, but in this case I would use the Arduino to control the frequency indirectly.

Ex: create a VCO and use the Arduino to adjust the voltage, through a DAC
> 0 votes

# Answer
One problem (for me) is to know how much time lines of (C) code take to execute on a (16) MHz Arduino. This and the coding you use would set an upper limit to the sinewave frequency you could synthesise at a given quality.

You probably can't beat assembly language when time is tight.
> 0 votes

---
Tags: arduino-uno, arduino-mega, arduino-due, arduino-pro-mini, frequency
---


title: AVRDUDE Error (Arduino Leonardo)

text:
# Question
Title: AVRDUDE Error (Arduino Leonardo)
I, like many others, have encountered the avrdude error. However, I am not sure how to go about fixing mine after looking at numerous forums, etc.

```
avrdude: verification error, first mismatch at byte 0x0002
     0x74 != 0xe6
avrdude: verification error; content mismatch

```

I am simply trying to upload a simple sketch, but right when it seems it is about to finish, I get this error and the uploading loading bar simply never finishes...

Thanks for the help!

# Answer
I had lots of issues when I first started. these are all things I tried and at least one of them stopped this problem occurring, but I haven't a clue which.

1. Close the IDE (if you are using it and open it again)
2. Disconnect your board, wait 10 seconds and reconnect it.
3. Check you settings, are you using the correct board, etc.
4. Use a different cable.
5. Update your drivers.
6. Update your IDE/Toolset.
7. Use a different physical port on your PC.
8. Load the Blink example, if that doesn't work you serious have issues.
9. Reboot your PC.
10. If you can, try a different PC.
> 1 votes

# Answer
I have a USB socket on the PC which causes the Arduino to lose track of its COM port although apparently Ok with other USB devices. Check your COM port before and after you try uploading.
> 0 votes

---
Tags: arduino-leonardo, uploading, avrdude
---


title: Wearable GPS Antenna

text:
# Question
Title: Wearable GPS Antenna
I am using the Adafruit Fona 808 to make a wearable device. One of the main features is GPS but I cannot seem to find a suitable antenna for wearables. My question is: What is a good GPS antenna for a wearable project and should it be active or passive? Thanks

# Answer
> 0 votes
I too thought whats wrong with a normal Antenna, but the answer is the problem is the human body.

There are manufacturers that make "fabric" antennas, but these tend to be Mil-Spec so are going to cost a fortune. (http://www.pharad.com/gps-wearable-antenna.html)

I found this site that explains what the effect of the body is, and seems to make their own antenna. http://www.pharad.com/gps-wearable-antenna.html

I think you might be better off looking for a high gain antenna and the choice of active or passive will probably be based on the interference you get from the body.

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


title: Better way to remap 16-Key Touch keypad

text:
# Question
Title: Better way to remap 16-Key Touch keypad
I have written a code that remaps the buttons of `TTP229` touch keypad which works as it is. Is there any way to optimize this code:

```
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#define SCL_PIN 11
#define SDO_PIN 12
#define I2C_ADDR    0x3F
#define BACKLIGHT_PIN     3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7

byte Key;
String keyRemap[12][2] = {
    {"1","1"},{"2","2"},
    {"3","3"},{"5","4"},
    {"6","5"},{"7","6"},
    {"9","7"},{"10","8"},
    {"11","9"},{"14","0"},
    {"13","Clear"},{"15","Enter"}
};

LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

void setup()
{
    lcd.begin (16,2);
    lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
    lcd.setBacklight(HIGH);
    lcd.home ();

    pinMode(SCL_PIN, OUTPUT);
    pinMode(SDO_PIN, INPUT);
}
void loop()
{
    Key = Read_Keypad();
    if (Key != 0) {
        lcd.clear();
        lcd.setCursor (0,0);
        for (int x = 0; x < 12; x++) {
            if (Key == keyRemap[x][0].toInt()) {
                lcd.print(keyRemap[x][1]);
            }
        }
        delay(160);
    }
}
byte Read_Keypad(void)
{
    byte Count;
    byte Key_State = 0;

    for (Count = 1; Count <= 16; Count++)
    {
        digitalWrite(SCL_PIN, LOW);
        if (!digitalRead(SDO_PIN))
            Key_State = Count;
        digitalWrite(SCL_PIN, HIGH);
    }
    return Key_State;
}

```

# Answer
> Is there any way to optimize this code:

Absolutely, yes. Don't use `String` for this, you are seriously wasting memory. Instead you can use a `struct`:

```
struct keymap {
    uint8_t code;
    const __FlashStringHelper *value;
};

const struct keymap keyRemap[] = {
    { 1, F("1") },
    { 2, F("2") },
    { 3, F("3") },
    { 5, F("4") },
    { 6, F("5") },
    { 7, F("6") },
    { 9, F("7") },
    { 10, F("8") },
    { 11, F("9") },
    { 14, F("0") },
    { 13, F("Clear") },
    { 15, F("Enter") },
    { 0, 0 }
};

void loop() {
    int Key = Read_Keypad();

    if (Key != 0) {
        lcd.clear();
        lcd.setCursor(0, 0);

        for (int x = 0; keyRemap[x].code != 0; x++) {
            if (Key == keyRemap[x].code) {
                lcd.print(keyRemap[x].value);
            }
        }

        delay(160);
    }
}

```
> 1 votes

---
Tags: arduino-nano
---


# Question
Title: Where can i get a current Websockets Library for Arduino that will work with the Ethernet Shield
I'm trying to get a simple WebSocket client working on an Arduino Mega with an ethernet shield. I tested the ethernet on the Arduino and it's working fine. I've tried a few of different WebSocket libraries the example sketches fail to connect. I've tried them with echo.websocket.org and with two different express instances ( one running WS and one running SocketIO ). But the WebSocket connection seems to fail.

https://github.com/billroy/socket.io-arduino-client

https://github.com/krohling/ArduinoWebsocketClient

is there a preferred library for the most recent WS standard that anyone has used with sucess recently?

# Answer
I have debugged both these libraries using wireshark, sending a message to a node.js ws server in my computer, and there really is some sort of problem in the handshake. The package is sent by the client and received by the host, by the connection with the ws server is never established.

Was anyone able to use them? Is there any alternative (besides Johnny-Five)?
> 1 votes

---
Tags: web-server
---


title: Mapping PPM Signals to Servo Values

text:
# Question
Title: Mapping PPM Signals to Servo Values
This question is an extension of this question.

Accessing Values From Array Within a Library

The answer provided by Mark showed me how to read and print a single value from a particular array by using the index number to print to the serial console.

The second part of this question is how to get these values from the array to map to 0-180 for values that are useful to the servo.

The below code is my attempt that is not working. I used the servo sweep example from the Arduino examples which worked fine with a potentiometer but not with the ppm input. What am I doing wrong here? This won't compile. (I am using TinyServo.h library since this is for an attiny85. Works with with the pot mapping just fine.)

```
#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int PPM_INPUT_PIN = TinyPpmReader.width_us(3); //<------- Doesn't work

//int potpin0 = 3;    <---------          // This worked
int val0;                     // integer to store value

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

void setup()
{
  setupServos();
}

void loop()
{
  val0 = analogRead(PPM_INPUT_PIN);  <---------          //Doesnt work// reads the value of the       potentiometer (value between 0 and 1023)            // reads the value of the 2nd potentiometer (value between 0 and 1023)
  val0= map(val0, 1000, 2000, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)
       // scale it to use it with the servo (value between 0 and 180)

moveServo(PANSERVO, val0);

  delay(5);                           // waits for the servo to get there
}

```

For some background, the ppm library outputs like this to the serial monitor:

Ch4=**1560** us

These values move from ~1000 - 2000 depending on the ppm signal input. (The input is from a RC remote control receiver)

This example below prints only channel 4 (Ch4=1560 us)from a total of 8 channels. Now, I want to map this to the values of 0-180:

```
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

#define PPM_INPUT_PIN  2

void setup()
{
  Serial.begin(38400);//attiny tx - rx uno does not work at 9600 baud. Set to 38400 @ attiny 1mhz and uno serial console to 38400 baud
  TinyPpmReader.attach(PPM_INPUT_PIN); /* Attach TinyPpmReader to PPM_INPUT_PIN pin */
}

void loop()
{

Serial.print(F("Ch"));Serial.print(3);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(3));Serial.println(F(" us"));

 display results */
  delay(500);
}

```

What am I doing wrong?

# Answer
```
int PPM_INPUT_PIN = TinyPpmReader.width_us(3);

```

will save the result into variable `PPM_INPUT_PIN`, while

```
val0 = analogRead(PPM_INPUT_PIN);

```

will save an analog reading results from `PPM_INPUT_PIN` channel into variable `val0`. This is (one of) your problem. To map the PPM value, you can do:

```
#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int val0,                     // integer to store value
    mappedval0;               // integer to store mapped value;

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

const int PPM_max_value = xxxxx; //put the max value of PPM reading result
const int PPM_min_value = yyyyy; //put the min value of PPM reading result

void setup()
{
  setupServos();
}

void loop()
{
  val0 = TinyPpmReader.width_us(4);   //get PPM reading result from index 4
  mappedval0= map(val0, PPM_min_value, PPM_max_value, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)

  moveServo(PANSERVO, mappedval0);
  delay(5);                           // waits for the servo to get there
}

```
> 2 votes

---
Tags: c++, attiny, array
---


# Question
Title: Is there a way to have more than 14 Output pins on arduino?
Is it possible to have more than 14 output pins on the Arduino, I am working on a project in which I need to light up several LEDs individually. I only have an Arduino Uno, and I don't want to get a Mega.

# Answer
> 56 votes
A common way to expand the set of available output pins on the Arduino is to use shift registers like the 74HC595 IC (link to datasheet).

You need 3 pins to control these chips:

1. Clock
2. Latch
3. Data

In a program, you pass on the data one bit at a time to the shift register using the shiftOut() command, like so:

```
shiftOut(dataPin, clockPin, data);

```

With that command, you set each of the 8 outputs on the 595 IC with the 8 bits in the `data` variable.

With one 595, you gain 5 pins (8 on the IC, but you spend 3 to talk to it). To get more outputs, you can daisy-chain a series of 595 together, by connecting its serial-out pin, to the data pin of the next one. You also must connect together the clock and latch pins of all of the 595 ICs.

The resulting circuit (using one 595) would look like this:

The figure above was taken from this codeproject.com webpage:

The latch pin is used to keep the 595 outputs steady while you are shifting out data into it, like so:

```
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, data);
digitalWrite(latchPin, HIGH);

```

# Answer
> 32 votes
There are two ways you can get more pins out of an arduino.

The first way is by using the Analog pins as digital output pins, which is really easy to do. All you need to do is refer to A0-A5 as pins 14,15,16,17,18,19. For example to write high to pin A0 just use digitalWrite(14, HIGH).

The other way to get more pins out of the Arduino is by using a Shift Register. To do this I recommend using the EZ-Expander Shield, which allows you to use digitalWrite(\[20-35\], HIGH) when you import the EZ-Expander Library. This shield however only allows the pins to be used as outputs only and uses pins 8,12 and 13 to control the shift registers.

The great thing is, is that you can use both of the two methods above together, without any problems.

# Answer
> 21 votes
## I2C (Wire)

You can use the I2C protocol (Wire library) to connect to other devices such as port-expanders. For example, the MCP23017.

I used one of those chips to connect to an LCD board. The MCP23017 has 16 ports, which can be configured as inputs or outputs. As inputs they can raise interrupts if desired.

Example of connecting 13 of those 16 to the LCD:

Now we connect to the Arduino using only 2 wires (SDA/SCL) plus power and ground:

---

Some third-party manufacturers have made boards with 4 x MCP23017 on them, this gives you 64 inputs/outputs:

---

## Multiplexers

You can use analog multiplexers like the 74HC4051 (8 ports) or the 74HC4067 (16 ports) to connect one pin to one of the 8/16 ports (but only one at a given time), like this:

These are bi-directional, so can be used as an input or output expander.

---

## SPI with 74HC595

Using SPI you can send fast serial data to a shift register, such as the 74HC595. These can be daisy chained together. In this example I am controlling 32 LEDs with only 3 I/O pins (MOSI/MISO/SCK) plus power and ground.

---

I found inside a commercial LED sign that the 72 LEDs were driven by 74HC595 chips.

This had 9 chips driving the columns (9 x 8 = 72 LEDs) and one chip driving the rows, in a multiplexed configuration.

---

## SPI with MAX7219

If you just want to drive LEDs you can usually multiplex them. The MAX7219 simplifies that by being designed to drive LED matrixes, for example 7-segment displays:

Or 64-LED matrixes:

In both cases these can be daisy-chained together, for example:

All those examples only use 3 pins of the Arduino (MOSI/MISO/SCK) plus power and ground.

---

## SPI with MCP23S17

The 16-port port expander mentioned earlier (MCP23017) also comes in an SPI variant (MCP23S17), which does virtually identical things. It uses one more wire, but would be faster.

---

## Other protocols

LED strips (like the NeoPixel ones) have their own protocols. There was a post on Youtube by Josh Levine where the author drove over 1000 pixels with a Duemilanove!

---

## References

# Answer
> 20 votes
If you want to drive LEDs, then you can also use a MAX7219 that can drive 64 LEDs, without extra circuitry (no need for transistor to amplify signal).

Driving a MAX7219 requires only 3 output pins on Arduino. Also, you can find a few Arduino libraries for it.

You can also chain several of them if you need to power more than 64 LEDs.

I have used it successfully for multiple 7-segment LED displays.

Downside: it is expensive (about $10).

# Answer
> 19 votes
You can use Charlieplexing. With this technique you can directly drive `n*(n-1)` LED's from n pins. So with 3 pins you can drive 6 LED's, 4 pins - 12 LED's, 5 pins - 20 LED's and so on.

Exemple:

Six LED's on 3 Pins

```
PINS        LEDS
0 1 2   1 2 3 4 5 6
0 0 0   0 0 0 0 0 0
0 1 Z   1 0 0 0 0 0
1 0 Z   0 1 0 0 0 0
Z 0 1   0 0 1 0 0 0
Z 1 0   0 0 0 1 0 0
0 Z 1   0 0 0 0 1 0
1 Z 0   0 0 0 0 0 1
0 0 1   0 0 1 0 1 0
0 1 0   1 0 0 1 0 0
0 1 1   1 0 0 0 1 0
1 0 0   0 1 0 0 0 1
1 0 1   0 1 1 0 0 0
1 1 0   0 0 0 1 0 1
1 1 1   0 0 0 0 0 0

```

You can see a better tutorial here.

# Answer
> 13 votes
Shift registers have been mentioned in other answers, and they are definitely an excellent choice for many projects. They are cheap, simple, moderately fast, and can typically be chained together to add more outputs. However, they have the downside that they usually need exclusive use of several pins (between 2 and 4, depending on how you set them up).

An alternative is to use more advanced port expanders, such as the 16-bit MCP23017 and MCP23S17. These support I2C and SPI respectively, which means you can place them on a bus with several other devices (potentially of different types). Each device on the bus can be individually addressed, meaning you only need 2 or 3 pins to talk to all of them. The update speeds are typically extremely fast, so you're unlikely to experience significant latency (i.e. transmission delays) in an Arduino project.

At a low level, using I2C or SPI is substantially more complicated than a simple shift register. However, there is library code for Arduino to take care of that for you. See this question, for example: How do I use I2C devices with Arduino?

# Answer
> 11 votes
In addition to Ricardo's answer, what Wikipedia states on shift registers:

> One of the most common uses of a shift register is to convert between serial and parallel interfaces. \[...\] SIPO registers are commonly attached to the output of microprocessors when more General Purpose Input/Output pins are required than are available. This allows several binary devices to be controlled using only two or three pins, but slower than parallel I/O.

In the article Ricardo linked you can see the diagram of the shift register.

What happens here is that you put the data of the 8 pins in a sequence and for each clock tick the shift register will shift (move the binary data from each latch to the next one) until it "makes a circle" i.e. the first bit arrives to the last pin. Shift registers also have an input where you can turn on/off the shifting so the status can be kept after the data is shifted to the position. For a simple demonstration see the following animation.

Here the red light is the serial input and the green ones are showing the state of the latches in this simplified SIPO shift register. After the data shifted to place shifting can be turned off and you can read the pins. In this example I shifted out `10101011`.

From these examples you can realize that serial transfer will be slower than parallel, because you have to wait for the shift register to shift the bits to their place. You will have to wait the same amount of clock tick as many bits you want to load. This is one of the many reasons why you can't chain them indefinitely, because loading would take forever.

# Answer
> 7 votes
As you wrote already already, you can use all pins, including TX and RX as digital output. I did that a while ago for a demonstrator and recorded a video - 20 LEDS on 20 pins \- of this rather nonsensical project.

As described by *Peter R. Bloomfield* here, you a have to disconnect TX and RX for upload. Moreover, you're out of pins to read sensors for possible interactivity and have to make sure that the total current limit isn't reached. Not to forget that you're limited to 5V leds if you drive them directly with your Arduino.

The use of shift registers in general and the 595, described by *Ricardo* is therefore highly recommended.

* They are cheap!
* It's rather easy to cascade them.
* A lot of speed can be gained when you use hardware-SPI.

I used them a while ago when I realized the soldering and programming part of Kawaii me (text of the link is in German) of the upcycling artist *Dominik Jais*.

Here, just a bunch of **595** were used to drive a display of 8x11 leds. Since the leds were cut from a stripe of 12V SMD leds, an additional power supply and some **UDN2803A** Darlington arrays, hooked to the output pins of the shift registers, were necessary.

Other general methods would include the use of PCF8574(A) 8bit port expanders, which are controlled via the I2C bus.

Anyway, I'd give the 595 shift registers a try first.

If you need to control a couple of RGB leds, however, you might want to look for more specialized solutions. Some RGB leds come with their own **WS2812**. These fine pieces can be cascaded (1-Wire bus) and are addressed via their position in the chain.

# Answer
> 5 votes
I do not claim this method for my own, but I found this neat trick on the webpage MUX-DEMUX: CD4051 Parlor Tricks

Whatever method you choose to use to drive outputs or read inputs (shift registers, multiplexors or the straightforward direct use of the Arduino pins themselves) you can DOUBLE the number of outputs or inputs by a clever use of parallel circuit pairs (to form a dual input or output *bank*), employing diodes in opposing senses on each parallel branch, and switching the inputs/outputs to high and low.

To illustrate the method for outputs (LEDs in this case, note that the extra diodes are not required):

> If you consider the pair of LEDs in this example to be a "bank", and you want to light LED\_0, you need to set PIN 17 to HIGH, and PIN 18 to LOW. (The pin numbers are confusing, but they match the later example so bare with me). To light LED\_1, you just reverse the PINS. The diode nature of LEDs keeps the current from flowing the opposite direction keeping the other one off.

To illustrate the method for inputs (CdSs in this case, note that the extra diodes are required):

> This gets a little more complicated if you want to do an analog read on a CdS light sensor. First, you need to add a diode to each sensor to control the flow. Second, since you are reading values, you need to pull the inputs high or low to keep them from floating. Being a lazy person, I'm going to pull them high using the internal pull-up resistors. To read CdS\_0, you set PIN 17 mode to OUTPUT and set it to LOW. This makes it the ground. Then you set PIN 18 mode to INPUT and set it to HIGH to engage the pull-up resistor. Now you are set to do a read on PIN 18 (a.k.a. analog pin 4). To access the other sensor, just switch the modes and outputs.

So, if you have a CD4051 8 port multiplexor, using 5 pins on the Arduino (instead of the usual 3), you can obtain 16 inputs or outputs, or a mix of the two.

Likewise, if you have a 4067 16 port multiplexor you can obtain 32 inputs or outputs, or a mix of the two.

An example sketch would be:

```
/*
 * Example of getting 16 i/o from 5 pins using a CD4051
 *
 * Based on tutorial and code by david c. and tomek n.* for k3 / malmö högskola
 * http://www.arduino.cc/playground/Learning/4051?action=sourceblock&ref=1
 */

int selPin[] = { 14, 15, 16 }; // select pins on 4051 (analog A0, A1, A2)
int commonPin[] = { 17, 18};   // common in/out pins (analog A3, A4)
int led[] = {LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW };  // stores eight LED states
int CdSVal[] = { 0, 0, 0, 0 }; // store last CdS readings
int cnt = 0;  // main loop counter
int persistDelay = 100; // LED ontime in microseconds

void setup(){
  Serial.begin(9600);  // serial comms for troubleshooting (always)
  for(int pin = 0; pin < 3; pin++){ // setup select pins
    pinMode(selPin[pin], OUTPUT);
  }
}

void loop(){
  flashLEDs();
  if (cnt == 0){
    for(int x; x < 8; x++){
      led[x] = random(2);
    }
  }
  cnt++;
  if (cnt > 100) { cnt = 0; }
}

void flashLEDs() {
  for(int pin = 0; pin < 2; pin++) {  // set common pins low
    pinMode(commonPin[pin], OUTPUT);
    digitalWrite(commonPin[pin], LOW);
  }
  for (int bank = 0; bank < 4; bank++) {
    for(int pin = 0; pin < 3; pin++) { // parse out select pin bits
      int signal = (bank >> pin) & 1;  // shift  & bitwise compare
      digitalWrite(selPin[pin], signal);
    }
    if (led[bank * 2]){        // first LED
      digitalWrite(commonPin[0], HIGH);  // turn common on
      delayMicroseconds(persistDelay);   // leave led lit
      digitalWrite(commonPin[0], LOW);   // turn common off
    }
    if (led[bank * 2 + 1]){     // repeat for second LED
      digitalWrite(commonPin[1], HIGH);
      delayMicroseconds(persistDelay);
      digitalWrite(commonPin[1], LOW);
    }
  }
}

```

Like I said in the first line, the full explanation can be found on MUX-DEMUX: CD4051 Parlor Tricks

# Answer
> 2 votes
If it's all about LEDs, what about WS2812B LED strips, or just the driver chips themselves? You can control a virtually unlimited number of LEDs using just one pin!

Although people are use to these in strips, they are available as standalone LEDs (known as neo pixels on Adafruit). Or if you're only driving a single colour, each WS2811 chip could control 3 LEDs by using each of the RGB outputs for a single LED each.

I recently just created created a project that uses 5 such LEDs: Door1 open/closed, Door2 open/closed, motor1 active, motor2 active and power. The "active" LEDs are dual purpose since I have red being the input from active motor and green being active flag inside the Arduino.

Point being, with 1 pin and the library installed, you can control any number of LEDs

# Answer
> 1 votes
For a class project I used a CD4024 and two Arduino pins to drive a 7-segment display.

There are some caveats to this approach. For example, to write a `high` value to the first output of a ripple counter only requires a `reset` and toggling the clock pin twice. But if you want to write `high` to all n pins requires toggling the clock pin 2n times, and during that time all the other pins are constantly toggling on and off.

If your application can deal with these limitations and you're short on pins, it's another option.

Bonus answer: there are a lot of examples of multiplexing inputs here, many of which also apply to multiplexing outputs.

# Answer
> 1 votes
With a bit of work (installing a different bootloader) an additional seven I/O lines are available on an Uno, on the ICSP1 and JP2 headers. The replacement bootloader is called HoodLoader2. It allows you to install sketches on both the Atmega328 and Atmega16U2 on an Uno. Dealing with multiple processors would be the main complication from using this method.

On an Uno, the ICSP1 and JP2 headers connect to pins PB1...PB7 of the Atmega16U2. In addition the Atmega16U2 has about 9 I/O pins with no connection to the circuit board. A person working under a microscope might be able to attach wires to a total of 18 I/O pins on the 16U2, while leaving three other I/O pins attached to their ordinary connections.

HoodLoader2 also works on Mega boards.

# Answer
> 1 votes
There is a wealth of good answers here, but if you costed your time you'd find it cheaper to buy a Mega.

My 3/2-d worth.

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


# Question
Title: Arduino connection websocket always fails
I am using the Arduino Websocket Client library to connect my Arduino Uno to a Socket.IO server. But the connection always returns 0 (fail) after the handshake. Anyone has used this library before? How could I debug this?

```
#include "Arduino.h"
#include <Ethernet.h>
#include <SPI.h>
#include <WebSocketClient.h>

byte mac[] = {0xB8,0x27,0xEB,0x7E,0x2D,0xC9};
char server[] = "labathome.rexlab.ufsc.br";
int port = 8001;
WebSocketClient client;

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac);
  Serial.println(client.connect(server, port));
  client.setDataArrivedDelegate(dataArrived);
  client.send("Hello World!");
}

void loop() {
  client.monitor();
}

void dataArrived(WebSocketClient client, String data) {
  Serial.println("Data Arrived: " + data);
}

```

PS: I tested the server and it works fine, and I also tested with a normal WS server instead of the Socket.IO, and nothing :(

# Answer
> 1 votes
With the help of the library developer, I found out that it was a problem on the handshake version. So, I just downgraded my socket.io app from 1.0 to v 0.9.11 and it worked.

---
Tags: ethernet, web-server, web-service, web
---


# Question
Title: Arduino pro mini (clone) @1Mhz target does not answer
Recently I have been experimenting with battery powered sensor (mySensors).

I created node with 3.3V Arduino Pro Mini (ATMega328P @ 8Mhz with nordic radio chip and BME280 sensor) and successfully programed it many times using either USBAsp programmer or serial (to USB) programmer.

I wanted to lower power consumption and so I disconnected power led and burned fuses as follows: lfuse 62 hfuse DA efuse 7

It worked successfully and I recompiled the sketch and upload it with USBasp. I got an error that data cant be verified. It was late in the night so I jumped to Internet and googled it. In one forum I found, post (which I am unable to find again) that stated the he was able to upload sketch when he switched programmer to 5V. (Power was connected to Vcc)

I did that and it worked fine.

Than I tried to make change to sketch and upload it again (on 3,3V) and again got verification error so I unplugged programmer and switched back to 5V.

When I did that, the device stopped answering.

I regularly used this command to check that device responds and see fuses

```
avrdude.exe -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -cusbasp -Pusb

```

What i did

1. Checked wiring.
2. Tried program fuses on blank new arduino - worked (programmer is fine)
3. Measured voltage ok
4. Measured current (its around 4mA, I see it as the board is not sleeping and is actively doing something)
5. I noticed that when I issue command mentioned above the on board led quickly lights up and then goes off again.
6. I tried to power it from raw, from Vcc and from Vcc on serial hader (picture).
7. I measured power on Vcc when connected to Raw pin and it reads 3.3V so power regulator should be ok.
8. I used -B10 switch to averdude with no luck

My question is

1. Is it possible that I burned the ATMega chip?
2. Is it possible that I see target not answering because of USBAsp is unable to lower programming frequency? (warning: cannot set sck period. please check for usbasp firmware update.)

Please suggest if there is anything I can try before throwing it out.

Thank you.

**EDIT 2017-01-07** I was able to brick another board. I think that the programmer is the cause.

I tried to upload bootloader with fuses from arduino and it failed with verification error.

I was able to burn bootloader from command line after seting fuses and restarting the board.

When I tried to upload the program it I got

```
avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x00 != 0x0c
avrdude: verification error; content mismatch

avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: safemode: lfuse changed! Was 62, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: hfuse changed! Was da, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: efuse changed! Was 7, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: Fuses OK (H:07, E:DA, L:62)

```

I answered yes because in in earlier attempts it just froze.

Now the board is in same condition as the first one.

Is it possible to revive it? Thanks.

# Answer
I am closing this thread.

The board is probably not destroyed, more likely are fused corrupted. There are ways of reviving ATMega328 chip and program fuses back its called high voltage programming. You need to probably unsolder the chip or modify your board (post from tontrack).

Also if you are wondering what to do or not to your Arduino board here is quite interesting page (you wil find it in comment).

I did not found a way how it could have happen but it did.

Anyway Iam done with UsbAsp programmer and ordered AVR pocket programmer. Until it arrives I stop any more attempts.

Hope this helps somebody.
> 0 votes

---
Tags: programming, arduino-pro-mini, usbasp
---


# Question
Title: Upload sketch remotely through a serial-IP-serial connection
I tried different times to use socat and ser2net in order to upload a sketch to an Arduino Uno (connected to a PC) from my laptop, unsuccessfully. Can anyone teach me how to achieve this goal? I use Linux.

# Answer
I've been searching through the net for some days, in order to discover how I could easily upload a sketch to an Arduino that is not phisically connected to my PC, but instead that is connected to an another one, that belongs to the same LAN. I mean:

PC1-SERVER Arduino Uno is connected to this PC with classic USB cable. This PC is running Ubuntu linux, and sees Arduino as a serial port /dev/ttyACM0.

PC2-CLIENT This is the PC where I create and compile the sketch. I want to upload the sketch to the Arduino Uno described above (so, connected to SERVER, port /dev/ttyACM0)

SOLUTION: server-side commands:

Code:

```
sudo apt-get install ssh-server ser2net

sudo passwd root    (to set the root password)

sudo reboot

```

client-side commands (assuming 192.168.0.7 as IP address of SERVER):

Code:

```
ssh -L 8086:localhost:8086 root@192.168.0.7 \
'/usr/sbin/ser2net -d -C "8086:raw:600:/dev/ttyACM0:115200 NONE 1STOPBIT \
8DATABITS -XONXOFF LOCAL -RTSCTS HANGUP_WHEN_DONE "'

```

you can then upload sketches to arduino doing this:

Code:

```
avrdude -C /path/to/avrdude.conf -p atmega328p -c arduino -P net:localhost:8086 -U flash:w:/path/to/file.hex:i

```

NOTE: In Eclipse, if you are using the arduino plugin, just place "net:localhost:8086" in the configuration panel, where "port:" field is required.

This solution was also posted on arduino forum.
> 5 votes

# Answer
You can use an ethernet to ttl adapter and then install a virtual com software.

What i did was the following.

I used an ethernet to 232 converter, and tweaked the board as you can see in the attached photo, I removed the 232 chip and jumpered the ttl directly to the output.

Then I installed USR-VCOM and set a virtual com port that shows in the arduino ide, it works without any software /boot changes

I am not sure how to remote reset the arduino.... Probably someone else knows.
> 2 votes

# Answer
**Basically it would require another bootloader.**

You might want to check this out: http://playground.arduino.cc/Code/TFTPBootloader1

**Programming through serial**

I don't have the intention to advertise a product, but I worked with an Lantronix xport which was able to receive serial information (or a telnet session) over ethernet. You might want to look into cheaper models of other manufacturers (that do not use modem like commands) you should look for ethernet to serial converters. It should be compatible with: http://blog.solutions-cubed.com/programming-the-arduino-uno-with-a-serial-port/

**You might also connect to another PC over ethernet which then programs the arduino**

This would require another PC, but can be fairly easy to set up, but cumbersome to use. You could use teamviewer or another remote desktop. Find a way to send your code (or completely program it at the other pc) and then execute the program command. You might even check if it's possible to use an raspberry PI instead of a full PC (always wanted to try this).

**Use an arduino to program your arduino**

You might use an arduino that receives code and then uploads it to another arduino. Not sure how that works out. Or how to get the code on the first arduino. Should work fine if you've got something like a modificated arduino webserver running.

Also details on programming arduino can be found here: http://www.arduino.cc/en/Tutorial/ArduinoISP
> 0 votes

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


# Question
Title: No power from Breadboard Power Supply Module
## Components

## LED Lights Up Fine with USB power from the Arduino

## LED Does Not Light Up with power from the Supply Module

What am I doing wrong?

* The Lipo battery is brand new and is charged as the terminals showed about 7.6V on my multimeter. This is confirmed by the LED on the supply module itself lighting up fine.
* I think I can smell just a little bit of burn whenever the supply module is connected and there is power in the circuit.
* The positive jumper wire is connected to the 5V VCC pin on the Arduino, not the VIN pin on the Arduino, not that it matters, because if I remove the Arduino from the breadboard the LED still does not light up

# Answer
I'm not surprised you can smell burning. You have the power supply connected backwards.

You see that little + and - symbol next to the ON/OFF jumper? That's the polarity of the two runs of pins. You have the + row connected to the - rail of your breadboard (blue) and the - row connected to the (red) positive rail.

Turn the power supply around 180° and connect it to the other end of the breadboard - the rails will be the other way around then.
> 7 votes

---
Tags: power, led, arduino-nano, battery, lipo
---


title: Arduino - Rural A-GPS Station

text:
# Question
Title: Arduino - Rural A-GPS Station
I'm trying to set up a GPS tracking solution in a rural area. The catch is the GPS trackers need to be lower cost (power and cash), because there will be a good amount of them.

So I'm trying to find a solution where I can benefit from A-GPS using a beacon of some sort to handle any cpu/server calculations while receiving GPS noise from the tracking devices (I think that's the idea). I've read up a bit on Mobile Station Assisted (MSA) GPS, but I'm not entirely sure what solutions there are to handle this.

Any help or advice is appreciated.

Example:

Arduino GPS tracker x 200 ---\[RF comms/GPS noise\]---\> Beacon/Tower ---\[Internet\]---\> GPS Server

# Answer
> 1 votes
I'm not sure I get what you want, but the A7 module of Ai-Thinker is a good GPRS module with GPS in it.

---
Tags: arduino-uno
---


# Question
Title: Weird text when pressing a certain touch button
I have written a code that remaps the 16-Key touch keypad. When 2 key is pressed, it writes weird characters in the serial monitor even on my 16x2 LCD

But the other keys work fine.
Here's the code:

```
#define SCL_PIN 11
#define SDO_PIN 12

struct keymap {
    int     kCode;
    String  kValue;
  };

keymap keys[] = {
  {1, "1"},
  {2, "2"},
  {3, "3"},
  {5, "4"},
  {6, "5"},
  {7, "6"},
  {9, "7"},
  {10,"8"},
  {11,"9"},
  {14,"0"},
  {13,"CLEAR"},
  {15,"ENTER"}
  };

void setup()
{
  Serial.begin(9600);
  pinMode(SCL_PIN, OUTPUT);
  pinMode(SDO_PIN, INPUT);
}

void loop() {
  int Key = Read_Keypad();

  if (Key != 0) {
    for (int x = 0; x < 16; x++) {
      if (Key == keys[x].kCode) {
        Serial.println(keys[x].kValue);
      }
    }

    delay(300);
  }
}

byte Read_Keypad(void)
{
  byte Count;
  byte Key_State = 0;

  for (Count = 1; Count <= 16; Count++)
  {
    digitalWrite(SCL_PIN, LOW);
    if (!digitalRead(SDO_PIN))
      Key_State = Count;
    digitalWrite(SCL_PIN, HIGH);
  }
  return Key_State;
}

```

# Answer
It seems by changing `16` to `12` on

```
for (int x = 0; x < 12; x++) {
      if (Key == keys[x].kCode) {
        lcd.print(keys[x].kValue);
      }
}

```

fixed it.
> 1 votes

---
Tags: arduino-nano
---


# Question
Title: FlySky TH9X with Arduino: cant get pulseIn() function to return sensible values for any channel
So I've got a FlySky TH9X and I'm trying to read some pulses using an Arduino Uno.

I'm just starting out so I want to get the hang of using the pulseIn function before moving onto interrupts. My problem is that, when I wire everything up, I don't get sensible values. Furthermore, they don't change even though I move around the sticks on the actual remote.

I tried to start off simple by wiring just the channel 1 of the receiver to pin 3 of the Uno. Then I used this code:

```
int ch1;

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

void loop() {
  ch1 = pulseIn(3, HIGH, 25000);
  Serial.print("Channel 1: ");
  Serial.println(ch1);
  delay(100);
}

```

The serial monitor then spits out numbers ranging from 0 up to 10000+ in a very erratic and apparently not periodic nature. I'll copy a few lines here:

```
Channel 1: 9989
Channel 1: 10063
Channel 1: 10068
Channel 1: 274
Channel 1: 0
Channel 1: 10085
Channel 1: 10039
Channel 1: 10336
Channel 1: 9629
Channel 1: 9959
Channel 1: 10064
Channel 1: 10088
Channel 1: 378
Channel 1: 0
Channel 1: 10044
Channel 1: 10059
Channel 1: 10424
Channel 1: 9632
Channel 1: 9867
Channel 1: 10069
Channel 1: 10067
Channel 1: 10473
Channel 1: 10037
Channel 1: 10063
Channel 1: 10063
Channel 1: 10253
Channel 1: 9677
Channel 1: 10013
Channel 1: 10064
Channel 1: 10062
Channel 1: 13

```

As you can see: not only are the higher-end values a whole order of magnitude too big (i thought pulses are normally between 1000 - 2000us?), but the actual range that these numbers span is far, far too wide for me to do anything with. Also, the sticks on my remote seem to have no influence on the numbers.

Can someone please help me? thank you :)

Hassan

# Answer
> 1 votes
I would not recommend using `pulseIn` for reading values from the receiver. `pulseIn` blocks the program until a signal is received, which is almost always undesirable.

An alternative approach would be to use CHANGE interrupts. You get an interrupt when the signal goes high and low. You take note of the time that each change occurs with `millis` and compare the times to get the duration of the signal.

Here's an example - you can add more channels if you'd like. Note, this is using the EnableInterrupt library.

```
#include <EnableInterrupt.h>

#define SERIAL_PORT_SPEED 57600
#define RC_NUM_CHANNELS  2

#define RC_CH1  0
#define RC_CH2  1
#define RC_CH1_INPUT  A0
#define RC_CH2_INPUT  A1

uint32_t last_update_time = 0;
uint16_t rc_values[RC_NUM_CHANNELS];
uint32_t rc_start[RC_NUM_CHANNELS];
volatile uint16_t rc_shared[RC_NUM_CHANNELS];

void rc_read_values() {
  // read the values out of the shared, volatile array (which can change at any time)
  // and into an array that we only will only change when we call this function

  noInterrupts();
  memcpy(rc_values, (const void *)rc_shared, sizeof(rc_shared));
  interrupts();
}

void calc_input(uint8_t channel, uint8_t input_pin) {
  // This is the interrupt.  If the pin is high, we record the start
  // time of the pulse.  If the pin is low, we compare the start time
  // to the current time in order to get the length of the pulse.

  if (digitalRead(input_pin) == HIGH) {
    rc_start[channel] = micros();
  } else {
    uint16_t rc_compare = (uint16_t)(micros() - rc_start[channel]);
    rc_shared[channel] = rc_compare;
  }
}

void calc_ch1() { calc_input(RC_CH1, RC_CH1_INPUT); }
void calc_ch2() { calc_input(RC_CH2, RC_CH2_INPUT); }

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

  pinMode(RC_CH1_INPUT, INPUT);
  pinMode(RC_CH2_INPUT, INPUT);

  // set up CHANGE interrupts, so that we get notified when
  // each signal goes high or low.
  enableInterrupt(RC_CH1_INPUT, calc_ch1, CHANGE);
  enableInterrupt(RC_CH2_INPUT, calc_ch2, CHANGE);
}

void loop() {
  rc_read_values();

  Serial.print("CH1:"); Serial.println(rc_values[RC_CH1]);
  Serial.print("CH2:"); Serial.println(rc_values[RC_CH2]);

  delay(200);  // just so serial log doesn't flood
}

```

For a more detailed explanation, take a look here: http://rcarduino.blogspot.com/2012/01/how-to-read-rc-receiver-with.html

# Answer
> 0 votes
Use a bigger timeout (30000):

```
int rcPin1 = 3; // PWM signal arduino pin
int rcPin2 = 4; // PWM signal arduino pin
int rcPin3 = 5; // PWM signal arduino pin
int rcPin4 = 6; // PWM signal arduino pin
int rcPin5 = 7; // PWM signal arduino pin
int rcPin6 = 8; // PWM signal arduino pin
int ch1 = 0;    // Receiver channel 1 pwm value
int ch2 = 0;    // Receiver channel 1 pwm value
int ch3 = 0;    // Receiver channel 1 pwm value
int ch4 = 0;    // Receiver channel 1 pwm value
int ch5 = 0;    // Receiver channel 1 pwm value
int ch6 = 0;    // Receiver channel 1 pwm value
void setup() {
  pinMode(rcPin1, INPUT);
  pinMode(rcPin2, INPUT);
  pinMode(rcPin3, INPUT);
  pinMode(rcPin4, INPUT);
  pinMode(rcPin5, INPUT);
  pinMode(rcPin6, INPUT);
  Serial.begin(9600);
}

void loop() {
  // Read in the length of the signal in microseconds
  ch1 = pulseIn(rcPin1, HIGH, 30000);
  Serial.print("Channel #1: ");
  Serial.println(ch1);
  ch2 = pulseIn(rcPin2, HIGH, 30000);
  Serial.print("Channel #2: ");
  Serial.println(ch2);
  ch3 = pulseIn(rcPin3, HIGH, 30000);
  Serial.print("Channel #3: ");
  Serial.println(ch3);
  ch4 = pulseIn(rcPin4, HIGH, 30000);
  Serial.print("Channel #4: ");
  Serial.println(ch4);
 ch5 = pulseIn(rcPin5, HIGH, 30000);
  Serial.print("Channel #5: ");
  Serial.println(ch5);
  ch6 = pulseIn(rcPin6, HIGH, 30000);
  Serial.print("Channel #6: ");
  Serial.println(ch6);
 delay(1000);
}

```

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


# Question
Title: How can I connect H-Bridge motor driver (using four 2n222 transistors) to Arduino?
First of all I'm a noob.

I was trying to do the H-Bridge using 2N2222 controlled by an Arduino Uno.

This is the design---\>

I joined A1 and A2 to form a common terminal (say A), similarly, I joined B1 and B2 to form B. Now I connected A and B to 2 pins of the arduino (say pin 9 & pin 10 respectively).

So, theoretically, when I should digitalWrite pin 9 HIGH, then current should flow via A1 and A2, i.e. left to right in the motor AND when I should digitalWrite pin 10 HIGH, then current should flow via B1 and B2, i.e. right to left in the motor.

Hence, I can control the direction of rotation of the motor.

BUT.....it wasn't working...!!!!

I need help...!!!

After much thinking I had a hunch...."Perhaps, I am not giving GROUND to the transistors". I thought about it, but was unable to figure out the way of doing it.

So, again, please help me...!!!

# Answer
I am not an electronics guru yet either so others might give you a better answer, but this is one circuit I have messed with a lot because I keep trying to build robots, so I will take a shot at an answer.

Normally you need both NPN and PNP transistors for an H-bridge:

The 2N222 is NPN so you'd want to pair two of them with two equivalent PNPs such as the 2N2907.

I've see diagrams that have all NPNs but I have never gotten a circuit to work that way. There is a distinction about where the load goes, before or after the transistor, that makes you chose to use an NPN or a PNP in order to make it all flow properly.
> 1 votes

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