# Question
Title: keypad code is not working and produces wrong numbers
I have the following issues:

1) When i press for example number 7 on the keypad it shows a different number on the serial monitor 2) The servo motor works for any combination of 4 numbers.

Code: /\*http://openhwdesign.comLock system using a Keypad \*/

```
#include <Password.h>
#include <Keypad.h>
#include <Servo.h>
#pragma GCC diagnostic ignored "-Wwrite-strings"
Servo myservo; //declare servo
Password password = Password( "5523" );

const byte ROWS = 4; // declare the rows of the keypad
const byte COLS = 3; // declare the columns of the keypad

// Define the Keymap

char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};

byte rowPins[ROWS] = {2,3,4,5}; // Connect keypad’s pins to these Arduino pins.
byte colPins[COLS] = {6,7,8}; // Connect keypad’s pins to these Arduino pins.

// Create the KeyPad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup(){
Serial.begin(9600);
myservo.write(0);
pinMode(11, OUTPUT); //The green led is set as an output.
pinMode(12, OUTPUT); //The red led is set as an output.
myservo.attach(13); //The servo is connected to the digital pin 13.
keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad

}

void loop(){
keypad.getKey();
myservo.write(180); //why? what happens if you comment it? ###########################
//delay(5);
}

void keypadEvent(KeypadEvent eKey){
// When the KeyPad will be pressed, the results will appear on the serial monitor.
switch (keypad.getState()){
case PRESSED:
Serial.print("Enter: ");
Serial.println(eKey);
delay(10);

switch (eKey){
case '*':
checkPassword(); // Will check the password.
delay(1); // Delay used for stability.
break;

case '#':
password.reset(); //Will reset the password
delay(1); // Delay used for stability.
break;

default:
password.append(eKey); //Append any keypress that is not a ‘#’ nor a ‘*’.
delay(1);
}
}
}
void checkPassword(){

if (password.evaluate()){ //If the combination inserted is equal to the combination saved, the servo’ll rotate.
Serial.println("Accepted");
//delay(5000);
delay(10);
myservo.write(50); //was 140
delay(5000);

digitalWrite(11, HIGH); //Turn the green led on.
delay(500); //Wait 5 seconds.
digitalWrite(11, LOW); //Turn the green led off.

//break; // remove if trial did not work #####################try#####################
}
//break; // remove if trial did not work ##########################################
else{ //If the combination inserted isn’t equal to the combination saved, the servo will not rotate.
//delay(5000); delays response
Serial.println("denied");
delay(10);
//delay(5000);
myservo.write(20); // was 50
digitalWrite(12, HIGH); //Turn the green led on.
delay(5000); //Wait 5 seconds. was 500 ///
digitalWrite(12, LOW); //Turn the green led off.

    }
}

```

Thank you.

# Answer
The first thing you need to do is just look at what the problem is. Create a new sketch and paste this code into it.

```
#include <Keypad.h>

const byte ROWS = 4; // declare the rows of the keypad
const byte COLS = 3; // declare the columns of the keypad

// Define the Keymap
char keys[ROWS][COLS] =
{
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
};

byte rowPins[ROWS] = {2,3,4,5}; // Connect keypad’s pins to these Arduino pins.
byte colPins[COLS] = {6,7,8};   // Connect keypad’s pins to these Arduino pins.

// Create the KeyPad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void keypadEvent(KeypadEvent eKey)
{
    // When the KeyPad will be pressed, the results will appear on the serial monitor.
    switch (keypad.getState())
    {
    case PRESSED:
        Serial.print("Enter: ");
        Serial.println(eKey);
        delay(10);
        break;
    }
}

void setup()
{
    Serial.begin(9600);
    keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad
}

void loop()
{
    keypad.getKey();
    delay(20);
}

```

You should recognise it, its a reformatted version of your code (pretty code is easier to debug), but with only the keypad bits in.

Now load that onto your hardware and write down what number is shown when you press 1 three times. Do it three times just to make sure its the same number and you haven't got something totally obscure happening. Repeat for the other 11 buttons.

If 7 and 3 always give you 3 and 6 then you have got your row and column wires crossed. If 7 always gives you 1 and 9 always gives you 3 then the wires for row 4 and 2 are crossed over. etc If you can't work out the patter post your findings and I'm sure someone will solve the puzzle.

As for problem 2, don't even go there until you know what you are typing. :)

Hope that helps
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How does changing arduino power supply from USB to Adapter change the circuit?
I have a circuit running with capacitive Sensors, that also has an LED strip. everything works fine when using USB power from a laptop (connected to the mains) and 12v 2A adapter powering 1m LED strip.

When the power supply is split and the arduino is also powered from this supply ( using adapter port ) the capacitive sensor begins to give junk values.

What changes in a circuit that would create such a porblem? Could it be a grounding issue? How else to ground this arduino to behave as it would with a usb connection?

# Answer
> 2 votes
I have run into problems like this before, often it can actually be that the voltage is not steady due to the LEDs sourcing current from it.

You may be able to solve the problem by adding a capacitor inline with the power input (from the +12v to GND). I would probably start with a value of around 10 μF and increase it if the interference continues.

Capacitive sensors and very sensitive to voltage fluctuations, you may even want to put a second capacitor across the VCC and Gnd of the sensor.

# Answer
> 1 votes
Some of the capacitive sensors need a seperate regulated power supply.You can look into the data sheet of the capacitive sensor.Maybe you can try with the same. I just read the datasheet of At42qt2120 cap sensor.

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


# Question
Title: Arduino to send sms one time only when a button is pressed
The **LED\_UPDATE()** is called in my **loop()** function, I implemented it (tried anyways), to send sms as shown in the code such that only one sms is sent , because as the **loop()** keeps calling **LED\_UPDATE()**, it's going to keep sending an sms every time (yep you guessed it, very bad for credit :o )

any tips on how I can get around this or what i'm doing wrong in my code would be much appreciated.

**p.s.** nearly left my mobile phone in the code lol

```
void LED_UPDATE(int state)
{

int count; // initialized to zero, once program runs it automatically enter state ==1
if (state == 1)
{

    digitalWrite(RED_PIN, LOW);
    digitalWrite(GREEN_PIN, HIGH);
    count=0;
}
else if (state == 2)
{
  count+=1;
  Red_Blink();

  if(count == 1 )
  {
    sms.SendSMS("086XXXXXXX", "PANIC BUTTON PRESSED, Subject needs help!!!");
  }

}

```

# Answer
You are resetting `count` every time you enter the function.

```
static int count; // initialized to zero, once.

```

Adding the static statement should initialise the variable once and preserve its value between calls.
> 0 votes

---
Tags: wires, gsm
---


# Question
Title: What do I need to make fluffy toys move and talk?
My kids got many fluffy toys, and I would like to make them move and talk. Something like a small platform with wheels and a speaker and some sensors that I would be able to mount any of the toys on.

I'd like to build something like 2 platforms with motors and sensors that move around, and when encountering obstacles "bark" at them through the speakers, wait random number of seconds, and move in different directions. Then the kids would mount their favorite fluffy dogs/cats/bears/rabbits on top of these platforms and unleash them on each other.

I am very new to DIY; what do I need to buy for such a project?

# Answer
You will need a processor board, motor driver, sensors, and audio amplifier.

Since you are asking on the Arduino forum, it would be natural to consider one of the Arduino boards or derivates - but beware they tend to be rather antiquated compared to alternatives now available. The plus side of the classic ATmega boards is the wide variety of read-to-go example code available right within the IDE, and the wide supply voltage range (of the bare chips if not the boards) which is more compatible with AA-cell battery packs than competing device's narrower voltage range tends to be. The one part of the functionality you describe that is a bit of an issue is the audio output - you can get it from an ATmega but it will be poor in quality and you will need to add storage for the "bark" data. You might almost consider a separate module with an ATtiny and a small SD card for that (ironically the ATtiny while generally less capable has fast PWM better suited to audio).

For motor drivers, especially when using batteries steer clear of the older bipolar L293/L298 type of solutions, as these have very high internal loss which basically means that one cell in your battery pack exists just to generate heat in the driver IC. A modern FET based driver (the TB6612FNG is quite popular) will be better.

For sensors you probably want one or more of microswitches extended with "whiskers", ultrasonic rangefinders, or short range IR reflectance.

Some dual wheel drive (or "tank steering") RC toys can be worth considering as platforms, but their gearing may be too fast for your purposes, particularly those designed to spin and tumble. Continuous rotation servos are sometimes mentioned, but it can be hard to get them tuned to not rotate when commanded to stop, and mounting wheels can be tricky. The small plastic gearboxes work well if you can get matching wheels but are hard themselves to mount. Access to a 3d printer can be quite useful for creating missing physical components, though a block of wood and a router can make a nice chassis, too. You can also buy ready made Arduino robot base kits with chassis, gearboxes, and wheels.

For audio output, you can accomplish something with an NPN transistor and base resistor driving a speaker, but best results would be with a small class D driver board as are now widely sold for a few dollars. They tend to be stereo, but you can feed both sides with the same signal. If you only wanted "robot beeps" you can drive a piezo disk directly from a processor pin with reasonable loudness at higher frequencies, but the low frequency response is quite poor.
> 2 votes

# Answer
## **Don't do it.**

When you say to us:

> I am very new to DIY; what do I need to buy for such a project?

Then you really aren't ready yet. Sometimes a virtuoso or savant exists, and they can make incredible DIY projects, but for most people, jumping into such an aggressive project as your first DIY is a recipe for disaster.

I'm not trying to be a smart-ass or negative, but you should get an Arduino and try some PROTOTYPING first. Again, not trying to be a smart-ass, but if you even have to ask this question, then you really aren't ready yet.

When I work with people on their first project, you should see how excited they get when they can get a light to blink (I still get excited each time too)!

I think you should go for more of a "karate kid" approach: Wax the car, paint the fence, sand the floor. Once you know the fundamentals, you'll be a ninja before you know it.

I could list a pile of "fundamentals" here, but any other guide would be more comprehensive than my Arduino karate kid list.
> 2 votes

---
Tags: motor, sound
---


# Question
Title: Using a L2938D Motor Driver Module. (Not IC, Module)
I have been trying to use my newly bought L293d Motor Driver Module to run motors(a single motor in this test case, simple 5V toy motor) from my Arduino UNO. Thing is, this is an entire module, not just the IC (in which case there are many tutorials available). So I was following this tutorial to try and get my motor running.

Here is the tutorial - http://www.instructables.com/id/Arduino-and-L293D-Robot-Part-1-/?ALLSTEPS
Here's what the module looks like -

There are 6 Pins on the module, which bring out the 6 inputs, EN1, EN2, IN1, IN2, IN3, IN4. Now since I am using only one motor, I connected my motor to the OUTPUT 1 & 2 header given on the module. I then take the 5V and GND from Arduino and connect them to my Module's 5V and GND header, (leaving the 12V one empty), I thought that this would be enough as my motor is also of 5V.
I then connected the IN1 and IN2 to the pins 7 & 8 on my Arduino and used the following code-

```
// Simple code to make the motor turn
int RightMotorForward = 7;
int RightMotorReverse = 8;

void setup()
{
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorReverse, OUTPUT);
}

void loop()

{
   digitalWrite(RightMotorForward, HIGH);
   delay(10000);

   digitalWrite(RightMotorForward,LOW);
   delay(1000);
}

```

Nothing happened. The motor didn't work and I have no idea why. I've gone through the entire datasheet for L293D but I found nothing that could help me. I suspect that it has something to do with the EN1 pin, but I don't really know how to use it, the tutorial said to connect it to 5V, which I tried but no results. So where am I making the mistake? How do I get this to work?

# Answer
> 0 votes
ooops. That **5V** you are applying to **5V pin** is actually an output pin.

You must apply some input voltage at the **12V** & **GND** inputs.

Don't forget to remove that **5V** connection to **5V pin**

# Answer
> 0 votes
While no one can tell you exactly how to connect that board without having its documentation or the board in hand to examine visually or with an ohm-meter, it is quite likely that by leaving the "12v" terminal unconnected, no power is being provided to the motor side of the circuit.

It kind of looks like there is a voltage regulator on board, so it may be that it will even provide 5v on that terminal when given something 7 volts (or so) or higher on the "12v" terminal - again, we cannot know without details of your exact board.

The L293 is an old and low-performing chip, with internal losses that mean that to achieve 5 volts across a motor, you will need to supply very nearly 7 volts to the chip. The difference gets wasted as heat.

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


# Question
Title: Adafruit Flora V2 use onboard and external NeoPixels
I am working on wearable project using an Adafruit Flora V2, and for this project I need to use the onboard NeoPixel. I also need to use Neopixels that are attached to the D6 pin (is it a pin?). I have a line at the beginning of my program that says `#define PIN 6`. I found that I can use the onboard NeoPixel by changing this to `#define PIN 8`. Is there a way to use the onboard NeoPixel **and** the ones attached to D6. I already have everything wired up, and the rest of my program is written, I just need to use both pins. Thanks for any possible help.

# Answer
The #define is just letting you use a nice name for the numeric value of the pin. If you want to use two different pins, you use two different names.

So you might define them at the beginning something like:

```
#define BOARDLED 8
#define STRIPLED 6

```

Then you create a NeoPixel object that uses that pin. In your case, you'll do this twice.

```
Adafruit_NeoPixel flora_led = Adafruit_NeoPixel(60, BOARDLED, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, STRIPLED, NEO_GRB + NEO_KHZ800);

```

And then you call the one you want to set/modify/show/etc.

```
strip.show();
flora_led.show();

```
> 2 votes

---
Tags: programming, pins, adafruit, neopixel
---


# Question
Title: Retrieve value from ThingSpeak using ESP8266 with Arduino setup
I just started learning ESP8266 and in my first project I am successfully able to send data to ThingSpeak.com using ESP8266 with following code:

```
uploadData() {
  String apiKey = "ESDS8678890SDDS";
  String myData = "45.5"; // example of data to send
  if (espClient.connect(server,80)) {
    String postStr = apiKey;
    postStr +="&field1=";
    postStr += String(myData);
    postStr += "\r\n\r\n";
    espClient.print("POST /update HTTP/1.1\n");
    espClient.print("Host: api.thingspeak.com\n");
    espClient.print("Connection: close\n");
    espClient.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
    espClient.print("Content-Type: application/x-www-form-urlencoded\n");
    espClient.print("Content-Length: ");
    espClient.print(postStr.length());
    espClient.print("\n\n");
    espClient.print(postStr);
    Serial.print(postStr);
    Serial.print("My Data: ");
    Serial.print(myData);
    Serial.print("\n");
  }
  espClient.stop();
}

```

But I have no idea how to retrieve data from ThingSpeak using ESP8266.

```
// Using XXXXX here as my channel is private
GET https://api.thingspeak.com/channels/XXXXXX/fields/1.json?results=2

```

I think I have to use the above GET string to get the fields data. But I don't know how to create the request string.

Help would be appreciated.

Thanks.

# Answer
Connect to the server as usual with `espClient.connect()`. The following request should return a JSON object containing your channel description and the first 2 entries in your feed:

```
espClient.println("GET /channels/CHANNEL_ID/feeds.json?results=2 HTTP/1.1");
espClient.println("Host: api.thingspeak.com");
espClient.println("Connection: close");
espClient.println();

```

If it's a private channel, then you must supply your Read API key like this:

```
espClient.println("GET /channels/CHANNEL_ID/feeds.json?api_key=<your API key>&results=2 HTTP/1.1");

```

Notice that I use `println()` and not `print()` in order to implicitly terminate each request line properly. You should end each line not with `\n` but with **`\r\n`**. You only need to type this yourself if you use `print()`.

To read the returned JSON data:

```
while (espClient.available() == 0);  // wait till something comes in; you may want to add a timeout here

unsigned long lastRead = millis();  // keeps track of last time a byte was read
while (millis() - lastRead < 2000) {  // while 2 secs havent passed since a byte was read
  while (espClient.available()) {
    Serial.print(espClient.read());
    lastRead = millis();   // update last time something was read
  }
}
client.stop();  // close socket

```

To parse the JSON string, you either get a library from GitHub or you parse the string yourself.
> 1 votes

---
Tags: esp8266
---


# Question
Title: Help compiling multiple .ino file code with code! (I'm not sure what to name this)
Ok, so i'm trying to make This Project and the code comes all in different .ino files but in the video its all in one program. So how do I compile all of the code onto the arduino? (By the way the code is on step 5 in a .zip file) Thank you!

# Answer
> 0 votes
One of the .ino files is likely the main code file. Name the enclosing folder with the name of the .ino file, then compile it as normal.

In this case, AbHhGD.ino is the main file, and its folder should be named 'AbHhGD'

The comments indicate there are missing libraries you likely need to install.

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


title: Reset as I/O pin

text:
# Question
Title: Reset as I/O pin
I'm looking to minimise the parts count and the power consumption as much as possible and I was wondering if is it possible to store a variable or execute a method when the 'reset' button is pressed?

I didn't find any docs or hints regarding this.

In theory, can it be done with an interrupt?

### Edit

In a further research Atmel shows, that if you burn the 'RSTDISBL' fuse (still in theory for me) you can get hold of the reset button by transforming it in a I/O pin with "special" electric characteristics:

Also, if you look at the schematic the reset pin shows that it has what it needs to be an I/O pin:

I say in theory because I really don't know if arduino has the required constellation for this capability and if it comes whit the fuses already burned.

# Answer
Yes, there are several possibilities here.

One is detecting state after reset and acting on it. One of the reasons you might do that would be to shut the processor down all but completely, and let the reset wake it back up.

Another would be to program the reset disable fuse and repurpose it as an I/O pin - of course if you do that, you can only then reprogram the chip if you have implement working functionality to get back to the bootloader (or similar), or if you use a high voltage programmer.

These are in the category of things which make development a lot more difficult, but are sometimes worthwhile as they let you squeeze a little more capability out of the hardware. If you are just starting a design, you might consider a different chip instead - but if you have existing boards or design investment, and this lets you get the last little bit of needed capability from it, it is possible.
> 1 votes

---
Tags: arduino-ide, interrupt, reset
---


# Question
Title: Converting RGB from color sensor into the Munsell Color System
I am hoping I could get some help developing a an idea I have for archaeologists/soil scientists using an arduino and the TCS3200 colour sensor. The idea I have is a simple device which can determine munsell colours with more accuracy and speed. The current conventional method is to use colour chips/swatches found in the Munsell system booklet and match them as close to examples of sediment/soil found at archaeological sites. The problem with doing this method is that it is highly subjective, and time consuming.

My idea is to use the Adafruit TCS34725 to read and detect the RGB colour of the sediment (in the RBG colour space) and convert the data into the Munsell System. I have all the data of what RGB ratio corresponds to each Munsell colour -- which I have downloaded from this site: www.cis.rit.edu/research/mcsl2/online/real\_sRGB.xls

My problem is that when I use the sketch provided, I can not figure out how to use the "if" statement to "Serial.print" what the munsell colour corresponds to the RGB colour detected by the sensor.

My ultimate goal is to modify the colour view sketch here see: colorview I would like to keep the everything provided but change two things, I would like to convert RGB into Munsell using the data provided by the RIT link and also add a screen and button to start the read process and display the colour.

If some one would be willing to help me that would be great!,

# Answer
> 1 votes
I have some thoughts on your task. First of all colorimetry is a science on its own. I know people working in this field for decades with equipment costing many millions of €. They all share some basic wise words. One is: "Because we all see colours we think measuring colous is an easy task. The opposite is true. Many of the best colorimetrists are colour blind." One second is: "Without light there is no colour". I will write on this later.

Colorimetry in fact is a complex matter. Between a colored piece of stone and a numerical value normally lie a lot of transformations and convolutions. And inbetween there are also lurking many error sources.

This said, I'm sure it will be possible to produce somewhat acceptable results with your sensor. Provided you do a proper calibration and add a calibratable light source.

Speaking of light source. A piece of stone can only reflect incident light (except some uranium/radium salts, you don't want to deal with). Pigments are basically LTI-systems (aka passive filters). This means they can only reflect wavelengths which are present in the incident light. And the will reflect a well defined and individual proportion of each wavelength regardless the luminous flux of the incident light. This means, if your incident light contains nearly no blue light then the stone or whatever you want to examine will reflect only the fraction of "nearly no light" it typically does reflect of any amount of blue light.

So the remission spectra of all pigments get shaped (multiplied) by the spectrum of the incident light. Your sensor sees only the reflected light and therefore will give totally different results for one and the same object depending on the incident light. Look up the spectra for daylight and incandescent light and think about the results of your sensor.

To make a long story short, you can only yield reproducable measurements if you supply your own light source along with the sensor. This is in fact the way all colour meters work. The only other way was to measure the full spectrum of the incident light. Reasonable portable spectroradiometers for this purpose cost 5000 €. So it's better to go for a light source :).

As they are rather affordable I recommend using LEDs to make up a light source for examination. But LEDs suffer from several drawbacks. They tend to change their output spectrum with their chip temperature and ageing processes. So you have to supply a proper calibration procedure for your measuring equipment. And you better do the calibration sequence before every measurement.

You then have to design an apparatus which allows the light from your LED fall onto your samples (stones, sediments or so) but prevents other scattered or direct light to enter your sensor. Otherwise all measurements will be crap.

While this is not a direct answer to your question, I think the topic is important enough to write an elaborate pamphlet.

**Update**

Now some more words more closely related to your problem.

In general loading a huge excel table into your arduino is not necessarily a good idea, even if a big "if"-code array was possible. Storage is scarce on this platform.

If you combine a lookup table with interpolation, you can save much space. You would have to omit 90% of all datapoints and estimate all in between when measuring. Still the table will be rather big, because you have three degrees of freedom.

Another drawback of big tables and LUT with interpolation is, that it makes calibration difficult. Normally, when you calibrate your sensor, you have to adjust the parameters along the calculation. If you rely on a table, you have to exchange the whole table, regardless if it is something like that excel thingy or a condensed lookup table.

If you go for an analytical solution, as suggested in one comment, the number of parameters you have to update after calibration reduces drastically. Effectively you have to adjust some factors and offsets in the equations for this problem. Of course you will have to learn the ropes of the photometric equations, but you will have to do that anyway, I think.

Some more words on the design of your appartus. Your idea of a cylinder in front of your probe is good. I recommend to fit it with a rim of black foam rubber, so you can seal light coming from outside. And you have to paint the inside of your cylinder as black as you can. See the interiour of a camera objective for reference.

If it is white you will have multiple reflections and multiple filtering which deteriorates your measurement results vastly.

---
Tags: sensors, rgb-led
---


# Question
Title: Arduino IDE get stuck while uploading sketch
I was trying to use my L293D motor driver module. But when I upload the following sketch to try and run my motor, but it would get stuck on "Uploading". This happens with this sketch only, and happens randomly, with odds of happening being 3 in 5 times. After a bit fiddling around I found an error

> Programmer is not responding.

When I try to reset the board or just reconnect it to my PC it might work.
Here's the sketch-

```
int RightMotorForward = 12;
int RightMotorReverse = 13;

void setup()
{
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorReverse, OUTPUT);
}

void loop()

{
   digitalWrite(RightMotorForward, HIGH);
   delay(10000);

   digitalWrite(RightMotorForward,LOW);
   delay(1000);
}

```

Can anybody point out where I am going wrong? I am using Arduino UNO. Is this just some problem in my code?

# Answer
Found the solution... Just connect the 5v from arduino to the 5v on the Module. Then another battery (12-36 V, I tried a 9v one... it worked but only for about 40 seconds), to the 12 V input, keeping the ground common... That's gonna make the motors run!
> 0 votes

# Answer
Is the motor driver connected to the Arduino while you program it?

When the Arduino is reset, the output pins on the Arduino are driven high. If too much current is drawn though any of these pins, then the voltage supply to the ATMega328 may drop, and the ATMega328 gets stuck in a brownout.
> 0 votes

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


# Question
Title: How can I connect an 8-relay board without using 8 digital pins?
I'm looking to connect an 8-relay board to an Arduino Uno. A board like this one. However, I don't really want to use up 8 digital outputs if I don't have to. Is there some intermediate circuitry I can either buy or build that would do this?

For example, can I connect something to the serial so that sending '3' would result in binary 00000011 and thus turn on relay's 1 and 2?

Alternately, and probably more lazy, is there an extension board that would just give me a pile more digital pins?

# Answer
> 1 votes
A likely solution is to use the Arduino SPI interface and the Arduino SPI library to control a SPI relay board. Here is a 6 year old thread talking about such a board. And another more recent relay thread where SPI is brought up.

# Answer
> 0 votes
There are ICs that provide additional I/O ports through either the SPI or I2C busses, such as MCP23017 or MCP23018 or their 8 port equivalents. There are many different makes, search Google for "Arduino addition IO Pins"

# Answer
> -1 votes
You can use a MUX/DEMUX. Check out the link. Basically, you can select the output pin by a series of commands that you can do with the Arduino. The relay inputs will be hooked up to the IC's outputs

https://www.sparkfun.com/datasheets/IC/cd74hc4067.pdf

---
Tags: relay
---


title: Arduino uno and ttl laser

text:
# Question
Title: Arduino uno and ttl laser
I am using my uno with gshield for my cnc. I would like to put laser on it. Laser have 3 wires. Red wire to power supply +, Black wire to power supply -, White wire to Arduino digital pin. I need to Connect the Arduino board ground to power supply -, but don't know how... Simple diagram (like child is using painter) would be great.

Thanks for help, Urban

# Answer
> 1 votes
You take a wire, connect one end to the ground on the Arduino board and the other end to the ground on your power supply. Don't forget to strip the insulation. It doesn't get simpler than that.

---
Tags: arduino-uno, power, wires
---


title: Arduino digital I/O pins

text:
# Question
Title: Arduino digital I/O pins
I heard that using digital io pins in INPUT\_PULLUP mode is much reliable and stable than in the case of using them in INPUT MODE.Then why is INPUT MODE still used...I mean **Why isn't INPUT\_PULLUP mode put as default** ??

# Answer
> 2 votes
When the internal pullups are activated, a small amount of current is *sourced* by the pin's circuitry whenever the input is low.

That means that to drive the signal low, an external driver must not only sink current to discharge the capacitance of the internal and external circuitry, but it must continue doing so to dominate the attempt of the internal pullup to make the line high so that the voltage of the resistive voltage divider formed by the internal and external resistors is low enough to be an unambiguous low.

This means that the external circuit must be stronger - not normally a problem for an active device, but potentially an issue for monitoring some very high impedance external circuit. So for example, if you wanted an external pull-down resistor, it would have to be substantially lower in value than the internal pull-up.

It also makes low power design (long life on batteries) difficult, as a system cannot take advantage of the best micropower suspend modes when any signal is being asserted *against* the direction of a pulling resistor. With just one or two such cases you might still get reasonable life when using flashlight batteries, but not with a coin cell, something a well designed ATmega circuit can presently do.

After seeing Igor's comment, and re-reading your post, it seems maybe you are asking why the default is to have them disabled, rather than why you have the ability enable/disable them at all. Most likely, the reason the Arduino core software has them disabled by default is because the ATmega resets that way. As to why the ATmega resets that way, you might have to ask the design engineers, but generally it has been the norm to have an MCU reset to a state where it has the least influence on the external circuitry. However, that is not necessarily the best - floating (undriven) inputs can potentially cause a typical CMOS input structure to consume more power than ones weakly driven to a known value.

---
Tags: pins, input
---


# Question
Title: Create own apache web server on Arduino Uno... just like you can on a raspberry pi?
I was wondering if I could create my own apache web server on my Arduino Uno, just like I did on my raspberry pi - https://www.raspberrypi.org/documentation/remote-access/web-server/apache.md

Anyone have any idea about this? From my research it seems like I cant achieve the same results on an arduino uno.

Thanks

# Answer
You can only make a very, very, very basic webserver, that won't be able to handle more than a few requests per second.

You also need to add something like an ethernet shield, and probably an SD card reader. Which would make it about the same price as a Pi.

It's possible, but very limited, not practical in most cases, and not that much cheaper.
> 1 votes

# Answer
I do recall someone actually managing to run Linux on an Arduino. It was quite impressive, involving a very large amount of external DDR RAM and bit-banging the interface to it. Basically emulating a virtual computer within the Arduino. I can't find the original post though - it's been lost in time...

So yes, technically it is possible to run Linux, and thus Apache, on an Arduino.

Is it recommended to even think about trying to do something like this though?

Certainly not.

The Arduino is a microcontroller, not a computer. It is designed for controlling things (hence its name) not for general computing tasks.

It can, though, run its own web server software - that is, you can connect some form of network interface (Ethernet, WiFI, etc) and implement a very very basic web server. It can't really do much, and all interactivity has to be hard coded into it in C++. There doesn't (yet) exist any simple scripting engine or anything like that (PHP, etc) and you are very limited on how much you can implement (lack of memory) as regards anything fancy.

In general a web server running on an Arduino is used as a back-end to a proper web server and interacted with using Ajax calls or other similar methods. More commonly though a web interface is shunned in favour of much lighter weight protocols or *push* technologies like MQTT.
> 1 votes

# Answer
No you can't. Apache (or any web server of similar functionality) will require:

* tens to hundreds of megabytes of RAM
* about 50 megabytes of storage
* an actual operating system

Perhaps you can get the required storage with the SD shield, but it's practically impossible to get enough RAM or run a suitable OS on arduino.
> 0 votes

# Answer
Yes, you can make a web server. Here is the tutorial.

You do not need Apache to create a web server.
> 0 votes

# Answer
While you can't make an apache web server with an Arduino Uno, you can if you access the linux module of the Arduino Yun board. I in fact did this and with some testing realized that it can't handle more than a few packet requests per second. Although a raspberry pi is much cheaper and more capable than a re-programmed Yun if you want a "Mainstream" server (Namely one Arduino Yun is $75.00 while a Raspberry Pi model 3 B is $35.00 at the time of this writing.)
> 0 votes

---
Tags: arduino-uno, web-server
---


# Question
Title: How to Change the Output Resolution of Sine Wave Controller
I have code that receives values from a serial connection, then uses those values to generate sine wave points. These sine wave points are used to position multiple servos.

I am currently trying to decrease the resolution of the sine wave points so there is more time for the servo to reach its given position.

The only way I can think of to accomplish this is by increasing the time between writing servo positions. As far as I can tell, I have implemented this correctly, however it results in a sine wave of a lower frequency.

The method I am using to alter the resolution is by changing the variable `sine_time`, which is used in the conditional statement `if(currentMillis - previousMillis >= sine_time)`, near the bottom of the program.

```
/*
This is a program that recieves sine wave parameters from a serial connection in a single string.
The string is parsed and converted into numbers, which are plugged into 8 sine equations to generate
positions for each joint of the robot.
*/

#include <Servo.h>

Servo SB, SF, HB, HF, EB, EF, KB, KF;
int iAmp, iF_offset, iB_offset, iFk_offset, iBk_offset, pos[] = {0,1,2,3,4,5,6,7};
unsigned int t = 0;
unsigned long previousMillis = 0;
float fKnee_amp, fAfreq, fPhase, fGait;

void setup(){
  //Start serial stream at 115200 baud
  Serial.begin(115200);

  //Connect servos to Arduino
  HB.attach(2);
  KF.attach(3);
  SB.attach(4);
  EB.attach(5);
  HF.attach(6);
  KB.attach(7);
  SF.attach(8);
  EF.attach(9);

  delay(3000);
}

void loop(){
  char c, buffer[10];
  String readString, amp, knee_amp, afreq, gait, phase, f_offset, b_offset, fk_offset, bk_offset;
  //change the resolution of the sine wave (lower value is higher resolution)
  //digital servos refresh at a rate of 50Hz which is 0.02s
  float sine_time = 100;

  while (Serial.available() && readString.length() < 37){
    //delay to allow buffer to fill
    delayMicroseconds(10);
    if (Serial.available() > 0){
      //get one byte from serial buffer
      char c = Serial.read();
      //creates the string "readString"
      readString += c;
    }
  }

  if (readString.length() > 36){
    //see what was received
    Serial.println("The string is: " + readString);
    Serial.println(readString.length());

    //parse serial string into separate parameters
    amp = readString.substring(0, 3);
    knee_amp = readString.substring(3, 7);
    afreq = readString.substring(7, 11);
    phase = readString.substring(11, 15);
    gait = readString.substring(15, 20);
    f_offset = readString.substring(20, 24);
    b_offset = readString.substring(24, 28);
    fk_offset = readString.substring(28, 32);
    bk_offset = readString.substring(32, 36);
    /*
    //Print to serial monitor to see parsed results
    Serial.println("Hip Amp: " + amp);
    Serial.println("Knee Amp: " + knee_amp);
    Serial.println("Afreq: " + afreq);
    Serial.println("Gait: " + gait);
    Serial.println("Phase: " + phase);
    Serial.println("F Offset: " + f_offset);
    Serial.println("B Offset: " + b_offset);
    Serial.println("Fk Offset: " + fk_offset);
    Serial.println("Bk Offset: " + bk_offset + "\n");
    */
    //convert string values to numbers
    iAmp = amp.toInt();

    knee_amp.toCharArray(buffer, 10);
    fKnee_amp = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    afreq.toCharArray(buffer, 10);
    fAfreq = atof(buffer)/100;
    memset(buffer, 0, sizeof(buffer));

    phase.toCharArray(buffer, 10);
    fPhase = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    gait.toCharArray(buffer, 10);
    fGait = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    iF_offset = f_offset.toInt();
    iB_offset = b_offset.toInt();
    iFk_offset = fk_offset.toInt();
    iBk_offset = bk_offset.toInt();

    //clear strings
    readString="";
    amp="";
    knee_amp="";
    afreq="";
    gait="";
    phase="";
    f_offset="";
    b_offset="";
    fk_offset="";
    bk_offset="";
  }

  //if the joints should be oscillating
  if (fAfreq > 0){
    //determine joint positions
    pos[0] = iAmp * sin(fAfreq*t) + 1500 + iF_offset;
    pos[1] = iAmp * sin(fAfreq*t) + 1522 - iF_offset;
    pos[2] = iAmp * sin(fAfreq*t + fGait) + 1500 + iB_offset;
    pos[3] = iAmp * sin(fAfreq*t + fGait) + 1446 - iB_offset;

    pos[4] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fPhase) + 1500 + iFk_offset;
    pos[5] = iAmp*fKnee_amp * sin(fAfreq*t + fPhase) + 1500 - iFk_offset;
    pos[6] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fGait + fPhase) + 1500 + iBk_offset;
    pos[7] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fGait + fPhase) + 1538 - iBk_offset;
    /*
    //print parameter variables
    Serial.println(iAmp);
    Serial.println(fKnee_amp);
    Serial.println(fAfreq);
    Serial.println(fGait);
    Serial.println(fPhase);
    Serial.println(iF_offset);
    Serial.println(iB_offset);
    Serial.println(iFk_offset);
    Serial.println(iBk_offset);

    //print servo positions
    Serial.println(pos[0]);
    Serial.println(pos[1]);
    Serial.println(pos[2]);
    Serial.println(pos[3]);
    Serial.println(pos[4]);
    Serial.println(pos[5]);
    Serial.println(pos[6]);
    Serial.println(pos[7]);
    */
    //get time in milliseconds
    unsigned long currentMillis = millis();

    //if the time threshold has been passed
    if(currentMillis - previousMillis >= sine_time){

      Serial.println(currentMillis - previousMillis);

      previousMillis = currentMillis;

      //write servo positions
      HB.writeMicroseconds(pos[2]);
      KF.writeMicroseconds(pos[6]);
      SB.writeMicroseconds(pos[0]);
      EB.writeMicroseconds(pos[4]);
      HF.writeMicroseconds(pos[3]);
      KB.writeMicroseconds(pos[7]);
      SF.writeMicroseconds(pos[1]);
      EF.writeMicroseconds(pos[5]);

      //increment time parameter
      t+=1;
    }
  }
}

```

# Answer
> 0 votes
Your sine waves depend on “time” via appearances of `fAfreq*t` in lots of places. However, `t` actually is a pass counter, rather than reflecting true elapsed time.

Instead of incrementing `t` by 1, increment it by a value that's proportional to elapsed time. Or, more directly, set `t` equal to a multiple of elapsed time. For example, whenever you start over, record current time via `basetime = millis()`. Then, just after your `//determine joint positions` comment, say `t = speedratio * (millis()-basetime);`.

---
Tags: servo
---


title: sensor sampling frequency

text:
# Question
Title: sensor sampling frequency
I have a problem collecting data from my accelerometer/gyroscope sensor with a constant sampling rate. Is there a way to program the arduino to collect data from the sensor and store these values in a SD card with a constant frequency of 1kHz without using delay? The sensor that I am using is a MPU6050 gy-521 sensor that uses I2C with arduino. I will be reading 6 different datas from my sensor: acceleration in x,y,z directions and gyration in x,y,z directions. Thank you all in advance for the advice/help.

so my project will be making a device that collects the values from the sensors and saves them to study the data later. First, a LCD display will print out a message without having any data collection to occur. The data collection will start when a button is pushed. After the button is pushed, the display will print out another message saying that the arduino is collecting data and the Arduino will save the 6 values (x,y,z acceleration and gyration) from the accelerometer/gyroscope sensor to the SD card. The data collection will stop after the button is clicked again and the display will print out another message saying that it has stopped collecting data. Then, this process can start again if the button is clicked once again. Thanks in advance

# Answer
You have discovered delay() does not guarantee the period of your code. This is because the period of your code is the delay() plus the time for your code to execute.

What you need is a hardware clock to give your code an indication that a fixed period has expired. This is one of several Arduino timer libraries. The timer library web page describes your problem in more detail with example code using delays and using the timer library features.
> 1 votes

# Answer
A quick and dirty solution is to just the right the code that does the sampling and loop it, say 10,000 times, with a short delay. Measure the time it takes to do the 10,000 samples by recording time before and after all the samples.

The amount of time taken will be:

```
10,000 x (delay period -> known) + 10,000 x (actual amount of time to do the sampling)

```

From this data you can determine the required delay to get your 1 kHz sampling goal.
> 0 votes

---
Tags: frequency
---


title: Arduino IO long distance travel

text:
# Question
Title: Arduino IO long distance travel
I would like to use Arduino to control locks around a building which is 5 storeys high and on every floor there is 2 door.

I'm concerned whether the wires is able to travel all the way from the ground floor to the 5th floor to provide enough power to the relay located at the door.

The lock will be a 12V magnetic lock and it will be unlocked thru a SSR relay which will be controlled by the arduino

# Answer
Yes, losses in wires are proportional to the length, so an excessively long wire may not be able to deliver enough power. Many factors come into play here:

* higher current consumed by the relay increases the losses
* smaller wire diameter increses the losses
* the voltage required by your relay defines how much you can afford to lose

For example, a pair of AWG23 wires 30m long will have a total resistance of 4 Ohm. If your relay consumes 100 mA, you will lose 0.4V in the wires. If Arduino delivers 5V, and the relay requires a mininum of 4.5V to work, you're just good enough: you're delivering 4.6V to the relay after the losses.
> 2 votes

# Answer
You are addressing a device control problem that auto, home and building automation has concerned itself with for years.

As such there are many solutions. Most require a transmitter and one or more receiver(s). C-BUS is one such solution. Another is CAN-BUS.
> 0 votes

# Answer
Use wireless nodes which are self-powered. It is easier (no need for lot of cables) and also solves this issue completely.

You can use ZigBee, which is mesh network. Every node re-transmit signal for nodes which are far. Because you have one on every floor, you would not have issues with reception.

EDIT: If you want to use wires, I would still keep self-powered nodes and you can communicate with them using i2c or similar. You would need only 3 wires (SDA, SCL and GND) and they could be very thin, because they transfer only signals (\<1mA range)). These 3 wires would connect all nodes. All nodes should have distinct address. I think this could be very cheap because you can create nodes with arduino micro which can be bought for ~1.5$ each.
> 0 votes

---
Tags: power, pins
---


title: Proper error logging using Arduino

text:
# Question
Title: Proper error logging using Arduino
Coming from a C# background where I do logs for every application, and given that I will be using the Mega for most projects and therefore have the memory available to do so, I want to incorporate error logging in my projects.

What is the best way to do so? Writing to an SD card? Writing via Wi-Fi or Ethernet to a networked storage or PC? Writing to a USB thumb drive?

The current project I am working on uses the Adafruit Music Maker shield so has the SD card reader incorporated into it, so the easy choice there would be to use that but I like creating solutions that are portable to multiple projects so writing via Wi-Fi or Ethernet seems to be the preferred method?

Since I am not fully up to speed with C++, and I see there are various ways to write to text files in C++, are there any preferred ways to do so depending on which storage route I take?

# Answer
> 0 votes
What you ask is difficult to answer in generic way, because not all the Arduino boards have the same HW options and even if you were to require a certain interface (ex: WiFi), that will introduce other side effects:

* it will use certain pins/buses (SPI) that one might want to reserve for other purposes (yes you can have multiple peripherals on the SPI bus, but it will require additional code)
* it might significantly alter the execution timing in certain cases

What most people use - and seem to be happy with - is the serial port:

* it is not too difficult to setup
* the ide already has a serial port monitor
* it can produce information that is immediately human-parsable
* there is no need to retrieve it afterwards (an SD card has to be extracted, mounted, etc.)

I would advise you to consider this at least as option, if not the only option.

Of course each option has drawbacks: the serial port can also cause delays in the execution, might not be too good if you have lots of stuff to log, etc.

The serial port could be seen as a intermediate step toward wireless logging: modules like the esp8266 do rely on serial communication.

Which means you could have wired logging while in the early phase and wireless logging later on, assuming you can afford to have something constantly listening to your project.

I would consider the SD card only for cases where the device will run unattended for long periods of time and there might be some hard to reproduce event that you want to track.

You could also consider the onboard flash, if you have to log events that happen seldom.

# Answer
> 0 votes
Normally, because Arduino is meant to be easy to understand and use, C++ is only used (extensively) in the libraries. Perhaps someone knows more about the Mega, but, in general, the Arduino platform does not contain many complex built in features. For instance, before even thinking about how best to write to an SDCard, you need to do some research into how to load and use the Arduino SDCard library.

This appears to be what you eventually want to do.

# Answer
> 0 votes
Embedded systems typically use UART for logging, and Arduino is no exception. Logging to UART is as easy as calling `Serial.begin()` in the `setup()` and `Serial.println()` in the `loop()`, it works on all Arduinos, doesn't require any additional hardware and consumes much less resources than the SD card or networking library. Of course, you're limited in bandwidth (115200 kbit/s, sometimes more), so you won't be able to log in the fast-running cycles.

If you don't like the Serial Monitor feature of Arduino IDE, you can install one of the many terminal programs which will happily write the data from serial port to a log file. Some of these tools also have nice analysis features, including plotting of logged signals, formatting, data conversions etc.

If you're good with command line, creating a log file is as simple as

```
cat /dev/ttyUSB0 > log.txt

```

in Linux or

```
type COM1 > log.txt

```

in Windows.

# Answer
> 0 votes
In my Arduino project, I wrote communication sub protocol between a Raspberry Pi (or a PC).

I simply added some commands to duo vars or arrays into memory.

---
Tags: programming, arduino-mega, datalogging
---


title: Connecting to WIFI using esp8266

text:
# Question
Title: Connecting to WIFI using esp8266
This is my code. I am tring to make a connection to my wifi through esp8266.

```
#define DST_IP "192.168.1.5" // my IP
#include <SoftwareSerial.h>

SoftwareSerial mySerial(0, 1);

void setup()
{
  Serial.begin(115200);
  mySerial.begin(115200);
  while (! Serial); // Wait until Serial is ready - Leonardo
  Serial.println("AT+RST");
  delay(4000);
  Serial.println("AT+CWJAP=\"Ahmed\",\"12341234Aass\"");
  delay(4000);
  if (Serial.find("OK") )
  {
    Serial.println("1");
  }
  else
  {
    Serial.println("0");
  }
}

void loop()
{

}

```

This is the result of my code.

# Answer
> 1 votes
```
SoftwareSerial mySerial(0, 1);

```

try changing **pin0** and **pin1** with some other pins. (lets say with **pin2** & **pin3**)

**pin0** and **pin1** are used by default **Serial**.

---
Tags: arduino-uno, serial, arduino-ide, wifi, esp8266
---


title: Wake up from sleep from pressed button?

text:
# Question
Title: Wake up from sleep from pressed button?
```
#include <avr/sleep.h>
#include <avr/power.h>
//This sketch is a metronome, in which each led pin shows one beat.

const int speaker = 13;  //speaker at pin 13
int ts = 6;  //highest led pin
int count = 3;  //"beat 1 pin"
const int keyPin = 11;  //button to change time signature
const int keyPinR = 10;  //button to change rhythm
const int keySwitch = 2;  //sleep mode/wake up button

//All pins below use a pull-up resistor, so the states are inverted
int buttonState = LOW;
int buttonState2 = LOW;
int switchState = LOW;
int silentState = LOW;

int bpm = 120;  //you do not need to know this,
//it's just a variable for the potentiometer to change the tempo

int rthm = 1;  //rhythm
volatile int pressed = 0;
long silent = p;

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

   for(int thisPin = 3;thisPin <= ts;thisPin++)
   {
      pinMode(thisPin,OUTPUT); //initialize thisPin as an output
      pinMode(8, INPUT); //potentialmeter for changing temp
      //Pin 9 to 11, along with pin 2, are all push buttons with pull-up     resistors
      for(int i = 9; i<=11; i++)
      {
         pinMode(i, INPUT);
         digitalWrite(i, HIGH);
      }
         pinMode(2, INPUT);
         digitalWrite(2,HIGH);
   }
}

void loop()
{
   turnOn();
}

void turnOn()
{
    buttonState = digitalRead(keyPin);//key for
    buttonState2 = digitalRead(keyPinR);
    switchState = digitalRead(keySwitch);
    silentState = digitalRead(9);
    //Serial.println(switchState);
    if(switchState==LOW&&pressed==0)
    {
       sleep_enable();
       set_sleep_mode(SLEEP_MODE_PWR_DOWN);
       attachInterrupt(digitalPinToInterrupt(0), interrupt, LOW);
       sleep_cpu();
       //Serial.println(switchState);
    }
    else {
       //The beat starts at pin 3, runs in consecutive pins,
       //and ends at pin 8 at maximum
       if(buttonState==LOW)
       {  //changing time signature - up to 5 beats
           ts++;
           if(ts==8)
           {
              ts = 3;
              //8 - 3 = 5 beats max
           }
        }
        if(buttonState2==LOW)
        {  //changing rhythm - quarter note to eighth, then
          //triplets and sixteenths, back to quarter notes
          rthm++;
          if(rthm==5)
          rthm = 1;
 }

    if(silentState==LOW){//if silent key pressed, go to silence (only LED's showing)
    silent++;
  }

  //The RUN code
  for(int thisPin = 3;thisPin <= ts;thisPin++)
  //LED's blinking beats (thisPin - LED pin (beat number + 2))
 {

 for(int r = 1; r<=rthm; r++)
 {//nested loop for the rhythm
   bpm = pulseIn(8, HIGH);//pin 8 - tempo potentialmeter
   digitalWrite(thisPin,HIGH);//each LED blinks

   pinMode(13,OUTPUT); //pin 13 - speaker

   if(silent%2==0)//Press once, tone, press again, no tone
     noTone(13);
 else
 if(count == 3&&r==1). //first beat is higher
 tone(13,4400,80);
 else if(r==1). //downbeats slightly lower
 tone(13,2500,80);
 else
 tone(13,2200,60);  //off beats even lower
 delay((bpm-52)/rthm);
 digitalWrite(thisPin,LOW);  //turn each off as we proceed to the next beat (LED)
 pinMode(13,INPUT);  //speaker input
}
count++;  //beat++

if(count >ts){//go back to count
count = 3;
}

   }
  }
 }

void noSound()//silence the speaker
{
  noTone(13);
}

void interrupt()//this is where the sleep interrupt starts -               //how can i press it to wake up???
{
    sleep_disable();
    detachInterrupt(0);
    if(switchState==HIGH){
       pressed = 1;
       Serial.println(switchState);
       turnOn(); //go back to the main functional method (?????)
     }
 }

```

Once the keySwitch button is pressed (pin 2), the arduino goes to sleep; however, the only way to turn it on is by resetting everything. How can I just wake up the Arduino, keeping every state as before the sleep interrupt?

# Answer
> 1 votes
```
attachInterrupt(digitalPinToInterrupt(0), interrupt, LOW);

```

should be either

```
attachInterrupt(0, interrupt, LOW);

```

or

```
attachInterrupt(digitalPinToInterrupt(2), interrupt, LOW);

```

As pin 0 is not an interrupt pin. Also the button is connected to pin 2, not pin 0. `digitalPinToInterrupt(0)` would actually return `-1`.

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


title: Printing decimal numbers

text:
# Question
Title: Printing decimal numbers
I made simple sketch that generates three random numbers and then calculates the average of these three random numbers.

It divides the total by 3 and then displays that average number with `serial.println`.

Sometimes the generated average number can be decimal (for example 261,333333 or 124,33333).

Interestingly, the serial print doesn't print in decimal format **124,33333** it prints just integer **124**.

How do I print the value in decimal?

# Answer
> 3 votes
In languages such as C or C++ there is a distinction between integer types and floating-point types. You see, computers work using **bits**. A bit is either **0** or **1**. A bit obviously lack in both range and precision, so we combine multiple bits in order to improve.

# Integral Types

A **byte** is a group of 8 bits. In C, the type used is either

```
uint8_t x; // Values from 0 to 255.
int8_t  x; // Values from -128 to 127
char    x; // Values from the ASCII character set (still -128 to 127)

```

On Ardiuno Uno, an **int** is a group of 16 bits:

```
uint16_t c; // Values from 0 to 2^16-1 = 65535, synonym: unsigned int (Arduino)
int16_t  c; // Values from -32768 to 32767,     synonym: int (Arduino)

```

A **long** is a group of 32 bits:

```
uint32_t v; // Values from 0 to 2^32-1 = 4,294,967,295 = 4 GiB (unsigned long)
int32_t  v; // Values from -2,147,483,648 to 2,147,483,647 (long)

```

There is also usually support for 64-bit numbers, but we try not to use them in Arduino code. The reason is that most Arduino MCUs use **8-bit** registers, so 64-bit operations such as "add", "sub", etc. would be very slow.

**Note**: Different architectures use different numbers of bits for these types. In order to be compatible with other architectures, use `int32_t` etc. to be sure.

## Literals and Casts

Oftentimes, the compiler can not see what type a literal value is supposed to be. In C, the compiler picks a default which is usually larger than you would like. For this reason, it is useful to know how to specify a literal exactly with the type:

```
 ((uint8_t)200)   // Casting 200 to an unsigned 8-bit integer
 ((char)65)       // Making the ASCII letter 'A'
 ((int32_t)42)    // Force 32 as a signed 32-bit integer (long)
 42L              // The 'L' suffix does the same as above

```

## Division and Remainder

A common cause of problems when programming in C is the division operator `/`. If the operands are both integer types, the result will also be an integer. So `1/3` is in fact `0`. You can get the remainder of the division using the modulus operation `%`. For instance:

```
void show_division(int n, int d)
{
    Serial.print("The division: ");
    Serial.print(n);
    Serial.print(" / ");
    Serial.print(d);
    Serial.print(" equals ");
    Serial.print(n / d);
    Serial.print(" with a remainder ");
    Serial.println(n % d);
}

```

# Floating-point Types

All of the above types are integrals, so they do not support any fractional value. Therefore C defines **two** different floating-point types: **float** and **double**. The former is a 32-bit value and the latter is a 64-bit value. The way it works is that the bits are split in 3:

* A single bit is used for the **sign**.
* A certain number of bits represent the fractional part, the **mantissa**.
* The rest of the bits are used for the **exponent**.

As an example, the 32-bit float value representation for 1.25 is

```
seeeeeee_emmmmmmm_mmmmmmmm_mmmmmmmm = s * 2^(e-127) * (1.m...)_2
00111111_10100000_00000000_00000000 = (+1) * 2^(127-127) * (1.0100)_2
// Note: Binary 1.01 equals 1.25 in decimal

```

## For performance, use the `f` suffix

Although 64-bit doubles are very accurate, the resulting code will run much slower. I, therefore, recommend using 32-bit floats instead. It is useful to know that you can tack on an `f` after the floating-point literal:

```
(a + b + c) / 3.0f; // Make sure to divide using 32-bit operations.

```

If `a`, `b` and `c` above are integer types, the additions will also be integer additions. When the compiler sees an `int` divided by a `float`, it will convert the `int` to a `float`, and then perform a float division. This is slow, but certainly faster than a double division.

The compiler is smart, but it doesn't hurt to help it. There is only a very small precision loss in converting this to a float multiplication:

```
(a + b + c) * (1.0f / 3.0f);

```

The compiler will pre-calculate `(1.0f / 3.0f)`, so you get a much faster floating-point multiplication (in addition to the `int` to `float` cast).

**Note**: Arduino Uno defaults all floating point literals to 32-bit, and `double` is the same as `float`. Therefore, the `f` suffix is strictly not needed. It is still good practice to add these for compatibility with other architectures.

# Answer
> 2 votes
In the C family of languages, if you divide an integer by another integer, the compiler interprets the division operator (`/`) as an *integer division*, i.e. you get the integer part of the quotient. Thus,

```
(first_int + second_int + third_int) / 3

```

is an integer.

If either operand is a floating point number, then the other one is implicitly converted to floating point, and you get a floating point division. Thus

```
(first_int + second_int + third_int) / 3.0

```

is a floating point number, and the result you expect.

---
Tags: arduino-uno, serial, mathematics
---


# Question
Title: Pi3 + ATmega644P: How do I establish a data connection with 1 analog input and 1 digital output left on the AT?
I have no UARTs left on the ATmega and need to deliver 1 Byte of information from the pi using 1 analog input. I2C is no option either.

I planned using the digital output to request an analog signal from the Pi, but it does not seem to have a DAC.

Is it possible to properly translate/read a PWM signal with the atmegas ADC? Analyzing the PWM the 'usual' way would probably be too slow as I don't trust the pi to keep up with a high PWM frequency.

PINS left: PA0(ADC0|PCINT0), PD7(OC2A|PCINT31)

I should add that this is a rather large robotics project involving communication between 8 MCUs in it's current state and needs to be extended by a computer vision module(=pi), which is not compatible with the existing custom bus

Edit: This also is a real time system which has approximately ~1-2ms left in it's main loop(10ms period). The required data has to be present in time as it alters the robot's behaviour for this loop.

# Answer
> 1 votes
The solution was to hook up PA0 to GPIO18 of the pi with an RC-circuit inbetween. GPIO18 features a hardware PWM output, which has to be set to mode 0 (non balanced, mark-space), because the balanced mode could not handle odd pwmRanges for some reason(it is badly documented).

This setup enables the atmega to read the pi's pulsed 0-3,3V output as analog input.

Pin initialization on Pi(using a python library):

```
import wiringpi2 as wiringpi

wiringpi.wiringPiSetupGpio()
wiringpi.pinMode(18, 2)
wiringpi.pwmSetMode(0)    #<- important part

```

Currently writing the Atmega side

```
    uint8_t     i = 0;
    uint32_t val  = 0;
    while(i<8)    //average 8 measures
    {
        i++;
        ADMUX   = 0 & 0x1f;    //select channel 0 (PA0)
        ADMUX |= (1<<5);       //set ADLAR bit ADCH > ADCL
        ADCSRA  = ADCSRA | (1 << ADSC) | (1 << ADIF);
        while (ADCSRA & (1<<ADSC));
        val = val + (ADCH);
    }
    return ((val)>>3);

```

Note that this reads a 10bit value on the channel and discards the least significant 2bit stored in ADCL as ADLAR is set to speed everything up.

# Answer
> 1 votes
You can start researching about one wire protocol here to see if can implement it given your situation.

---
Tags: serial, communication, adc
---


# Question
Title: Help! Interfacing LCD with Arduino using 8255A Intel peripherals
I'm new to all this stuff and for the past two days, I have been trying to interface a 16x2 LCD to an Arduino Uno using an Intel 8255A component without any luck. The problem is, how can I attach or set the LCD's pins \<\> to the unknown pins of the 8255A.

Is it even possible?

Thanks for any kind of help.

# Answer
You will not be able to use 8255 pins as parameters to the the LiquidCrystal library without making substantial changes to either the library or the Arduino core.

The reason is that to configure or change a pin on the 8255, you will need to go through a series of operations manipulating the ATmega pins to which the 8255's `microprocessor bus interface` is connected. You can learn about the necessary operations by reading the 8255 data sheet. Also keep in mind that the 8255 does not have per-pin configuration - rather, the first two ports must each be either entirely inputs or entirely outputs, while there third port can be split in half.

Once you know how to set a pin, you will need to have the liquid crystal functionality trigger these operations.

One approach would be to create a heavily modified version of the library which knows how to work through the 8255.

Another would be to create a modified version of the Arduino core which has additional pin numbers corresponding to the 8255's pins, and generates code which does the necessary intermediate bus operations to access them. However this will be quite challenging - you have to make sure the intermediate code gets in there in all paths, and figure out how it will handle cases where code tries to set pins that must have the same mode to conflicting modes.

As others have said, you would practically be better off using a different MCU with more I/Os - either an Arduino Mega, or one of the ARM-based boards.
> 1 votes

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


# Question
Title: Draw polygon on LCD from GPS latitude and longitude
I'm working on a personal project (a usefully tool based on ublox GPS and Arduino Mega that can measure distance between 2 points, compute area, speed, save data on SD card)

Now I want to add new feature and when I show the area(in m^2) on LCD, I want to show the polygon built by more coordinates.

I tried all I know, I searched for solutions but without success.

How can I "scale down" coordinates to make them fit in a x,y system with max size (320\*480, LCD size) ?

# Answer
Over a small area lat and long are just simple Y and X coordinates respectively.

Dynamic scaling of the points is a very simple matter. All you need to do is work out the range of each dimension - so subtract the lowest latitude from the highest, and the lowest longitude from the highest.

That gives the full X and Y dimension of your area. Then just divide those by the dimensions of your screen. That gives you a scaling factor for each direction.

For each point, subtract the lowest longitude and latitude, and divide by the scaling factor for each direction.

If you want to be more fancy and retain the aspect ratio then you just need to work out which of the two scaling factors will allow all the polygon to remain on the screen - that is, divide and offset all your points by one factor, then by the other, and pick the smallest factor where all the points are within the area of your screen.
> 2 votes

# Answer
I did the code for Arduino and it works really nice. I added an dynamic X offset to center it on the screen.

```
// lat = coordinatesForArea[i][0]
// lng = coordinatesForArea[i][1]
// cntr is the count of points

float newPoints[100][2];
float maxLat = 0;
float maxLng = 0;
float minLat = 180;
float minLng = 180;

for (int i = 0; i < cntr; i++) {
  maxLat = max(maxLat, coordinatesForArea[i][0]);
  maxLng = max(maxLng, coordinatesForArea[i][1]);
  minLat = min(minLat, coordinatesForArea[i][0]);
  minLng = min(minLng, coordinatesForArea[i][1]);
}

float ySize = maxLat - minLat;
float xSize = maxLng - minLng;

float scaleFactor = ySize / 300;

float maxY = 0;
float maxX = 0;

for (int i = 0; i < cntr; i++) {
  newPoints[i][1] = (coordinatesForArea[i][1] - minLng) / scaleFactor;
  newPoints[i][0] = (coordinatesForArea[i][0] - minLat) / scaleFactor;
  maxX = max(maxX, newPoints[i][0]);
  maxY = max(maxY, newPoints[i][1]);
}

float newScaleFactor = maxY > maxX ? maxY / 300 : maxX / 300;

float newMaxX = 0;

for (int i = 0; i < cntr; i++) {
  newPoints[i][1] = newPoints[i][1] / newScaleFactor;
  newPoints[i][0] = newPoints[i][0] / newScaleFactor;

  newMaxX = max(newMaxX, newPoints[i][0]);
}

float newOffsetX = (320 - newMaxX) / 2;
float newOffsetY = 100;

for (int i = 0; i < cntr; i++) {
  newPoints[i][1] = newPoints[i][1] + newOffsetY;
  newPoints[i][0] = newPoints[i][0] + newOffsetX;
}

for (int i = 0; i < cntr-1; i++) {
  myGLCD.drawLine(newPoints[i][0], newPoints[i][1], newPoints[i+1][0], newPoints[i+1][1]);
}

myGLCD.drawLine(newPoints[0][0], newPoints[0][1], newPoints[cntr-1][0], newPoints[cntr-1][1]);

```

Thank you Majenko
> 0 votes

---
Tags: arduino-mega, lcd, gps
---


# Question
Title: When should you worry about interference affecting the analog input?
I made something that uploads the measured current to Thingspeak. Everything works, but i did not place the DC to DC converter on the board because i was worried that it would interfere with the analog input. Also the ESP8266 is very close to the Arduino Pro Mini. Could it affect the reading? Could i have put the DC to DC converter on the board without any problem?

230VAC to 12VDC adapter(not on the picture) --\> 12VDC to 3,3VDC(on the picture)--\>the prototype board

Sensor: SCT-013-030 30A = 1V

# Answer
> 0 votes
You are more likely to have noise injected on the power pins of the Arduino that by EMI or capacitative coupling. With the switcher on board of off board it will make no difference if the voltage it supplies to the Arduino (and hence to the ADC) is noisy and full of spikes.

# Answer
> 0 votes
Noise reduction involving Analog to Digital Conversions can be done in many ways. Common software solutions involve averaging multiple conversions. Exponential smoothing is one such method. One advantage of exponential smoothing is that it can be applied to an endless stream of conversions.

---
Tags: esp8266, analogread, wireless
---


title: LED and LCD game

text:
# Question
Title: LED and LCD game
I am making a game where four different colored LEDs are flashing randomly, and when the green LED lights up, the user presses a button. If the user pushes the button when the LED is green, I want my 16x2 LCD screen to record points. And when the user presses the button on the wrong LED, i want the LCD screen to start over at "0 points."

Can you give me some place to start on a code that will feed "data" from each time the button is pushed to the LCD screen?

# Answer
You need an example that shows you how to right to a screen and an example that shows you how to detect a button press, also you need to be able to light LEDs. These are all examples supplied with the Arduino IDE, are you using that? Look at each example in turn, setup the circuit get to understand them, then disect them and understand how they work and can get them to do what you want.

Button presses can be trouble some, you may need to investigate denouncing, either software or hardware.

Hope that gives you a starting point.
> 1 votes

---
Tags: arduino-uno, programming, led, lcd, button
---


# Question
Title: Powering from 3V coin cell to VCC, using I/O pin as supply GND
I'm thinking of creating a "small" electronic dice. (I will solder the button a little different though xD)

But there are some concerns on my design:

**Powering from a coin-cell**

It's a 5V arduino Pro mini, but it should be able to run (per datasheet) on 2.7V to 5.5V, can I just put the 3V of the coin-cell battery on VCC. (I'm aware I'll have to use the internal 8Mhz clock on this voltage though). I won't need the regulator, since the coin-cell will never exceed 5V?

**Can I use a I/O as (input/supply) GND?**

You can actually use outputs as positive voltage, and you can sink currents. But does that mean I can connect the negative side of the coin-cell to an output, and sink it? This way it should power my arduino's VCC pin through the "digital GND"

**Using the reset button**

I could use the reset button, but would it still give me "random enough" numbers? Since the seed is reset every time?

(I probably won't use it though, it's placed inconveniently for this project, but I am wondering.)

**A crude drawing below:**

The fun thing is, polarity of the LED's/segments doesn't matter, since I can change which side is high or low? :) Also, I've only drawn half the LED's/segments. And I know it's better to use a resistor on every pin, but I don't want to make it any more bulky.

(btw, battery GND pin should be pin 4, not pin 2)

# Answer
> 6 votes
> Can I use a I/O as (input/supply) GND?

You can use an I/O pin as a supply for *another (low power) device*, but you should power the Arduino itself from its Vcc and GND pins.

> I could use the reset button, but would it still give me "random enough" numbers?

You will likely see the very same sequence every time you reset it. There are ways around this:

* You can seed the random number generator (RNG) at startup with an `analogRead()` from an unconnected pin, but it's not clear how much entropy you can expect from this.
* You can save the RNG's entropy into the .noinit memory section, this way it will not be wiped up during the program startup.

I would recommend, however, that you use a normal I/O pin to trigger the dice, if only for one reason: the time when the user presses the button (that you read with `micros()`) is a very good entropy source for seeding the RNG.

For example, whenever the user presses the button you could:

```
srandom(random() ^ ((uint32_t) analogRead(0) << 22) ^ micros());

```

This way you combine the entropy from the button press with the entropy from the analog pin (if any), with whatever entropy may already by in the RNG.

**Edit**: More on entropy gathering.

As you seemingly already know, `random()` is a pseudo-random number generator intended to produce a sequence of numbers that *look* random. Unless you have some other source of randomness in your program, every time you restart the Arduino you will get the *very same* sequence of numbers. Getting true randomness (also called “entropy”) on an Arduino is not so easy. Here are some ideas you may want to explore.

## Read from an unconnected analog input

This trick seems to be pretty popular. It can even be found in the Arduino documentation on randomSeed():

> use randomSeed() to initialize the random number generator with a fairly random input, such as analogRead() on an unconnected pin.

In my experience, this seems to be a very poor entropy source. I wrote a test program that prints out the output of `analogRead(0)` and it seems to cycle through the same few values in an almost predictable way. I estimate this gives around one or two bits of entropy per call. On the plus side, each call takes just over 100 µs.

## Read from an analog noise source

There is a lot of literature on building analog noise sources. Such sources are used inside crypto-grade random number generators, but the circuits are likely to be more complex than you would like. There seems, however, to be a very simple alternative. In a comment to this post, CharlieHanson wrote:

> Connecting the analogue input to the collector of a run-of-the-mill transistor, with the emitter grounded and base open helps to make a noisy input.

I have not tested this idea, but it is certainly worth exploring.

## Time user input

If the user is required to press a button to throw the dice, the timing of the button press is probably the best entropy source you can have. With a 8 MHz clock, the `micros()` function has a resolution of 8 µs (64 clock cycles). Assuming the user is unable to control his timing better than 0.1 seconds, then you have more than 13 bits of entropy per button press.

If, instead of `micros()`, you use timer 1 running at the full CPU speed, then you would have 16 bits of entropy per button press. And you would not need `random()` at all, as you could just output `1+TCNT1%6`. That would be like throwing a dart at a carnival wheel spinning at 80 *million* RPM (8 MHz / 6)!

## Measure clock drift

The drift of a clock relative to another clock can be used as an entropy source. The ATmega chip in your Arduino has two independent clocks: the internal “calibrated” 8 MHz RC oscillator, and the 128 kHz oscillator used by the watchdog timer. Both are low-accuracy clocks subject to somewhat unpredictable drift, which is a good thing for this application. You can gather entropy from this by configuring the watchdog timer as a periodic interrupt source, and using timer 1 at full speed to time the interrupt arrival times:

```
#include <avr/wdt.h>
#include <util/atomic.h>

// Configure Timer 1 for counting CPU cycles and the watchdog as an
// interrupt source firing (roughly) once a second. Call once in
// setup().
void configure_timers()
{
    // Timer 1.
    TCCR1A = 0;          // normal counting mode
    TCCR1B = _BV(CS10);  // prescaler = 1

    // Watchdog. This is a timed sequence.
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        WDTCSR = _BV(WDCE)  // enable changing the prescaler
               | _BV(WDE);  // ditto
        WDTCSR = _BV(WDIF)  // clear interrupt flag
               | _BV(WDIE)  // enable interrupts
               | WDTO_1S;   // timeout ~ 1 second
    }
}

volatile uint16_t wdt_time;
volatile bool wdt_fired;

// Watchdog interrupt service routine.
ISR(WDT_vect)
{
    wdt_time = TCNT1;
    wdt_fired = true;
}

// Add entropy to the RNG from the timing of the last WDT interrupt.
// Call periodically in loop().
void get_wdt_entropy()
{
    if (!wdt_fired) return;  // No WDT event since last time.
    uint16_t wdt_time_copy;
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        wdt_time_copy = wdt_time;
        wdt_fired = false;
    }
    srandom(random() ^ wdt_time_copy);
}

```

I have tested this idea by plotting the time *differences* between successive interrupts. On an Arduino Uno clocked at 16 MHz, I see short-time fluctuations with an amplitude of about 300. That should provide around 8 bits of entropy per second.

## Save the entropy pool across reboots

Once you have spent some effort to gather entropy from the environment, it would be a pity to lose it all at power down. It is common practice to save the entropy pool to disk when a computer shuts down, and restore it at boot time. This avoids the problem of the RNG always starting in the same predictable state. On the Arduino, you have no disk, but you can use the EEPROM instead. The problem is you cannot know in advance when the user is going to switch the device off. Then, ideally, you would save the entropy every time the user requests a new dice value. The new problem is that the EEPROM is only guaranteed to work reliably for 100,000 write/erase cycles. This may not be a serious problem (100,000 is plenty of throws), but it can nonetheless be mitigated by using a wear-leveling scheme, where you distribute the writes across the whole EEPROM instead of always overwriting the same bytes.

Wear-leveling can add significant complexity to your program, but it turns out there is, in this particular case, a wear-leveling scheme that is trivial to implement: just write at a random location! At startup, you do not know what was the last location written to, but you do not need to: you read and mix the whole contents of the EEPROM:

```
#include <avr/eeprom.h>

// Save the entropy to EEPROM. Call this every time the user requests a
// new value.
void save_entropy()
{
    uint32_t *address = (uint32_t *)(random() & E2END & ~3);
    eeprom_write_dword(address, random());
}

// Restore the entropy from the EEPROM. Call once in setup().
void restore_entropy()
{
    uint32_t seed = 0;
    for (uint32_t *address = 0; address < (uint32_t *) E2END; address++)
        seed ^= eeprom_read_dword(address);
    srandom(seed);
}

```

## Combine the entropy sources with the XOR operator

As you probably already noticed, the bitwise xor operator (^) is used every time one wants to combine entropy sources. The main reason is that, if `a` and `b` are independent random variables, then `a^b` is at least as random as the most random of `a` and `b`. Which means that XORing a “good” random variable with a “bad” one is harmless. This is somewhat formalized as the piling-up lemma.

As an example, doing `randomSeed(analogRead(0))` at program startup is fine, but doing it repeatedly during program execution is a terrible idea: most of the time this will put the RNG in one of a very few states. If instead you

```
srandom(random() ^ analogRead(0));

```

then you are combining the current randomness of the RNG with the output of `analogRead()`, and putting this back into the RNG. And this is harmless even if `analogRead()` is quite predictable.

**A side note on randomSeed()**: Arduino releases prior to 1.6.5 had a bug that would truncate to 16 bits the entropy provided with `randomSeed()`. On those releases it is better to use the avr-libc srandom() function. The bug has since been fixed.

# Answer
> 2 votes
> It's a 5V arduino Pro mini, but it should be able to run (per datasheet) on 2.7V to 5.5V, can I just put the 3V of the coin-cell battery on VCC. (I'm aware I'll have to use the internal 8Mhz clock on this voltage though). I won't need the regulator, since the coin-cell will never exceed 5V?

That is correct.

> You can actually use outputs as positive voltage, and you can sink currents. But does that mean I can connect the negative side of the coin-cell to an output, and sink it? This way it should power my arduino's VCC pin through the "digital GND"

Definitely not. That is a sure-fire way to kill the Arduino.

Also you have a Catch-22 situation. To make the pin conduct to ground you have to set it to output and switch it LOW. How can you do that if the chip is powered off? You need to power the chip on in order to power the chip on. It just can't work.

> I could use the reset button, but would it still give me "random enough" numbers? Since the seed is reset every time?

You will only get random numbers if you seed the PRNG with a random number. If you can get a source of entropy (noise on an analog pin for instance) then yes, that could work.

> And I know it's better to use a resistor on every pin, but I don't want to make it any more bulky.

It's not "better" - it's **REQUIRED**. With just one resistor and one segment on that segment will get 8x the current compared to having all 8 segments on. You then either get very dim segments with lots on, or smoke from segments when not many are on.

# Answer
> 1 votes
Yes you should be fine with the voltage from a coin cell - though don't expect it to last long!

No you can't use an I/O as ground - they are set to input by default, and even if they weren't, if wouldn't be guaranteed to work, and even if it did happen to work\*, it would be horrible. I don't quite understand why you want to do it this way - why not just connect the cell's -ve to the GND pin, right next to the VCC?

If you seed your random number generator suitably (e.g. from an unconnected analogue input) you ought to be OK since that will suitably random - you'll be reseeding it each time with a different seed.

\*Stranger things have happend! The very fist ARM chip worked without power, running from parasitic currents from the inputs, as they discovered by mistake when they tested it with the power supply disconnected.

# Answer
> 0 votes
> You can actually use outputs as positive voltage, and you can sink currents. But does that mean I can connect the negative side of the coin-cell to an output, and sink it? This way it should power my arduino's VCC pin through the "digital GND"

It would not be a good idea to use a input pin as they can only sink a maximum of 40mA per pin.

Also, incase any power surges are experienced and it is connected to Vcc if that 5v is exceeded then it could damage your board. It might be a better solution to use the RAW pin even if it does ultimately use more power.

---
Tags: arduino-pro-mini, battery
---


title: Are there fixed connectors for gpio?

text:
# Question
Title: Are there fixed connectors for gpio?
Curently I am using these connectors for my prototype: Ebay link

However, I need something more reliable so I can deliver the prototype to a user without to risk that the cables fall out of their pins. Is there something else to use? I would like to avoid soldering.. :(

# Answer
> 2 votes
Unless you want to replace the headers with something else, which means soldering, then you will be soldering.

The options are:

1. Solder different connectors in the place of the existing headers
2. Remove the existing headers and solder wires directly in their place
3. Get a prototyping shield and solder wires in to that
4. Get a prototyping shield and solder different connectors to it.

Whatever you choose you will be soldering.

Don't be scared of soldering - it's the most basic thing you need to be able to do when you are working with electronics.

# Answer
> 0 votes
The cables you link are supposed to be assembled by *crimping* rather the *soldering*. The risk of them falling out is mostly because the housing are only for a single contact.

If you instead get multi-contact housings the width of the headers you are matching, and insert contacts into those in the desired positions, the risk of things falling out will be greatly reduced. You can add a label to indicate correct insertion direction.

Of course, a much better result would be to make either a custom shield with terminations for the signals you need to route elsewhere, or to replace the Arduino itself with a custom ATmega board that handles application-appropriate polarity-keyed wiring harnesses.

---
Tags: arduino-uno, mechanical
---


# Question
Title: Digital input pin voltage treshold (voltage to register 1 or 0)
I was thinking of using multiple analog light sensors (variable resistance by light), but basically I only need to know if there is "a lot of light" or "not a lot of light". And would like to use interrupts.

Since I'm using multiple analog inputs, I can't set the ADC module to interrupt on a specific voltage, for each of the (5?) sensors? I'd like to do this withouth using a external comparator.

I've checked the ATMega328p datasheet (going to use Arduino Nano probably).

The fun thing, however, is that on 5V a high signal is \>2.6V and a low signal is \<2.2V

What does this mean for the grey area? Would my inputs be glitching randomly? Would they maintain high, until below 2.2V and maintain low until above 2.6V? Or can the switching point be any where between that (and is it different per chip or pin?

*EDIT: I've checked, my voltage divider circuit has 0.6V for "nothing" and 3V for "interrupted", so it should work neverthless. Though, I'm still interested in how the grey threshold area behaves.*

# Answer
> 1 votes
The titles of the graphs are actually saying what happens: the hysteresis.

In other words:

* if the input level is high (greater than 2.6V), it will be considered high through the hysteresis area (until it goes below 2.2V)
* if the input level is low (below 2.2V), it will be considered low through the hysteresis area (until it goes above 2.6V)

According to the description you gave, this should work for your case. In case it doesn't, you have to condition it until the values you want to consider 0 and 1 are respectively below 2.2V and above 2.6V, with a safety margin, for good measure (say 30%).

The hysteresis is meant to prevent noise from causing unwanted spurious transitions: without safety margin, it should be greater than 0.4V.

You can dimension the safety margin to meet your needs.

But, for the sake of completeness, I'll say that it might be preferable to have a timer to trigger periodic sampling with the ADC.

If you know the maximum frequency at which every input can vary, you can sample it at twice that frequency and be sure that you will not miss anything. Again, this is theory, I would probably make it 4 times, to allow for unforeseen variations.

This works as long as the conversion time of the ADC is shorter than the maximum combined frequency at which you need to read the values.

The GPIOs, of course, are faster, but might require additional circuitry for the conditioning I mentioned earlier.

---
Tags: arduino-nano, input, analog-sampling, digital-in
---


# Question
Title: 'Keyboard' not found when trying to use Keyboard.write from the <Keyboard> library
I am trying to get a response from the arduino when I press a key, but when I try to upload the code it says that it could not find 'Keyboard' with 'Keyboard.write'. Here is my code. Ignore the bits with servo stuff, that is for the project later on. I am using the arduino mega 2560.

```
  #include <Servo.h>
  #include <Keyboard.h>

Servo myservo;
Servo myservo2;

int pos = 0;
int pos2 = 0;
String comdata = "";
int lastLength = 0;

void setup() {
myservo.attach(12);
myservo2.attach(11);
Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}

void loop() {
if (Serial.available() > 0) {
 // read incoming serial data:
 char inChar = Serial.read();
 Keyboard.write(inChar + 1);
}

}

```

# Answer
The Mega2560 can't be a keyboard. It lacks the required hardware.

Instead you need to use one of the pure USB boards, like the Leonardo.
> 1 votes

# Answer
To use USB communication (such as mouse or keyboard) you must have a arduino that uses an ATMEGA32U4. These are so far, the only boards that can work as a USB device.
> 0 votes

---
Tags: serial, arduino-mega, keyboard, input
---


# Question
Title: Find number in a reply returned via serial
I am communicating with my GoPro via ESP8266 and GET requests.
One of the replies returns a set of predefined number and what I would like to do is extract the number on position "38". This is what the reply looks like in full:

```
SEND OK

+IPD,4,163:HTTP/1.1 200 OK
Transfer-Encoding: chunked
Date: Sun, 24 Apr 2016 03:13:40 GMT
Server: Cherokee/1.2.101b150714_bd80061 (UNIX)
Content-type: application/json

OK

+IPD,4,972:3c0
{"status":{
"1":1,"2":1,"3":0,"4":0,"6":0,"8":0,"9":0,"10":0,"11":0,"13":0,"14":0,"15":0,"16":0,"17":1,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"26":0,"27":0,"28":18,"29":"","30":"xxx","31":0,"32":0,"33":0,"34":7933,"35":5039,"36":0,"37":4,"38":0,"39":4,"40":"%10%04%18%03%0D%28","41":0,"42":0,"43":1,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"54":29698976,"55":1,"56":4,"57":1022279,"58":0,"59":0,"60":500,"61":2,"62":0,"63":0,"64":0},
"settings":{"1":0,"2":9,"3":6,"4":1,"5":2,"6":1,"7":1,"8":0,"9":0,"10":0,"11":1,"12":1,"13":1,"14":0,"15":4,"16":0,"17":2,"18":2,"19":2,"20":0,"21":1,"22":2,"23":0,"24":2,"25":0,"26":4,"27":0,"28":2,"29":1,"30":10,"31":0,"32":0,"33":0,"34":1,"35":2,"36":1,"37":2,"38":0,"39":4,"40":0,"41":13,"42":8,"43":0,"44":8,"45":8,"46":0,"47":0,"48":0,"49":0,"50":1,"51":1,"52":0,"53":0,"54":0,"55":1,"56":1,"57":1,"58":1,"59":0,"60":8,"61":1,"62":700000,"63":4,"64":1,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":1}}

0

OK

```

As you can see, position 38=0 (...,"38":0,...). The number 0 will increment. So I would like to find the string `"38":` and do something with following numbers until `,`.
What is the correct way to grab that number from the serial reply and echo or do something with it?

# Answer
Since you are being returned JSON, you can use the jsoncpp library found here To split your return to an array. Then you simply retrieve whatever item you want using array index notation.

Here is another helpful post on creating arrays of strings in C++ from JSON. C++ and JSON
> 0 votes

---
Tags: serial, esp8266, string
---


title: Unidentified constant value

text:
# Question
Title: Unidentified constant value
im working on the following project kalman filter

and im working to implement in arduino.. i read the entire code and i succesfully implemented it into arduino but i couldnt implement the following function code line because arduino gives "not defined" error in **PI\_DIV\_180**

```
imu_MadgwickQuaternionUpdate(bUseAccel,elapsedTimeSecs,fax,fay,faz,fgx*PI_DIV_180,fgy*PI_DIV_180,fgz*PI_DIV_180,fmx,fmy,fmz);

```

it multiplies `fgx` with **PI\_DIV\_180** but as i said arduino cant identify it

i looked into math.h to find the value of that define but there isnt anything in math.h related with this

the `imu_MadgwickQuaternionUpdate` function is in here **IMU.cpp**

can anyone help me please thanx..

# Answer
> 1 votes
Maybe it's pi (π) divided by 180?

Pi is roughly: 3.1415926535898

So:

```
3.1415926535898 / 180 = 0.017453292519943

```

So add this line:

```
#define PI_DIV_180 0.017453292519943

```

---
Tags: arduino-uno, compile, mathematics
---


# Question
Title: Measure different Vcc using 1.1V bandgap
When I power my ATmega328P chip from 5.16V and 3.3V, there doesn't seem to be a single bandgap voltage compensation figure that works for both.

I'm using the following sketch, and I need the following `InternalReferenceVoltage` values to read the correct voltage from `A0`:

* `1255L` to correctly output 5.16V.
* `1358L` to correctly output 3.3V.

I have a couple of questions:

* Should I be able to use a single `InternalReferenceVoltage` compensation value whe powering the ATmega328P from different voltages?
* Aren't both of these values outside the specced 1.0 to 1.2 range?

The code is from, http://forum.arduino.cc/index.php?topic=56750.msg407897#msg407897, retolefty post @ Mar 28, 2011, 02:27 pm.

```
#include <SPI.h>

void setup()
{
  delay(5000);

  Serial.begin(115200);
}

void loop(void)
{
  // Determines what actual Vcc is, (X 100), based on known bandgap voltage
  int battVolts = readVcc1();

  Serial.print("Battery Vcc volts =  ");
  Serial.println(battVolts);
  Serial.print("Analog pin 0 voltage = ");
  Serial.println(map(analogRead(0), 0, 1023, 0, battVolts));
  Serial.println();

  delay(1000);
}

// Returns actual value of Vcc (x 100)
int readVcc1()
{
  uint8_t oldADMUX = ADMUX;

  const long InternalReferenceVoltage = 1255L; // Adjust this value to your boards specific internal BG voltage x1000

#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  // For mega boards
  // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc reference
  // MUX4 MUX3 MUX2 MUX1 MUX0  --> 11110 1.1V (VBG)         -Selects channel 30, bandgap voltage, to measure
  ADMUX = (0 << REFS1) | (1 << REFS0) | (0 << ADLAR) | (0 << MUX5) | (1 << MUX4) | (1 << MUX3) | (1 << MUX2) | (1 << MUX1) | (0 << MUX0);

#else
  // For 168/328 boards
  // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc external reference
  // MUX3 MUX2 MUX1 MUX0  --> 1110 1.1V (VBG)         -Selects channel 14, bandgap voltage, to measure
  ADMUX = (0 << REFS1) | (1 << REFS0) | (0 << ADLAR) | (1 << MUX3) | (1 << MUX2) | (1 << MUX1) | (0 << MUX0);

#endif
  delay(50); // Let mux settle a little to get a more stable A/D conversion
  // Start a conversion
  ADCSRA |= _BV(ADSC);
  // Wait for it to complete
  while (((ADCSRA & (1 << ADSC)) != 0));

  // Scale the value
  int results = (((InternalReferenceVoltage * 1023L) / ADC) + 5L) / 10L; // calculates for straight line value

  ADMUX = oldADMUX;

  return results;
}

```

I have read these other references to try and find a solution:

# Answer
The internal reference won't change much. That's why it's a reference.

Running this code on my Atmega328P:

```
void setup ()
{
  ADMUX = bit (REFS0) | bit (REFS1);  // Internal 1.1V reference
}
void loop () { }

```

That outputs the reference voltage on Aref. I measured it as follows with different values for Vcc:

```
Vcc     Aref
------------
5.00   1.085
4.00   1.081
3.30   1.080
3.00   1.079

```

So you can see that it retains, more or less, the same voltage regardless of Vcc. In any case, there is no way of measuring Aref, unless you have *another* reference voltage around to compare it to.
> 1 votes

---
Tags: atmega328, voltage-level, adc
---


title: ESP8266 blink not building to esp-01

text:
# Question
Title: ESP8266 blink not building to esp-01
I am trying the esp8266 esp-01, and did all it asked on the arduino IDE side, but i am having problems compiling and building the blink example into the board

Using: FT232RL usb-ttl in the 3.3v configuration, two 1.6v (new) batteries to power the esp, and all the conections as indicated here (not using the led though).

when I hit (go) it compiles, but as it transfers both boards blink sincronously and I recive the following errors:

O sketch usa 219.479 bytes (50%) de espaço de armazenamento para programas. O máximo são 434.160 bytes. Variáveis globais usam 31.172 bytes (38%) de memória dinâmica, deixando 50.748 bytes para variáveis locais. O máximo são 81.920 bytes.

error: failed reading byte warning: espcomm\_send\_command: cant receive slip payload data error: failed reading byte warning: espcomm\_send\_command: cant receive slip payload data error: failed reading byte warning: espcomm\_send\_command: cant receive slip payload data error: failed reading byte warning: espcomm\_send\_command: cant receive slip payload data error: failed reading byte warning: espcomm\_send\_command: cant receive slip payload data error: failed reading byte warning: espcomm\_send\_command: cant receive slip payload data error: failed reading byte warning: espcomm\_send\_command: cant receive slip payload data error: failed reading byte warning: espcomm\_send\_command: cant receive slip payload data error: failed reading byte warning: espcomm\_send\_command: cant receive slip payload data warning: espcomm\_sync failed error: espcomm\_open failed error: espcomm\_upload\_mem failed

I looks to me as a newbie that its trying to establish a link and failing... what could it be?

the configurations are default, programmer is "AVRISP MKII"

# Answer
> 1 votes
You did not put ESP8266 into programing mode.

the easiest way to do so is to make your own programing board, something like shown here. Go down to middle of the document to title "Writing a program to the ESP8266" where you will see a schematic of simple programing board. You will need two switches and a 10k resistor.

The voltage regulator can be omitted if you are powering it by 3.3v power. Also its a good idea to put a small capacitor (100uf) between vcc and ground to stabilize any drops in voltage which is primary cause of esp8266 rebooting it self.

---
Tags: esp8266
---