# Question
Title: Set array to array passed as parameter in constructor
I have a constructor which looks like this:

```
Preset::Preset(char* presetName, MIDICommand* MIDICommands[])
  _presetName = presetName;
  _MIDICommands = MIDICommands;
}

```

`_MIDICommnads` is declared like this: `MIDICommand* _MIDICommands[];`.

When run, this throws the error below on the second line in the constructor:

`incompatible types in assignment of 'MIDICommand**' to 'MIDICommand* [0]'`

Why do I need to declare `_MIDICommands` as `MIDICommands**`, and not `MIDICommand* _MIDICommands[]`?

The array I pass is declared like this:

```
MIDICommand* one =  new MIDICommand(1, 2);
MIDICommand* two =  new MIDICommand(2, 2);

MIDICommand* MIDICommandsA[] = { one, two };

```

EDIT: When I pass in an array, should I just use `MIDICommand* MIDICommands`, or do I need the `[]` at the end? Now I've taken them off, but then I get trouble with passing the array.

It doesn't find a matching function to call. Basically, this `MIDICommand* MIDICommandsA[] = { one, two };` doesn't match this `MIDICommand* MIDICommands` parameter.

EDIT 2: So, I've solved the problem of passing the array. I changed the parameter in the constructor to `MIDICommand** MIDICommands`, and I just pass a pointer to the array.

Now the constructor looks like this:

```
Preset::Preset(char* presetName, MIDICommand** MIDICommands)
{
  Serial.println(MIDICommands[0]->getProgramChange());

  _presetName = presetName;
  _MIDICommands = *MIDICommands;

  Serial.println(_MIDICommands[0]->getProgramChange());
}

```

I'm getting an error on the second `Serial.println`, telling me it is a non-pointer type. I'd like it to be a pointer, so that's what I am looking at now.

`_MIDICommands` is now declared like this: `MIDICommand* _MIDICommands`.

EDIT 3: When I try to loop through the array now, it seems I have lost the second element, and have only the first.

# Answer
> 1 votes
> \_MIDICommnads is declared like this: MIDICommand\* \_MIDICommands\[\];.

This is the major error. That is an incomplete array type. The number of elements (and storage) is unknown.

To solve this you have decide on how the elements should be stored. Should the class allocate storage and copy the values given to the constructor or should a pointer to the vector be used.

One alternative is to use a template class and provide the max element size as a template class parameter.

Cheers!

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


# Question
Title: Powering the attiny85 with a separate power source
I have an LED project for which i'm using a 9v power supply. For part of the project I'm using an off the shelf LED driver that is compatible with 9v however I have one LED component that I want to drive with the attiny85 (random blinking pattern), which is not compatible with 9v.

Does it make any sense to power the attiny85 separately with say a 3v coin cell, while allowing my LEDs to draw from 9v? The attiny85 would only be tripping transistors. I assume the attiny85 itself doesn't consume much power so hopefully I wouldn't be changing out the coin cell too often.

I have a couple 5v buck converters on hand but they take up more space than a coin cell would.

P.S. It's a Guy Manuel Daft Punk Helmet.

# Answer
> Does it make any sense...

Well, actually it does make sense and you already rationalize it in your question: less space consumed, expected life time of the coin cell is ok for your intended use case (though you could/should confirm the assumption about power consumption with the AVR's data sheet).

There is nothing wrong in powering the microcontroller with a different voltage than the "power" circuitry, assuming the ground lines are connected and the transistors mentioned are operated in a suitable mode, e.g. open collector/open drain type.
> 1 votes

---
Tags: led, atmel
---


title: Utilizing Array with RGB

text:
# Question
Title: Utilizing Array with RGB
I am trying to create a sketch that utilizes two arrays, one array to hold five buttons as input, assigned to pins, and another array to hold five musical notes. I have attached a RGB LEDs with pull-down resistors and attached a 8 ohms resistor speaker.

The code is as followed:

```
 //Pentatonic Piano
 // C D E G A

 #define NOTE_C   262 //HZ
 #define NOTE_D   294 //HZ
 #define NOTE_E   330 //HZ
 #define NOTE_G   392 //HZ
 #define NOTE_A   440 //HZ

 const int SPEAKER = 9;   //speaker on pin 10
 const int BLED = 10;      //Blue LED on pin 9
 const int GLED = 6;      //Green LED on pin 6
 const int RLED = 5;      //Red LED on pin 3

 int buttonState = 0;

 //Button Array
 int Buttons[]= {11, 8, 7, 4, 3};

 //Tone Note Array
 int Notes[] = {NOTE_C, NOTE_D, NOTE_E, NOTE_G, NOTE_A};

 void setup()
 {
 pinMode(BLED, OUTPUT);
 pinMode(GLED, OUTPUT);
 pinMode(RLED, OUTPUT);
 pinMode(Buttons, INPUT);
 }

 void loop()
 {

   buttonState = digitalRead(Buttons);

   if (buttonState = Buttons[0])
   { tone(SPEAKER, Notes[0]);
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, HIGH);

   }
   else if (buttonState = Buttons[1])
   {tone(SPEAKER, Notes[1]);
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, HIGH);
    digitalWrite(RLED, LOW);
   }
   else if (buttonState = Buttons[2])
   {tone(SPEAKER, Notes[2]);
    digitalWrite(BLED, HIGH);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, LOW);

   }
   else if (buttonState = Buttons[3])
   {tone(SPEAKER, Notes[3]);
    analogWrite(BLED, 127);
    analogWrite(GLED, 0);
    analogWrite(RLED, 127);

   }
   else if (buttonState = Buttons[4])
   {tone(SPEAKER, Notes[4]);
    analogWrite(BLED, 0);
    analogWrite(GLED, 127);
    analogWrite(RLED, 127);

   }

   else
   {
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, LOW);
    noTone(SPEAKER);
   }
 }

```

The problem is no matter what button I press, the RGB only emits a green light and there is absolutely no sound coming from the speaker. I am truly stumped.

# Answer
First, these statements:

```
if (buttonState = Buttons[0])

```

are doing an assignment, not a test for equality. You want:

```
if (buttonState == Buttons[0])
//               ^Notice

```

Next, `pinMode` takes two integers, but you are passing an array. You can use a loop to call `pinMode` multiple times:

```
for (int i = 0; i < sizeof(Buttons) / sizeof(Buttons[0]); i++) {
     pinMode(Buttons[i], INPUT);
}

```

Same goes for `digitalRead()`. You need to read the state for each button:

```
buttonState = digitalRead(Buttons[0]);
if (buttonState == HIGH) {
   ....
}
buttonState = digitalRead(Buttons[1]);
if (buttonState == HIGH) {
   ....
}
//etc

```
> 0 votes

---
Tags: arduino-uno, programming, rgb-led, array
---


title: Data transmission Serial to TCP

text:
# Question
Title: Data transmission Serial to TCP
I am trying to send numeric data using ESP8266 to local network python server. Before that I am collecting data from sensors using Arduino UNO and then send it to ESP using hardware serial.

ESP8266 code:

```
#include <ESP8266WiFi.h>

const char* ssid     = "ssid";
const char* password = "pass";

const char* host = "192.168.1.103";

String serial_data;

WiFiClient client;

void setup() {
  Serial.begin(115200);
  delay(5000);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

   delay(5000);

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections

  const int port = 8888;
  if (!client.connect(host, port))
  {
    Serial.println("connection failed");
    return;
  }

}

void loop() {

  delay(200);

  while(Serial.available() <= 0)
  {
    //wait for arduino serial data
  }

  if(Serial.available()>0)
  {
    // This will send data to client via TCP
    Serial.println("Sent..");
    serial_data = String(Serial.read());
    client.print(serial_data);
  }
}

```

Python Server code:

```
import socket
import sys
from thread import *
from peewee import *

db = SqliteDatabase("data.db")

class post(Model):
    timestamp = DateTimeField()
    current = TextField()

    class Meta:
        database = db

#connecting to database
def initialize_db():
    db.connect()
    db.create_tables([post], safe = True)

initialize_db()

HOST = '192.168.1.103'
PORT = 8888 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

s.listen(10)
print 'Socket now listening'

#keep talking with the client
#Function for handling connections. This will be used to create threads
def clientthread(conn):
    #Sending message to connected client
    conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

    #infinite loop so that function do not terminate and thread do not end.
    while True:

        #Receiving from client
        data = conn.recv(1024)
        print data

        #send data to database
        post.create(
            current = data
        )

        reply = 'OK ->' + data
        if not data:
            break

        conn.sendall(reply)

    #came out of loop
    conn.close()

#keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])

    start_new_thread(clientthread ,(conn,))

s.close()

```

After powering up ESP it successfully connects to server and then simulating arduino esp serial communication I am using serial monitor to send some numbers. Before I send anything server outputs number 240:

```
Connected with 192.168.1.100:26137
240

```

Then I am sending number 1 but on server terminal I get numbers 49 and 13. Sending numbers some 2 - 3 times and no more data are outputted to server terminal. Should I parse data received from serial to some form I can transmit it via TCP or data should be processed on server side?

# Answer
The numbers are ASCII Codes (here is a chart from the Arduino website). 49 is the number 1, and 13 is a carriage return ('\n'). There should be a setting in the bottom right corner of Serial Monitor to change line ending, this should be set to "no line ending." If it is, than `client.print()` must be adding the carriage return, so you will need to remove it in Python. If you are only sending integers, replace

```
serial_data = String(Serial.read());

```

with:

```
serial_data = String(Serial.parseInt());

```

In the Python code I suggest adding a print statement to check if the connection is closed after

```
#came out of loop
    conn.close()

```
> 1 votes

---
Tags: arduino-uno, serial, esp8266, tcpip
---


title: Multiplying the voltage output

text:
# Question
Title: Multiplying the voltage output
I'm working on a project where my arduino is receiving a voltage 0-5V, I need the output to be 10V always. Is there a way to do that?

# Answer
> 1 votes
Assuming the 0-5 Volts is supposed to switch the output, in which case you want a program to control your output, then you will want to use a digital output pin to either switch a relay or a transistor that controls the 10 Volts put out to whatever it is that you are controlling.

Perhaps you want PWM which indicates a transistor circuit. Hard to tell what you want from the way this is worded.

Taking your words literaly, "I need the output to be 10V always" then that simply means hard-wiring to a 10V power supply. ;-)

---
Tags: arduino-uno, voltage
---


title: Voltage transfer

text:
# Question
Title: Voltage transfer
I'm trying to read the battery voltage using Arduino, using a 9V battery. I keep getting the same voltage (4.99). I connected my Arduino to Matlab so I'm only using the command `voltage=readVoltage(a,'pin')`. I'm very new to this, so any help would be appreciated.

# Answer
> 3 votes
Analog inputs on the arduino will measure 5v maximum. If you want to mesure higher voltage you will have to use a voltage divisor circuit (resistors).

---
Tags: arduino-uno, arduino-mega, arduino-nano
---


# Question
Title: How to pass a string pointer to a function
I'm working on a project, where I wish to use pointers. I had a very quick overview of using pointers in C in collage, but I don't know how to use them.

I want that function uses input String (answer) as pointer.

Calling function in setup block

```
void setup() {
    sendCommand("AT+RST\r\n", 5000, DEBUG, "ready");
    sendCommand("AT+CWSAP_CUR=\"mega\",\"password123\",10,3\r\n", 4000, DEBUG, "OK");
}

String sendCommand(String command, const int timeout, boolean debug, String *answer)
{
    String response = "";

    Serial1.print(command); // send the read character to the esp8266

    long int time = millis();

    while ((time + timeout) > millis())
    {
        while (Serial1.available())
        {
            // The esp has data so display its output to the serial window
            char c = Serial1.read(); // read the next character.
            response += c;
        }

        //Waiting for the right answer and breaking a while loop
        if (response.indexOf(*answer) > 0)
        {
            break;
        }

    }

    if (debug)
    {
        Serial.print(response);
    }

    return response;
}

```

# Answer
What you have there are not String objects, but *string literals*. Their type is `const char *`

You should avoid using String objects if at all possible. Instead use character arrays.

To get a character array out of a function it is best to create one outside your function and pass it to the function as one of the parameters. The return value of the function can then be a status value indicating if the call worked or not.
> 2 votes

# Answer
If you want to use the `String` type, have a variable `String rdy="ready";` and pass `&rdy` (the address of the variable). Same with "OK".

I assume you want to use a pointer to avoid copying?

As you are already using C++ techniques (`String` is C++, not C), you might want to consider to pass `rdy` (not a pointer), and to write `const String &answer` in the `sendCommand` parameter list (meaning: reference to a string, which will not be modified), and omit the `*` when using the parameter. Passing references is quite similar to pointers: no copying involved. The additional benefit is that you may even write `sendCommand("AT+RST\r\n", 5000, DEBUG, "ready");` then... the "ready" is automagically converted into a `String`, and passed via reference.
> 1 votes

# Answer
You can pass parameters to functions by reference by value or 'by pointers'.

Passing a parameter by value means that the function has a separate copy of the parameter so this is more expensive in terms of memory. It also means that any changes you make to the parameter inside the function are not reflected outside the function, they are two separate variables after all.

Passing by reference in C/C++ is done by adding a & after the parameter's type, `(int& byRef)`. This means that you are using the same variable inside and outside of the function. If you want to prevent the function changing the value then you set the parameter to be a constant reference. `const int& constByRef`

There is a third method which is passing a pointer. This is very useful for parameters that are a few bytes in size, i.e. strings and structures `char* ptr`. When you pass a pointer it is passed by value, you can modify the pointer or the data it points to. Since a pointer is usually only the word size of the processor it is only as expensive as passing an int parameter.

When you pass a `const char* cPtr` you can not modify the value of the pointer, but you can modify the value of the data pointed to. This type of parameter will let you pass in string literals.

To make you code cleared always write functions to accept constant parameters. If the parameter is larger than a word pass it by reference unless its an array (including char\*) in which case pass it by pointer. If in doubt it should be a constant reference to start with. Sometimes embedded constraints affect these rules.
> 0 votes

---
Tags: pointer
---


# Question
Title: What is the theory behind the Arduino UNO being able to create AM waves at 800 kHz
I am doing a school project and saw someone use an Arduino and a piece of wire as an antenna here: https://forum.arduino.cc/index.php?topic=88422.0

I've tested this experiment and it works, but I have searched the internet for some time now for some background knowledge or theory on why this works, and how does it?

If anyone knows anything about the arduino creating simple AM waves, could you please let me know about it or redirect me to another source.

For some context, in this school project I've got to explain the theory behind creating basic AM waves and amplitude modulation in general, then prove the theory by conducting this experiment which I prove it correct.

# Answer
> 3 votes
Strictly speaking it's not AM, it's OOK (On-Off Keying) which just turns a carrier frequency (800kHz PWM, 50% duty cycle) on and off.

Many cheap 443MHz (eBay) modules do the same thing - turn the carrier frequency on and off.

The presence of the carrier frequency is seen as a logic 1 and the absence as a logic 0.

The fact that it's using PWM to generate a square wave means that the "cleanliness" of the signal will be incredibly horrible. You really want to get the carrier frequency as close to a pure sine wave as possible. A square wave has lots of harmonics at 3x, 5x, 7x, 9x etc the frequency. So your 800kHz signal will also have a 2.4MHz signal, a 4MHz signal, a 5.6MHz signal and so on, each at a lower level. That causes interference in other signals.

To understand more about *why* it works you first have to understand radio transmission theory, and that's not something we can cover on an Arduino site (it's an entire college course all by itself).

# Answer
> 1 votes
It works because everything is wrong. A perfect sine wave of 800 kHz would not transmit very well with such a small wire as antenna.

The output signal is a digital pulse (PWM signal) with very sharp edges. Those edges create many harmonics as Majenko wrote. It is those high harmonic frequencies that can use that small wire as antenna. The receiver might get help of those harmonic frequencies to combine them with the base signal to be able to receive the base signal of 800kHz. The receiver might also receive the electrical field coupling (capacitive coupling) instead of really receiving radio signals. The electrical (capacitive) coupling might even be main part of what is received.

You could add a large antenna or a large open coil or a tuned circuit of a coil with a capacitor. That should increase the range, because that will transmit real radio signals.

The Arduino board with the wire can not be used to explain AM radio signals, because it is not a AM radio signal. You can also not use it to explain AM modulation, because there is no modulation (only on/off). Do you know someone who has equipment to make modulated AM signals ?

Last but not least: it is illegal to transmit at 800kHz.

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


title: Arduino Mega vs servo shield

text:
# Question
Title: Arduino Mega vs servo shield
I am currently designing a hexapod with a total of 18 servos. I come from a computer science background and know little about electronics, so there is one thing which puzzles me. Adafruit is selling this servo shield. It can power up to 16 servos while only using two pins. But it's quite expensive as it would cost me ~30€. Add the cost of an Arduino Uno and you are at \>50€. At the same time I could just buy an Arduino Mega and power all Servos for a lower price.

I like to think that Adafruit wouldn't sell a uselessly overpriced product, so would there be any advantage to using this shield?

Bonus question: If I'd end up buying the shield, could I just power 16 Servos with the shield and 2 via the Arduino? Would there be any problems with that? Like a delay in the 16 motors or similar issues which could through my kinematics over bord? Would I have to buy two shields (which is not really an option at that price)? Any other suggestions I have not heard of are also very welcome!

If it is of any relevance, I am planning to buy these servos as they are pretty strong and come super cheap in bulk.

# Answer
> 3 votes
The idea of that particular servo shield is that it provides 16 PWM (pulse width modulation) channels. These are all operated simultaneously with no additional processing overhead on the Arduino.

The Arduino Uno itself does not offer 16 (or 18) hardware PWM channels but only 6 (see here). So driving 18 servos without an additional shield would require software PWM which requires some of the Arduino's ressources to be devoted doing the calculations. This may or may not interfere with the rest of your program.

Furthermore the Uno does only provide 14 dedicated digital GPIO pins in total (+6 multiplexed digital/analog pins, as ZS6JMB's answer points out), so additional hardware would\* be required either way - or using an Arduino with more pins (such as the suggested Mega). The Mega however offers only 15 hardware PWM channels, leaving you with soft PWM again. (\* assuming some pins will be needed for sensors or user interfacing).

An alternative is this board or, uhm, well, cheaper clones if you like. It features the same chip as the shield but with a PCB half the size and thus skipping the "free use area". I expect it to behave the same way like the shield and operate with the same libraries as the both the shield and this board communicate only via I2C. Both can be chained (or stacked for the shield if you will) for up to 992 PWM outputs (62 boards).

# Answer
> 1 votes
Most of those pen controllers or shields are o.o expanded or own generators. In this case, the resolution maxes out to be just shy of 8 bits.

There are better ways to do it. I can post the link later but I explored quite a few ways to drive multiple servos off of a timer on a pic or avr. The number of servos it can drive is determined by the length of off-duration a servo can tolerate, and number of gpio pins on a mcu.

here is the link: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/

it provides a few examples for its implementation on PIC and AVR. But the basic concept is the same.

No shield used and it runs in the background so it is full transparent to the user code.

# Answer
> 1 votes
I need to correct an earlier poster: the number of PWM pins is irrelevant, since the servo library can control servos on any pins, even analog. That said, the servo library can only control 12 servos, but that has nothing to do with servo pins being PWM or not.

Same poster is also wrong on the number of pins, since the analog pins are fully capable of digital io just like the so-called digital pins. So an Uno has the 14 pins mentioned (0-13, although personally I never include 0 and 1 in that count since life's easier if they are left for serial) and 6 analog pins for a total of 20 (or 18 if you discount the serial Tx and Rx pins).

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


# Question
Title: Not able to add JSON data to Arduino data
In my recent project, I'm working with Arduino with JSON.

I made software on JSON. Now, I want to send data from this software to my Arduino. Serial communication is done between Arduino and JSON. But somehow, I can't able to get proper data from JSON to my Arduino. So, I google out and find library named `ArduinoJson`. And here, I found out example code. So, I tried out that code and modified based on my requirement.

Here, below is my code.

Now, Software sends me value. And I split it out into three variable MAP\_Json, TPS\_Json, and LOAD\_Json. In Arduino side, I have already the value of MAP, TPS, and LOAD.

So, now my main intention is to compare `MAP_Json with MAP` & `TPS_Json with TPS`. If they are matched then `LOAD_Json is added to LOAD`. But, when I try it out, then `LOAD_Json not added to LOAD`. I don't understand why this happened?

```
 #include <ArduinoJson.h>

//----------------------------For MAP calculation----------------------------//
float MAP_MIN = 0.85;
float MAP_MAX = 1.90;

int LOAD_MIN_MAP[] = {1, 2};
int LOAD_MAX_MAP[] = {3, 4};

float mMAP[2] = {};
float yMAP[2] = {};

int i, j, a;
float MAP, mFinalMAP, yFinalMAP;

//----------------------------For TPS calculation----------------------------//
float TPS_MIN = 0.00;
float TPS_MAX = 5.00;

int LOAD_MIN_TPS[] = {1, 3};
int LOAD_MAX_TPS[] = {2, 4};

float mTPS[2] = {};
float yTPS[2] = {};

int k, l, b;
float TPS, mFinalTPS, yFinalTPS;

//----------------------------For LOAD calculation---------------------------//
int LOAD_MIN = 2;
int LOAD_MAX = 100;

float injTime_MIN_LOAD[] = {8.00, 9.06};
float injTime_MAX_LOAD[] = {10.60, 11.86};

float mLOAD[2] = {};
float yLOAD[2] = {};

int m, n, c;
float LOAD, mFinalLOAD, yFinalLOAD;

//------------------------------ Variable ---------------------------------//

float load;

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

void loop()
{
  //----------------------ARDUINO DATA-------------------------//

  //----------------------------MAP----------------------------//

  MAP = analogRead(A0) * (5.0 / 1023.0);

  for(a = 0; a < 2; a++)
  {
    mMAP[i] = (LOAD_MIN_MAP[a] - LOAD_MIN_MAP[a]) / (MAP_MAX - MAP_MIN);
    yMAP[j] = mMAP[i] * (MAP - MAP_MIN) + LOAD_MIN_MAP[a];
  }

  //----------------------------TPS----------------------------//

  TPS = analogRead(A1) * (5.0 / 1023.0);

  for(b = 0; b < 2; b++)
  {
    mTPS[k] = (LOAD_MAX_TPS[b] - LOAD_MIN_TPS[b]) / (TPS_MAX - TPS_MIN);
    yTPS[l] = mTPS[k] * (TPS - TPS_MIN) + LOAD_MIN_TPS[b];
  }

  //----------------TPS/MAP CALLIBRATION / LOAD----------------//

  mFinalTPS = (yMAP[1] - yMAP[0]) / (TPS_MAX - TPS_MIN);
  yFinalTPS = mFinalTPS * (TPS - TPS_MIN) + yMAP[0];

  mFinalMAP = (yTPS[1] - yTPS[0]) / (MAP_MAX - MAP_MIN);
  yFinalMAP = mFinalMAP * (MAP - MAP_MIN) + yTPS[0];

  LOAD = (yFinalTPS + yFinalMAP) / 2;

  Serial.print("T : ");
  Serial.print(TPS);
  Serial.print("\t");
  Serial.print("M : ");
  Serial.print(MAP);
  Serial.print("\t");
  Serial.print("L : ");
  Serial.print(LOAD);
  Serial.print("\t");

  while(!Serial)
  {
    // wait serial port initialization
  }

  StaticJsonBuffer<200> jsonBuffer;

  char json[] = "{\"TPS\":1.67, \"MAP\":1.83,\"LOAD\":30}"; // JSON DATA

  JsonObject& root = jsonBuffer.parseObject(json);

  // Test if parsing succeeds.
  if(!root.success())
  {
    Serial.println("parseObject() failed");
    return;
  }

  // Splitted JSON DATA

  float TPS_Json = root["TPS"];
  float MAP_Json = root["MAP"];
  float LOAD_Json = root["LOAD"];

  Serial.print("T_J : ");
  Serial.print(TPS_Json);
  Serial.print("\t");
  Serial.print("M_J : ");
  Serial.print(MAP_Json);
  Serial.print("\t");
  Serial.print("L_J : ");
  Serial.print(LOAD_Json);
  Serial.print("\t");

  //Compare JSON DATA and ARDUINO DATA

  if(TPS_Json == TPS && MAP_Json == MAP) //If matched
  {
    load = LOAD_Json + LOAD;            // Add LOAD_Json and LOAD
  }

  Serial.print("Final Load :");
  Serial.print(load);
  Serial.print("\n");
}

```

**EDIT 1:** Improve question formatting

**EDIT 2:** Upload Complete code

# Answer
> 2 votes
Comparison of floating point values is nigh on impossible. They aren't as accurate as you may think anyway, and two values have to be precisely the same to be considered equal - not something that is easy to achieve (23.4893782 != 23.4892480).

Instead you should either round them to a specific precision, or take the difference between the two values and decide if they are "close enough".

E.g.:

```
float diff = abs(TPS - TPS_Json);
if (diff < 0.5) {
    // do something
}

```

---
Tags: arduino-uno, json
---


# Question
Title: Measuring the capacitance of 2 capacitors at a time
I need help with my project. In my project, I have two homemade capacitors made from 2 aluminum foil strips separated by a water bottle. I need to detect which bottle is going to become empty as people drink from it. So I plan to use the change in capacitance to detect the empty bottle. I know how to measure capacitance of 1 bottle and detect the change, but I don't know how to do it to 2 bottles at a time. Any ideas how to do this? Here is the following code, I have been working on.

```
// Initialize Pins
int analogPin = 0;
int analogPin1=1;
int chargePin = 13;
int chargePin1=12;
int dischargePin = 11;
int dischargePin1 = 10;

// Initialize Resistor
int resistorValue = 10000;

// Initialize Timer
unsigned long startTime;
unsigned long elapsedTime;

// Initialize Capacitance Variables
float microFarads;
float microFaradr;
float nanoFarads;
float nanoFaradr;

void setup()
{
  pinMode(chargePin, OUTPUT);
  pinMode(chargePin1,OUTPUT);
  digitalWrite(chargePin1,LOW);
  digitalWrite(chargePin, LOW);
  Serial.begin(9600); // Necessary to print data to serial monitor over USB
}

void loop()
{
  digitalWrite(chargePin, HIGH); // Begins charging the capacitor
  digitalWrite(chargePin1,HIGH);
  startTime = millis(); // Begins the timer

  If(analogRead(analogPin)>648){
    elapsedTime= millis() - startTime;
    microFarads = ((float)elapsedTime / resistorValue) * 1000;

    if (microFarads == X) // X is an arbitrary capacitance when the bottle is empty and X is not a variable
    {
      Serial.println(" Bottle A is empty");
    }

    digitalWrite(chargePin, LOW); // Stops charging capacitor
    pinMode(dischargePin, OUTPUT);
    digitalWrite(dischargePin, LOW); // Allows capacitor to discharge
    while(analogRead(analogPin) > 0)
    {
      // Do nothing until capacitor is discharged
    }
    pinMode(dischargePin, INPUT); // Prevents capacitor from discharging
  }

  If(analogRead(analogPin1)>648){
    elapsedTime= millis() - startTime;
    microFaradr = ((float)elapsedTime / resistorValue) * 1000;

    if (microFaradr == Y) // Y is an arbitrary capacitance when the bottle is empty and Y is not a variable
    {
      Serial.println(" Bottle B is empty");
    }

    digitalWrite(chargePin1, LOW); // Stops charging capacitor
    pinMode(dischargePin1, OUTPUT);
    digitalWrite(dischargePin1, LOW); // Allows capacitor to discharge
    while(analogRead(analogPin1) > 0)
    {
      // Do nothing until capacitor is discharged
    }
    pinMode(dischargePin1, INPUT); // Prevents capacitor from discharging
  }
}

```

# Answer
Before we get started, there are a few problems with your code.

First, I wouldn't check for `==648` or `==0`: what if you miss it by a moment and it jumps to 649, or it doesn't quite discharge to 0v? I'd use `>=648` and `<=2` (or some other similarly low number - experimentation required).

How is your circuit connected? I can't quite get my head around the charge and discharge pins, but I'll stick with what you have, assuming it works.

You say you want measurements every 30s, but don't say how long they take. (I have no idea of the capacitance of your bottle.) My code assumes it takes much less than 30s to measure one bottle. If it takes near to 30s to do one, this won't work.

I'll also assume your code works. This is a bad assumption, since it won't even compile (capital `I` in `if`) but regardless, that's what I'll assume.

All that being said, here's the code:

```
// Pins connections
int analogPinA = 0;
int analogPinB = 1;
int chargePinA = 13;
int chargePinB = 12;
int dischargePinA = 11;
int dischargePinB = 10;

// Resistor being used
int resistorValue = 10000;

void setup()
{
  pinMode(chargePinA, OUTPUT);
  pinMode(chargePinB, OUTPUT);
  digitalWrite(chargePinA, LOW);
  digitalWrite(chargePinB, LOW);
  pinMode(dischargePinA, OUTPUT);
  pinMode(dischargePinB, OUTPUT);
  digitalWrite(dischargePinA, LOW);
  digitalWrite(dischargePinB, LOW);
  Serial.begin(9600);
}

// Measure the capacitance of specified capacitor
float measureCapacitance(int analogPin, int chargePin, int dischargePin)
{
    // Ensure the capacitor is discharged
    digitalWrite(dischargePin, LOW);
    while (analogRead(analogPin)>2) { /* Do nothing */ }
    pinMode(dischargePin, INPUT);

    // Start charging
    unsigned long startTime = millis();
    digitalWrite(chargePin, HIGH);

    // Wait for the capacitor to charge
    while (analogRead(analogPin)<=648) { /* Do nothing */ }
    unsigned long endTime = millis();

    // Start it discharging again, ready for next time
    pinMode(dischargePin, OUTPUT);
    digitalWrite(dischargePin, LOW);

    // Calculate measured capacitance
    unsigned long elapsedTime = endTime - startTime;
    float microFarads = ((float)elapsedTime / resistorValue) * 1000;
    return microFarads;
}

void loop()
{
    // Measure capacitance of first bottle
    float microFarads = measureCapacitance(analogPinA, chargePinA, dischargePinA);
    if (microFarads <= X) // X is an arbitrary capacitance when the bottle is empty
    {
      Serial.println("Bottle A is empty");
    }

    // Measure capacitance of second bottle
    float microFarads = measureCapacitance(analogPinB, chargePinB, dischargePinB);
    if (microFarads <= X) // X is an arbitrary capacitance when the bottle is empty
    {
      Serial.println("Bottle B is empty");
    }
}

```
> 1 votes

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


# Question
Title: Smooth out digital signal from SW-420 vibration sensor in order to record duration?
I'm attempting to make a sensor that will record the duration and frequency of a pump going off. It always fires for at least 4 seconds, but the duration can be up to 7 days. The vibration sensor I have is a SW-420, which I think will work. I'm fairly new at this, and I don't mind figuring out the actual code myself, but I'm running into newb problems.

1. Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub? Is there a better solution?
2. Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".
3. The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

Bonus points if I can accomplish this without any additional libraries. I'd love to put this on an ESP8266.

Thanks for your help, I appreciate it.

# Answer
> 1 votes
> Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub?

No. If you want to use interrupts then just record the start time on one edge of the signal and subtract it from the current time on the other edge (not sure which edge is which on that sensor).

> Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".

It depends how you define "close". An RTC can give you better accuracy over long periods, yes, and the Arduino struggles with \> 49 days by itself.

> The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

What kind of frequency are you wanting? The frequency of the vibration itself, or the frequency at which some vibration occurs? If the former the sensor you have won't do the job - that just tells you when there is vibration above a certain threshold.

To sense the actual frequency of vibration you need a more hands-on approach by the MCU. Either use the raw HDX-2 vibration sensor as used on the SW-420 (that's the blue tube at one end), or do it properly and use an accelerometer which you sample over time and perform an FFT on the sampled signal to isolate the different frequencies.

---
Tags: programming, sensors, interrupt, signal-processing, switch
---


title: Getting RFID tag data using C#

text:
# Question
Title: Getting RFID tag data using C#
I am trying to get an RFID tag number using a WinForms application. But whenever I click the Button the application stops responding. Please help regarding this.

Arduino code

```
void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
}

void loop() {
  if(rfid.isCard()) {
    if(rfid.readCardSerial()) {
      Serial.print(rfid.serNum[0], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[1], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[2], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[3], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[4], HEX);
      Serial.println("");
      delay(1000);
    }
  }
  rfid.halt();
}

```

C# code

```
private void button1_Click(object sender, EventArgs e) {
  try {
    serialPort1.Open();
    serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
    textBox2.Text = "connected";
    serialPort1.Close();
  }
  catch(Exception ex) {
    textBox2.Text = "Com port disconnected";
  }
}

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) {
  SerialPort sp = (SerialPort)sender;
  string indata = sp.ReadExisting();
  textBox1.Text = indata;
}

```

# Answer
You are closing the port immediately after you open it. You need to keep it open while you are expecting data. Remove the line

```
serialPort1.Close();

```

Then, in the callback you try to access the GUI from the callback thread. That's not allowed. Use `Invoke()`.

```
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
     SerialPort sp = (SerialPort)sender;
     //string indata = sp.ReadExisting();
     string indata = sp.ReadLine();
     //textBox1.Text = indata;
     Invoke(new Action<string>(
         (s) =>
         {
             textBox1.Text = s;
         }
     ), indata);
}

```
> 1 votes

---
Tags: arduino-uno, rfid, c#
---


title: MAX7219 not behaving as expected

text:
# Question
Title: MAX7219 not behaving as expected
I have 2 rows of 12 MAX7219 connected in series with DOUT to DIN (rows are isolated). Now the thing is I am using `LedControl` Library to work with it. The problem is the last 4 Matrices on both the rows don't work. The sequence in my code is like this where `(row, column, matrix)` is used to define the row and column of the matrix and I am talking about a single ROW from two ROWs of 12.

```
Sequence in Code      What Happens
----------------      -----------------
(0, 1, 0)             (0, 1, 0)
(0, 1, 1)             (0, 1, 9)
(0, 1, 2)             (0, 1, 1)
(0, 1, 3)             (0, 1, 10)
(0, 1, 4)             (0, 1, 2)
(0, 1, 5)             (0, 1, 11)
(0, 1, 6)             (0, 1, 3)
.                     .
.                     .
.                     .
(0, 1, 11)            (0, 1, 8)

```

Now I can understand why does this happens. This code works like this even if the `Device Count` is 8.

Code:

```
#include "LedControl.h"
LedControl row1=LedControl(2,4,3,12);
LedControl row2=LedControl(5,7,6,12);

unsigned long delaytime=500;

void setup() {
  int d_row1 =row1.getDeviceCount();
  for(int address=0;address<d_row1;address++) {
    row1.shutdown(address,false);
    row1.setIntensity(address,15);
    row1.clearDisplay(address);
  }

  int d_row2 =row2.getDeviceCount();
  for(int address=0;address<d_row2;address++) {
    row2.shutdown(address,false);
    row2.setIntensity(address,15);
    row2.clearDisplay(address);
  }
}

void loop() {
  int devices=row1.getDeviceCount();
  for (int i = 0; i < devices; i++){
    delay(delaytime);
    row1.setLed(i,0,0,true);
    row2.setLed(i,0,0,true);
    delay(delaytime);
    row1.setLed(i,0,0,false);
    row2.setLed(i,0,0,false);
  }
}

```

**EDIT** I just noticed something, there is no data going to the last 4 matrices. The timings of the blinking of the LEDs on last 4 matrices does not ties correctly (500ms) but it is in fact 250ms (i.e. half time). It means the blinks on last 4 matrices are between pulses of the first 4 matrices.

# Answer
> 1 votes
After fiddling around with various Libraries, I came across this one.

MD\_MAX72XX

It has all the functionalities that I needed with a good Simple Wiki to get you started.

Also it is simple enough that even a noob like me could figure it out.

Regards

# Answer
> 1 votes
Have you checked the wiring between matrices and/or swapped modules in case there is a faulty one in the sequence?

# Answer
> 1 votes
Looking at your library source, it seems the number of devices is clamped at 8. This isn't a hard limit imposed by the chip but rather practical design. SPI, especially at high speeds, can get unreliable when the bus capacitance, related to the cable lengths, gets so high that signals are skewed beyond recognition. Also the buffer in the library used to hold the row data is 64 bytes in size, intended to hold the data for 8 devices with 8 rows each.

You can edit the library to make it support 12 devices though it will require attention to detail like, increasing the buffer to 96 bytes, getting rid of short-circuits within the methods that make sure that no more than 8 devices can be addressed, for-loops, etc.

---
Tags: arduino-uno, led, max7219
---


# Question
Title: Error compiling: expected unqualified id before token {
```
#include <LiquidCrystal.h>
#define trigPin 12              // the trig pin to digital pin 12
#define echoPin 13              // the Echo pin to digital pin 13
#define led 8
#include <Servo.h>
Servo servoMain; // Define our Servo

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600); // Starts the serial communication
  lcd.begin(16, 2);
  servoMain.attach(11); // servo on digital pin 11
}

void loop() {
  servoMain.write(5);  // Turn Servo Left to 5 degrees
  delay(1000); // Wait 1 second
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance < 3) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("PLEASE REFILL!");
    lcd.setCursor(0, 1);
  } else {
    digitalWrite(led, LOW);
  }
  if (distance < 6) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("U May Refill Now");
    lcd.setCursor(0, 1);
  } else {
    digitalWrite(led, LOW);
  }
  if (distance < 8) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Take it easy");
    lcd.setCursor(0, 1);
  }
  if (distance <= 16) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("FULL!!");
    lcd.setCursor(0, 1);
  }
  if (distance > 16 || distance <= 0) {
    Serial.println("Out of range");
  } else {
    Serial.print(distance);
    Serial.println(" cm");
  }
}
delay(1000);

```

} }

# Answer
At line 82 you have the closing bracket of the loop function. Then after that you have:

```
  delay(1000);

}
}

```

Which is invalid.

If you format your code properly it's easy to see. Fix that and it will compile. Will it do what you want is an other question...

```
#include <LiquidCrystal.h>
#define trigPin 12        // the trig pin to digital pin 12
#define echoPin 13        // the Echo pin to digital pin 13
#define led 8
#include <Servo.h>
Servo servoMain; // Define our Servo

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600); // Starts the serial communication
  lcd.begin(16, 2);
  servoMain.attach(11); // servo on digital pin 11

}
void loop()
{
  servoMain.write(5); // Turn Servo Left to 5 degrees
  delay(1000);     // Wait 1 second

  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

  if (distance < 3) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("PLEASE REFILL!");
    lcd.setCursor(0, 1);
  }
  else {
    digitalWrite(led, LOW);
  }

  if (distance < 6) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("U May Refill Now");
    lcd.setCursor(0, 1);
  }
  else {
    digitalWrite(led, LOW);
  }

  if (distance < 8) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Take it easy");
    lcd.setCursor(0, 1);
  }

  if (distance <= 16) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("FULL!!");
    lcd.setCursor(0, 1);
  }

  if (distance > 16 || distance <= 0) {
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
}
delay(1000);

}
}

```
> 1 votes

---
Tags: led, servo
---


title: Measuring voltage from -12 to +12 VDC

text:
# Question
Title: Measuring voltage from -12 to +12 VDC
I'm making a -12 to +12V DC regulated power supply, on which I want to measure voltage and current with Arduino (through a voltage divider, of course).

I'm not sure, how to either detect nor measure negative voltage. I could "detect" it via a Schottky diode, but I'd get about 0.3V voltage drop, but that's not what I want, because any voltage between 0.0V and -0.3V wouldn't be measured. I want also to be able to measure positive and negative voltage on the same Arduino analog input pin.

And furthermore, how to measure current, flowing into both ways? (not an AC current, but will change during operation).

I will make additional PCB for this application, so size and number of components isn't important at all.

# Answer
> 3 votes
## Measuring voltage

Use the following interfacing circuit for measuring voltage:

Resistors R1, R2, R3 (1% tolerance or better recommended) will map the voltage input range (-12 to +12V DC) to an output range that can be read will the Arduino ADC (+0.5 to +4.5V DC, in order to have some slack from the top and bottom end of the ADC range). The actual theoretical input range would be -15 to 15V DC.

The optional (but recommended) Schottky diodes D1 and D2 will protect the Arduino analog IN pin that you connect to Vout from any input under/overvoltage outside the -15 to +15V DC range.

This is the resulting input to output voltage translation curve:

## Measuring current

For measuring current, use a current shunt (i.e., a very low resistance resistor, in the milliohm range) and measure the voltage drop on it via a high input impedance differential amplifier, then sample the output of the amp with the Arduino ADC.

simulate this circuit – Schematic created using CircuitLab

Follow this link to an article in EE Times to learn more about the main options available for current measurements using a shunt.

---
Tags: power, analogread, current, voltage
---


title: Easy bipolar motor control?

text:
# Question
Title: Easy bipolar motor control?
Is here some easy way to control bipolar motor without using any other external devices, drivers or shields? I have small motor from CD-ROM so I expect it's low voltage. By control I mean just turning clockwise and anti-clockwise and speed. I'm looking for easy to make circuit not just direct control from Arduino.

# Answer
> 1 votes
No. You cannot directly drive any bare motor directly from an Arduino without any external components. To do so will damage the Arduino.

You need a motor driver (or at least some transistors and diodes etc) to control the motor.

# Answer
> 1 votes
Taking a guess here, the current this motor requires will be exceeding the safe operation limits of the Arduino's GPIO pins. Furthermore without a flyback diode the voltage spike across the motor (an inductive load) when the current is reduced/switched off might kill the GPIO pin.

You will need a motor driver or transistor with flyback diodes to operate it.

This is a nice tutorial that has it sorted out for a CD ROM brushless motor.

---
Tags: arduino-uno, programming, motor, electronics, electricity
---


# Question
Title: analogRead returning 0 constantly when connected to joystick
What reasons could there be for a joystick to return 0 when using analogRead?

X-pin is connected to AO and y-pin is connected to A1.

VCC is connected to 5V and GRND is connected to GRND.

By default (as in when not using the joystick) the value should be approximately 500, right? Well why is the value then 0? Can this only be a wiring issue?

# Answer
> 1 votes
Follow these steps to identify the problem.

1. Disconnect A0/A1 from Arduino and use a multimeter to check the voltage coming from the joystick X and Y. If it swings from 0 to 5V....the problem is in the Arduino. Check your code and connections. Maybe your wires are damaged?
2. If the voltage is not changing at X and Y pins, disconnect power from the joystick and use a multimeter to check the joystick potentiometer. Check all three terminals in each axis of the joystick. If R is the measured resistance between the two outer pins, then the resistance between the central pin and each of the outer pins should vary from 0 to R depending on the position of the joystick.
3. If there is no problem at all with the joystick readings by potentiometer then the problem has to be on the Arduino side.

# Answer
> 0 votes
Adding an answer after clarification:-

Moving the joystick also failed to produce a valid reading which indicated a wiring issue or incorrect configuration of the Analog `pin` in the Arduino code.

Proven to be a wiring problem

---
Tags: analogread, wires, joystick
---


title: Avoid blocking from bluetooth callbacks

text:
# Question
Title: Avoid blocking from bluetooth callbacks
I'm developing a wearable data logging device. Sensors are sampled at 20Hz, and written to a SD card through a buffer. There is an Android app that could query the status of data collection (size of written files, latest timestamp etc) through bluetooth LE.

```
// timer interrupt 20Hz
// reading sensors to buffer
ISR() {
    int a = analogRead(A0);
    buffer.push(a);
}

void loop(){
    if buffer.isFull() {
        myFile.open("data.csv", FILE_WRITE);
        myfile.print(buffer.getData());
        myFile.close();
    }
}

// possibility of blocking data collection process
RFduinoBLE_onConnect() {
    int freeSpace = SD.vwd()->fileSize();
    // other operations for monitoring data collection process
    RFduinoBLE.sendInt(freeSpace);
}

```

I am worried that long operations inside RFduino callback function might block the data collection process. (freeSpace is an example, I am planning for other useful data for monitoring process). Also, one could repeatedly try to connect to get updated status data.

What is the recommended technique to make sure that data collection process will not be affected?

UPDATE:

The actual usage is that RFduinoBLE\_onConnect will be called every hour or on demand only. On the other hand, I am trying to deal with worst case of someone trying to call onConnect repeatedly. Is there any way to see that if data collection is busy then reject the RFduinoBLE\_onConnect requests?

# Answer
> 1 votes
Well, one easy, but effective improvement is to use 2 buffers for writing data - while you are writing the one full to file, your interrupt can safely push values to the other and then after the other is full, your ISR would go to first one, while the second will be written. So even long open/seek/write/close loop does not get hit by new data arrival.

Then the main problem - RF - I would bet, that the on\_connect() is called from interrupt too, as it is not mentioned anywhere in the loop(). In that case you would like to have it as small and fast as possible. So if you are only providing data, I would collect all the data in the main loop() in some variable (structure, class, what you need), get it thread safe as much as possible (atomic operations, or have two instancies, one actually enabled for the callback, the other opened for filling new data, then pointers to point which is which and just reassigning those pointers in atomic way (means disable interrupts, swich two pointers, enable interrupts - interrupts can wait for time need to two pointers be changed - on other hand you have no chance do anything in main loop (as disabling interrupts), while interrupt is actually running)

So (I know, it is just example, but) you know, that fileSize() is changed only after file is written - so save its value to some (volatile, of course) variable each time you write to the file and use that variable in onConnect.

So more like this (did not tested it, just idea):

```
volatile buffs[2];
volatile actBuff;
// timer interrupt 20Hz
// reading sensors to buffer
ISR() {
    int a = analogRead(A0);
    buffs[actBuff].push(a);
}

volatile int freeSpace;
void loop(){
    if buffs[actBuff].isFull() {
        int fullBuff=actBuff;
        cli();             // disable global interrupts
        actBuff = 1 - actBuff; // switch actual Buffer between 0 and 1
        sei();// enable global interrupts
        // ISR have nice free buffer to fill, we will write and empty the old one
        myFile.open("data.csv", FILE_WRITE);
        myfile.print(buffs[fullBuff].getData());
        myFile.close();
        buffs[fullBuff].empty()
        int tempval = SD.vwd()->fileSize();
        cli();             // disable global interrupts
        freeSpace = tempval;
        sei();// enable global interrupts:
    }
}

// possibility of blocking data collection process
RFduinoBLE_onConnect() {
    // int freeSpace = SD.vwd()->fileSize();
    // do the same trick here // other operations for monitoring data collection process
    RFduinoBLE.sendInt(freeSpace); // use the value from loop
}

```

---
Tags: bluetooth, sd-card
---


title: Button to not run script

text:
# Question
Title: Button to not run script
I'm looking to have a button that, when pressed down, will mean that the script loaded on the Arduino doesn't run. So far I have:

```
void setup() {
  pinMode(3, INPUT_PULLUP);
  if (digitalRead(3) == LOW) {
    while(1);
  }
  // Beginning the Keyboard stream
  Keyboard.begin();
  // then the rest of the code.

```

I have a push button soldered to the ground and 3 pin. Could you see what is wrong with the code?

# Answer
> 1 votes
I would do it this way:

```
void setup () {
    pinMode(3, INPUT_PULLUP);
}
void loop () {
    while (digitalRead(3)==LOW) {}; //do nothing, wait for release button
    // do all my stuff
}

```

or even better I would use some LED to indicate, that the button is pressed (or released) to have some visual state indicator (or another stuff to do while the button is pressed

```
void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    while (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       };
    digitalWrite(13,LOW);
    // do all my stuff
}

```

eventually

```
void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    if (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       while (digitalRead(3)==LOW) {
          // do some other stuff
       };
    digitalWrite(13,LOW); // switch indicator off
    // do my regular stuff
}

```

# Answer
> -1 votes
You need to move the code that checks the button into `loop()`. Put the code that you want to pause in the `if` block.

```
void loop() {
    // Only execute if not pressed
    if (digitalRead(3) != LOW) {
        // Do stuff
    }
}

```

---
Tags: button
---


# Question
Title: How to find the pin map for the LCD 1602 I2C adapter module?
I'm working with I2C to work with my LCD 1602 and the I2C adapter.

This module has 16 pins and I don't know how to communicate with it.

I2C sends 8-bit packets. What are the commands to deal with this module, because it has 16 pins?

This is my current code:

```
void I2C_init(void);
void I2C_start(void);
void I2C_stop(void);
void I2C_tx(uint8_t data);
void I2C_TWSR_Check(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  I2C_init();
  I2C_TWSR_Check();
  I2C_start();
  I2C_TWSR_Check();
  I2C_tx(0x20);
  I2C_TWSR_Check();
}

void loop() {
  uint8_t i;

  for (i = 0; i < 5; i++)
  {
    I2C_tx(0xff);
    I2C_TWSR_Check();
    _delay_ms(500);
  }
}

void I2C_init(void) {
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1 << TWEN);
}

void I2C_start(void) {
  TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
  while (!(TWCR & (1 << TWINT)));
}

void I2C_stop(void) {
  TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
}

void I2C_tx(uint8_t u8data) {
  TWDR = u8data;
  while (!(TWCR & (1 << TWINT)));
}

void I2C_TWSR_Check(void) {
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch (Status)   {
    case 0x08:    // start OK
      Serial.println("Start is OK");
      break;
    case 0x10:    // Re start
      Serial.println("Re start");
      break;
    case 0x18:        // SLA+W OK ACK
      Serial.println("SLA+W OK ACK");
      break;
    case 0x20:        // SLA+W no ACK
      Serial.println("SLA+W no ACK");
      break;
    case 0x28:        // data OK ACK
      Serial.println("data OK ACK");
      break;
    case 0x30:        // data OK no ACK
      Serial.println("data OK no ACK");
      break;
    case 0x38:        // arbitration lost in SLA+W or data TX
      Serial.println("arbitration lost in SLA+W or data TX");
      break;
    default:
      Serial.println("Error");
      break;
  }
}

```

I don't know I get first case working all the time. I can't proceed to sending the data.

This is the most I got from google images: PCF8574 I2C backpacks for HD44780 Compatible LCD Module Arduino Raspberry

# Answer
The ￼tronixstuff page about PCF8574-based backpacks for LCD modules and Arduino (with material that also appears in an instructable) includes a sketch that most likely will work with that backpack.

Once you've identified which I2C library to use, and the appropriate object instantiation, most of the general API description (that is, “the commands to deal with this module”) as shown at arduino.cc's *LCDi2c Library* page and at arduino.cc's *LCD API 1.0* page will apply.

The I2C library-include and the appropriate object instantiation for the backpack shown in your link probably will look much like:

```
#include <LiquidCrystal_I2C.h>
...
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7);

```

For documentation of what the numbers mean, see lines 82 to 90 of LiquidCrystal\_I2C.h:

```
@param      lcd_Addr[in] I2C address of the IO expansion module. [...]
@param      En[in] LCD En (Enable) pin connected to the IO extender module
@param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
@param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
@param      d4[in] LCD data 0 pin map on IO extender module
@param      d5[in] LCD data 1 pin map on IO extender module
@param      d6[in] LCD data 2 pin map on IO extender module
@param      d7[in] LCD data 3 pin map on IO extender module

```

Briefly, 0x27 is the I2C address of the PCF8574 chip on the backpack. Note, if your backpack has a PCF8574A, its address is 0x3F.

The other seven numbers describe which PCF8574 output pin is connected for each designated purpose. Most PCF8574/PCF8574A I2C backpacks are wired the same and numbers 2,1,0,4,5,6,7 are appropriate.

---

*Edit 1:* If you write an LCD-with-backpack library of your own and expect to publish it, it is reasonable to comply with the LCD API mentioned earlier. By using standard interface functions, you will make it possible for users to plug in your library in place of others with the same interface. In addition, the availability of sketches using the LCD API provides you with a range of test material to verify your drivers.

In writing an LCD-with-backpack library, start by solidifying your understanding of each of the parts – LCD and backpack – separately.

**LCD:** Get some HD44780-based LCD units; hook one up using direct wiring or a shield rather than a backpack; install a known-good library and sketch; run tests to verify the wiring. With the wiring known to work, develop an LCD control library. This may require detailed study of the Hitachi HD44780U data sheet or other HD44780 data sheets. The necessary timing for LCD control is picky enough that it would be a fool's errand to not verify the wiring using known-good software before writing your own.

**Backpack:** Plug the 16 pins of a backpack into a breadboard, and attach LED cathodes to all the breadboard pins that connect to PCF8574 output pins. Use appropriate resistors to V+ on the anode sides of the LEDs. Connect the backpack's SDA, SCL, V+, and ground to that of your Arduino. Write simple test software using `Wire.h` calls to send data to the PCF8574, verifying proper operation using the LEDs. This may require detailed study of the Texas Instruments *PCF8574 Remote 8-Bit I/O Expander for I2C Bus* data sheet. Write your PCF8574 control library. Adapt your LCD control software to send data via the PCF8574 library instead of via direct wiring.
> 2 votes

---
Tags: i2c, lcd, avr
---


# Question
Title: Transfer 10-bit via Arduino-to-Arduino SPI protocol
The task I need to accomplish is as follows:

I have an analog/digital converter that sends out a 10-bit signal. This signal needs to be transferred to an Arduino Uno using the SPI protocol. Because the SPI protocol works with a 16 bit pattern I need to expand the incoming signal. The slave Arduino then needs to put out the transferred number in decimal.

I imitated the ADC with another Arduino Uno, setting it as master, but unfortunately at the time I only had one Arduino so I couldn't test my code. Furthermore, I don't really have a clue how to "expand" a 10-bit signal to a 16-bit one. Can someone please explain it to me and have a look at my code?

Code for the master Arduino:

```
#include <SPI.h>
#define SS 10
#define MOSI 11

void setup() {
  pinMode(SS, OUTPUT);
  pinMode(MOSI, OUTPUT);
  SPI.beginTransaction(SPISettings(62500, LSBFIRST, SPI_MODE0));
}

void loop() {
  byte x=0000001101;
  byte y=0011111111;
  digitalWrite(SS,LOW);
  SPI.transfer(x,y);
  digitalWrite(SS,HIGH);
  delay(1000);
}

```

Code for the slave Arduino:

```
#include <SPI.h>
#define SS 10
#define MOSI 11

void setup() {
  pinMode(SS, INPUT);
  pinMode(MOSI, INPUT);
}

void loop() {
  byte x=SPDR;
  byte y=SPDR;
  printf(x,DEC);
  printf(y,DEC);
  delay(1000);
}

```

# Answer
> -1 votes
A byte is only 8 bits, so your code:

```
  byte x=0000001101;
  byte y=0011111111;

```

won't do what you think it does.

A 10 bit value will be stored as an int (which is 16 bits) or 2 bytes.

Assuming it is an int then this will convert it to two bytes.

```
 const int adcData = 0x03FF;  // From ADC
 byte dataToSend[2] = {0, 0}; // Initialise it to zeros
 dataToSend[0] = (adcData & 0xFF00) >> 8;  // didn't really need the bit mask just to make it clearer.
 dataToSend[1] = (adcData & 0x00FF);
 // Now send dataToSend via the SPI bus.

```

To reassemble the data on the otherside:

```
 byte dataReadFromSPI[2];  // Filled with the data read from the SPI
 int adcData = 0;
 adcData = (dataReadFromSPI[0] << 8) | (dataReadFromSPI[1]);

```

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


title: I have a problem uploading blink

text:
# Question
Title: I have a problem uploading blink
I am uncertain what a serial monitor does when I try uploading blink. I get:

```
problem uploading to board avrdude stk500_recv910 programmer is not responding

```

# Answer
> 1 votes
You have probably not chosen the right COM port. Try picking a different COM port, if using USB cable.

---
Tags: arduino-mega
---


# Question
Title: Nano + ESP8266 control pins with REST API
I connected and flashed successfully an ESP8266 module to a Nano. Now I want to control pins values with a REST API, but all the libraries I found are for using standalone ESP8266 modules (without Arduino) or for Arduino with some other modules like CC3000 etc. Can anybody recommend a library please?

# Answer
> 1 votes
You can use Firmata to control the Arduino pins, just having the ESP8266 publish a web page exposing the Firmata operations you desire to expose and sending the user actions to the Arduino via serial using the Firmata protocol.

To make your life easier you can consider your ESP8266 an equivalent of your serial console: everything you write *from* the ESP82667 becomes input data on the console for your Arduino and the other way around.

In Firmata, each command can be read from a generic *Stream*, with `Serial` being the default implementation.

---
Tags: esp8266, arduino-nano, library
---


# Question
Title: How to connect an Arduino to WIFI using an ESP8266
Hi I am trying to make `Arduino Uno` on local network with the help of ESP8266 wifi module.

I tried to search on internet, found mostly they are making `ESP8266` as web server.http://circuits4you.com/2016/12/16/esp8266-web-server-html/

Can anyone help me how to add `Arduino Uno` on network with the help of `ESP8266`.

# Answer
> 3 votes
Sending the following commands to the ESP should get you started:

```
AT+RST                         # Reset
AT+CWMODE=1                    # Set to station-mode as a client
ATE0                           # turn off command echo
AT+CWLAP                       # optional: list access points
AT+CWJAP_DEF="SSID","PASSWORD" # Always connect to this SSID

```

(I made-up the comment syntax; don't try to send those.) The full ESP8266 AT Instruction Set has the complete set of commands and a functional description of each one.

Update:

> ... do I need to connect RX of ESP8266 to RX of Arduino, TX of ESP8266 to TX of Arduino, Ground of Arduino to RESET ?

Rx & Tx must be cross-connected with the corresponding Arduino pins and the ESP's reset pulled high (3.3v).

# Answer
> 1 votes
It depends on how you want to approach it. I know of two options:

1. Use AT commands.
2. Program the ESP.

When you are using AT commands you need to program the Arduino to open a serial line to the ESP (ensuring rx and tx are crossed over). You tell the Arduino to send the AT commands you need to the ESP and wait for each one to be acknowledged. Then the Arduino sends its network data via the serial connection, to the ESP and the ESP will forward it to the network.

You can program the ESP in EXACTLY the same way as you would the Arduino. You could write some code to accept data from the Arduino over either Serial, SPI, I2C or your own proprietary communication method. The ESP has libraries to be a DHCP client, DNS, HTTP client, etc. (most of which you have probably seen already). If you then write a simple application that establishes the connection to the network and then waits for a packet of data from either the Arduino or the network and forwards it as appropriate.

I can't tell you which option is best, because I have never tried either method. I just program the ESP to do everything that the Arduino would have done anyway and simplify the code.

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


# Question
Title: GSM shield 2 - Fully erase memory buffer
I would love to get real developers' input regarding the following issue as I've been spinning my head around it for a while now.

### What I'd like to do

My program receives SMS containing simple instructions. When a SMS is received, the code will run according to the instruction. In the mean time, other SMS can be received by the modem\[1\].

> I would like my program to ignore any instruction received while it was busy doing something, and therefore I'm looking for a way to delete any SMS received before the arduino finished doing what it was doing.

What I'm having trouble with is the `sms.flush()` function. This function is available from the `GSM.h` library, which is bundled with the Arduino IDE by default.

* and here comes the first glitch: the `flush()`function reference page states that it "clears the modem memory of any sent messages once all outgoing characters have been sent". So it seems at first that `flush()` would only work for outgoing messages...
* ...but in the mean time, the official sketch for SMS reception (ReceiveSMS) does indeed use `flush()` to delete received SMS.

So for me, `flush()` really works both for outgoing and received SMS. Am I right?

### What I did

Here is how the program works:

1. The arduino receives a SMS and is asked to light a LED
2. It does as instructed
3. then sends a SMS back saying that the LED is ON.
4. The DeleteSMS function is triggered

Here is the code:

```
void DeleteSMS(){
    int MessageQtt = 0;
    Serial.print(F("["));
    do{
        sms.flush();
        MessageQtt++;
    } while (sms.available() > 0);
    Serial.print(MessageQtt);
    Serial.print(F(" message(s)"));
    Serial.println(F(" have been deleted]\n"));
}

```

This function is therefore called at the end of the Arduino operations. With it, I wanted to force the Arduino to delete not only the first SMS received as well as the one sent back, but also *any SMS received in the mean time*.

But it doesn't work and I can't really find out why.

### My devices

* Arduino UNO
* GSM Shield 2
* local (France) provider SIM card

Thanks all in advance for your input...

(by the way: if someone could tell me where to find the GSM.h file, I could mess with it to see how things work...)

---

\[^1\]: *From what I've learned, any SMS received while the modem is turned off or the Arduino busy doing something else will be stored in the **memory buffer**, but I can't really retrieve my source on that one*.

# Answer
> 0 votes
Well, after many trials, here is the thing: the GSM shield actually can suck up a lot of electric current (up to 2A at full whack).
So, for some functions (connecting to the GSM network, deleting SMS), if you MEGA or UNO is only powered through your computer's USB port, chances are that the whole program will get stuck in a loop waiting for the command to execute.
Good news: if you just plug a 12V power cable even in the middle of the freeze, the program will go on.

So, the bottom line: never try to use the shield without a good powering system.

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


# Question
Title: Press on pressure sensor once, turn on LED for 6 seconds
I am working on a project where I would like to press on a pressure sensor (0-1024) once and turn on the LED and turn off by itself after 6 seconds. I am quite new to arduino and I can't seem to understand how to code this with using a pressure sensor as a switch rather than an actual switch. Any ideas?

# Answer
Sensors which give a range of outputs need to have their outputs processed using a technique called hysteresis. That is, normally, the turn on threshold is higher then the turn off threshold.

For example, the thermostat in your home uses hysteresis when controlling your HVAC system. Otherwise your thermostat would constantly be turning on and off your HVAC system likely causing an early failure.

Here is a stackexchange Arduino question about hysteresis.
> 1 votes

# Answer
If you're having a problem implementing the system in software, there is a hardware approach to do it. The phenomenon is called monostable multivibrator. Monostable mode retains its output for a certain time interval before coming back to previous state. You can use a simple RC circuit configuration to implement this functionality along with Arduino setup. Just interface FSR in voltage divider format, read the voltage and switch another GPIO interfaced with RC circuit configuration.
> 0 votes

---
Tags: arduino-uno, led, timers, millis, pressure
---


# Question
Title: Combining code for two sensors in one programming
We need to read two readings of Humidity and Temperature from 2 different locations. We can run each of them separately but we don't know how we can make them work simultaneously in one program. We are using a TH02 sensor that we connect to I2C and DHT11 that is connected to one of the Analog port.

We are connecting them to Grove base shield V2, which is on top of Arduino uno wifi.

TH02 Code:

```
 void setup()
{
Serial.begin(9600);        // start serial for output

Serial.println("****TH02_dev demo by seeed studio****\n");
/* Power up,delay 150ms,until voltage is stable */
delay(150);
/* Reset HP20x_dev */
TH02.begin();
delay(100);

/* Determine TH02_dev is available or not */
Serial.println("TH02_dev is available.\n");
}

void loop()
{
float temper = TH02.ReadTemperature();
Serial.println("Temperature: ");
Serial.print(temper);
Serial.println("C\r\n");

float humidity = TH02.ReadHumidity();
Serial.println("Humidity: ");
Serial.print(humidity);
Serial.println("%\r\n");
delay(1000);
}

```

DHT11 Code:

```
byte read_dht11_dat()
{
byte i = 0;
byte result=0;
for(i=0; i< 8; i++){

    while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
    delayMicroseconds(30);

    if(PINC & _BV(DHT11_PIN))
    result |=(1<<(7-i));
    while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
}
return result;
}

void setup()
{
DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

Serial.begin(9600);
Serial.println("Ready");
}

void loop()
{
byte dht11_dat[5];
byte dht11_in;
byte i;
// start condition
// 1. pull-down i/o pin from 18ms
PORTC &= ~_BV(DHT11_PIN);
delay(18);
PORTC |= _BV(DHT11_PIN);
delayMicroseconds(40);

DDRC &= ~_BV(DHT11_PIN);
delayMicroseconds(40);

dht11_in = PINC & _BV(DHT11_PIN);

if(dht11_in){
    Serial.println("dht11 start condition 1 not met");
    return;
}
delayMicroseconds(80);

dht11_in = PINC & _BV(DHT11_PIN);

if(!dht11_in){
    Serial.println("dht11 start condition 2 not met");
    return;
}
delayMicroseconds(80);
// now ready for data reception
for (i=0; i<5; i++)
dht11_dat[i] = read_dht11_dat();

DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
// check check_sum
if(dht11_dat[4]!= dht11_check_sum)
{
    Serial.println("DHT11 checksum error");
}

Serial.print("Current humdity = ");
Serial.print(dht11_dat[0], DEC);
Serial.print(".");
Serial.print(dht11_dat[1], DEC);
Serial.print("%  ");
Serial.print("temperature = ");
Serial.print(dht11_dat[2], DEC);
Serial.print(".");
Serial.print(dht11_dat[3], DEC);
Serial.println("C  ");

delay(2000);
}

```

# Answer
This example combines both codes but uses a single `delay`. If you want readings at two different times you should use two `unsigned long` global variables to store the `millis()` of the last time the functions were called. Then you use an `if` statement to only call `readTH02()` or `readDHT11()` when the last `millis` is less than the `<= current-interval`.

It is better to use `millis` interval checking instead of delays but I have not made significant changes to your code to implement that. Take a look at the Arduino IDE example called `BlinkWithoutDelay` to understand how to use intervals instead of `delay()`

```
void setup()
{
  setupTH02();
  setupDHT11();
}

void loop()
{
  readTH02();
  readDHT11();

  delay(1000);
}

void setupTH02()
{
Serial.begin(9600);        // start serial for output

Serial.println("****TH02_dev demo by seeed studio****\n");
/* Power up,delay 150ms,until voltage is stable */
delay(150);
/* Reset HP20x_dev */
TH02.begin();
delay(100);

/* Determine TH02_dev is available or not */
Serial.println("TH02_dev is available.\n");
}

void readTH02()
{
float temper = TH02.ReadTemperature();
Serial.println("Temperature: ");
Serial.print(temper);
Serial.println("C\r\n");

float humidity = TH02.ReadHumidity();
Serial.println("Humidity: ");
Serial.print(humidity);
Serial.println("%\r\n");
//delay(1000);
}

byte read_dht11_dat()
{
byte i = 0;
byte result=0;
for(i=0; i< 8; i++){

    while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
    delayMicroseconds(30);

    if(PINC & _BV(DHT11_PIN))
    result |=(1<<(7-i));
    while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
}
return result;
}

void setupDHT11()
{
DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

Serial.begin(9600);
Serial.println("Ready");
}

void readDHT11()
{
byte dht11_dat[5];
byte dht11_in;
byte i;
// start condition
// 1. pull-down i/o pin from 18ms
PORTC &= ~_BV(DHT11_PIN);
delay(18);
PORTC |= _BV(DHT11_PIN);
delayMicroseconds(40);

DDRC &= ~_BV(DHT11_PIN);
delayMicroseconds(40);

dht11_in = PINC & _BV(DHT11_PIN);

if(dht11_in){
    Serial.println("dht11 start condition 1 not met");
    return;
}
delayMicroseconds(80);

dht11_in = PINC & _BV(DHT11_PIN);

if(!dht11_in){
    Serial.println("dht11 start condition 2 not met");
    return;
}
delayMicroseconds(80);
// now ready for data reception
for (i=0; i<5; i++)
dht11_dat[i] = read_dht11_dat();

DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
// check check_sum
if(dht11_dat[4]!= dht11_check_sum)
{
    Serial.println("DHT11 checksum error");
}

Serial.print("Current humdity = ");
Serial.print(dht11_dat[0], DEC);
Serial.print(".");
Serial.print(dht11_dat[1], DEC);
Serial.print("%  ");
Serial.print("temperature = ");
Serial.print(dht11_dat[2], DEC);
Serial.print(".");
Serial.print(dht11_dat[3], DEC);
Serial.println("C  ");

//delay(2000);
}

```
> 0 votes

---
Tags: arduino-uno
---


title: #define VS local static const char

text:
# Question
Title: #define VS local static const char
Could someone give me a hint regarding what would be the best practice to save memory: should I `#define` strings or use local `static const char` arrays?

Code example, option #1:

```
#define         LCD_LIMIT   "Number of hours"
...
setup(){
    DisplayData(LCD_LIMIT, actual_Data);
}
...
void DisplayData(const char *theme, String data){
}

```

Code example, option #2:

```
setup(){
    DisplayData(actual_Data);
}
...
void DisplayData(String data){
    static const char theme[] = "Number of hours";
}

```

Cheers

# Answer
> 4 votes
The #define will be substituted in at compile time. So as far as memory usage goes

```
#define MYSTRING "hello world"
DisplayData(MYSTRING);

```

and

```
DisplayData("hello world");

```

are completely identical.

but

```
static const char theme[] = "hello world";
DisplayData(theme);

```

Will store the text in memory and then call DisplayData with a pointer to that memory location. This will require one memory pointers worth of memory extra (unless that is the compiler is being smart that day and realizes it can substitute in the string and save a few bytes).

However if you are using the same string twice or more then things are different.

The static const will only include the string once and then point to it each time, each reference to the string adds only a couple of bytes to the code size. If you #define the string then every time it is referenced the whole string is inserted into the code at a cost of n+1 bytes where n is the string length.

# Answer
> 1 votes
I think they both are similar with respect to memory stored in the heap.

However, since you pass one extra pointer, it cost 2 of 4 bytes extra on the stack (temporary space).

To save more memory use the F() function to store it in FLASH (32 KB on Arduino Uno) instead of the heap (only 2 KB). By using

```
static const char theme[] = F("Number of hours");

```

---
Tags: variables
---


# Question
Title: Serial monitor isn't updating in while loop
I'm trying to make a lamp that fades when it reacts with surrounding light. I've installed a library from github that doesn't require the delay (). The serial monitor doesn't refresh. The lamp is supposed to fade from 0-255 when in the dark and fade 255-0 when in light. It's supposed to happen only once so I can't put it in loop().

The LED is connected to PWM pin 10. The LDR sensor is connected to A0.

```
#include <LEDFader.h>
int sensorvalue = analogRead(A0);
LEDFader led = LEDFader(10);

void setup(){

  if(sensorvalue<=380){
    led.set_value(0);
    led.fade(255, 3000);
  }
  if(sensorvalue>=555){
    led.set_value(255);
    led.fade(0,3000);
  }
}

void loop() {
  Serial.begin(9600);
  Serial.println(sensorvalue);
  led.update();

```

}

# Answer
> 2 votes
Arduino does not work that way. You only try to read a sensor value outside of a function, so will happen once only, if it works at all. You need to read the sensor more often and always read from within a function.

`Serial.begin()` is used once when the code starts, so that will be in the setup()

Your LED fade values are only set one time, when the cpu starts because you have the fade in the `setup()`.

In the following example we do all fade code in the `loop()` but change the fade values only when the sensor reading changes.

```
#include <LEDFader.h>
LEDFader led = LEDFader(10);

int sensorValue = 0;
int sensorValueLast = 0;

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

void loop()
{
  sensorValue = analogRead(A0);
  Serial.println(sensorValue);

        if (sensorValueLast!=sensorValue)
        {
          sensorValueLast = sensorValue;
          if(sensorvalue<=380)
          {
             led.set_value(0);
             led.fade(255, 3000);
          }
          if(sensorvalue>=555)
          {
            led.set_value(255);
            led.fade(0,3000);
          }
        }

  led.update();
}

```

This example only calls `led.fade()` when the sensor value changes but uses the same sensor reading that was found during startup. The sensor is read just once time and the fade values are set just one time.

```
#include <LEDFader.h>
LEDFader led = LEDFader(10);

int sensorValue = 0;
int sensorValueLast = 0;

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

void loop()
{
  sensorValue = analogRead(A0);
  Serial.println(sensorValue);

        if (sensorValueLast!=sensorValue)
        {
          sensorValueLast = sensorValue;
          if(sensorvalue<=380)
          {
             led.set_value(0);
             led.fade(255, 3000);
          }
          if(sensorvalue>=555)
          {
            led.set_value(255);
            led.fade(0,3000);
          }

          led.update();
        }
}

```

This example does everything just one time, when the cpu starts

```
#include <LEDFader.h>
LEDFader led = LEDFader(10);

int sensorValue = 0;

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

   sensorValue = analogRead(A0);
   Serial.println(sensorValue);

          if(sensorvalue<=380)
          {
             led.set_value(0);
             led.fade(255, 3000);
          }
          if(sensorvalue>=555)
          {
            led.set_value(255);
            led.fade(0,3000);
          }

          led.update();

}

void loop()
{
   //we will always see the same value
   Serial.println(sensorValue);
}

```

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


title: How to set alarm on DS3231 sensor?

text:
# Question
Title: How to set alarm on DS3231 sensor?
I want to know if it is possible to set an alarm in DS3231. I want to set the alarm every 6 AM in the morning. Is this possible?

# Answer
> 2 votes
Yes it is (see datasheet datasheet) ... the DS3231 has 2 alarms.

There is also a library for the Arduino, see: library. The alarm(s) can be set (repeatedly) via one of the following functions:

```
Alarm.alarmRepeat(hours, minutes, seconds, function);
Create an alarm that will call a function every day at a particular time.

Alarm.alarmRepeat(dayofweek, hours, minutes, seconds, function);
Create an alarm that will call a function every week on a specific day at
a particular time.

 "dayofweek" can be dowSunday, dowMonday, dowTuesday, dowWednesday,
 dowThursday, dowFriday, or dowSaturday.

```

Detailed info and more functions: link

# Answer
> 0 votes
I find the answer to my question . I just add `Time t;` and `t = rtc.getTime();` into my code then an if statement like this `if (t.hour == 11 && t.min == 59 && t.sec == 00)`

ref http://www.instructables.com/id/Setup-for-DS3231-AlarmTimer-Function/

---
Tags: arduino-uno
---


title: #endif without #if

text:
# Question
Title: #endif without #if
I have an extrange Problem... I have written this short code:

```
////////////// BOARD SETTINGS \\\\\\\\\\\\\\
#define BAUD_RATE 9600

// Board type selection
// Uncomment the wanted
//#define WAND 0
//#define GUN 0
#define RIFLE 0

////////////// WAND SETTINGS \\\\\\\\\\\\\\
#ifdef WAND
//#define USE_CHARGER 0

#endif

////////////// GUN SETTINGS \\\\\\\\\\\\\\
#if GUN
//#define USE_CHARGER 0

#endif

////////////// RIFLE SETTINGS \\\\\\\\\\\\\\
#ifdef RIFLE
  #define USE_CHARGER 0

#endif

```

It's in a file called `Settings.h`, that I use in the main code:

```
#include "Settings.h"

void setup(){
  Serial.begin(BAUD_RATE);
  #ifdef WAND
    Serial.println("Initializing Wand...");
  #endif
  #ifdef GUN
    Serial.println("Initializing Gun...");
  #endif
  #ifdef RIFLE
    Serial.println("Initializing Rifle...");
  #endif
}

void loop(){
  #ifdef WAND

  #endif
  #ifdef GUN

  #endif
  #ifdef RIFLE

  #endif
}

```

But for an extrange reason, it gives me this error: `error: #endif without #if` Full error is:

```
In file included from D:\MEGA\Winsoft\Projects\Hardware\MWands\Arduino_5\Arduino_5.ino:1:0:

Settings.h:15: error: #endif without #if

 #endif

  ^

Settings.h:21: error: #endif without #if

 #endif

  ^

Settings.h:27: error: #endif without #if

 #endif

  ^

exit status 1
#endif without #if

```

Any idea in where am I wrong?

And taking advantage that I'm asking, is necessary the 0 after `#define RIFLE 0`, next to each definition?

# Answer
It looks like your comment style is causing the problem.

Remove the `////////////// BOARD SETTINGS \\\\\\\\\\\\\\` style comments, or change them to something like: `/*----------- BOARD SETTINGS -----------*/`
> 1 votes

# Answer
If you remove backslashes at the end of comments on lines before `#ifdefs`, it will work just fine.

The gvim editor was much more helpful in that:
> 0 votes

---
Tags: arduino-ide
---


title: Arduino Nano Circuit grounding

text:
# Question
Title: Arduino Nano Circuit grounding
I am making an LED circuit for a Lobot (from star wars) costume headset that will not be on a PCB or stripboard. It will all be running inside the walls of the plastic shell I am making. Please see Gif of what I am hoping to do:

## EDIT:

The LEDs will run through 4 different programs. Here is one program as an example:

-Far left and right led pairs will alternate on/off -Single LEDs will blink twice then off for a cycle -The (4) pairs on the left and right will rise and fall like a soundboard -The (3) pairs of white(blue in the demo) will chase bottom to top and back down again

I am new to electronics so I am a little nervous about running the ground wire for it. Here is my circuit:

## EDIT 2:

Here is a reworked diagram based on the suggestions i received below:

The reds were switched to blue for the simulation but will actually be white. So they are 3v each but running in parallel will need 100ohm.

Now that we have that out of the way, is the ground wire run correctly?

The simulation runs perfectly, but I want to make sure that I am not overlooking something important before I try it on my arduino IRL. Is there a neater way to do this? Google searches availed me not. What is the accepted method for this type of circuit?

# Answer
> 1 votes
The schematics is unfortunately somewhat complicated to read as one has to look at the pinout to understand it. When comparing it to the pinout however I find a few things that are odd, e.g. one of the green wires (top, fourth pin from the right) is connected to GND.

Note that the sum of the forward voltages of the LEDs connected in series need to be (significantly) lower than the supply voltage of the Arduino. This forward voltage is different for differing LEDs (depending on the colour). Blue LEDs have a higher voltage (typically 3.0 - 3.5 volts). Connecting two blue LEDs or some more red LEDs in series leads to a necessary forward voltage higher than what the Arduino can provide.

Be sure to add the current limiting resistor for the LEDs in the appropriate places. Due to the non-linear current-voltage characteristic of (light emitting) diodes those resistors are a must-have (unless driving them with a current source, which the Arduinos GPIO pins are not). Do use one resistor per LED or if LEDs are connected in series. Do not use only one resistor for LEDs wired in parallel. For more details on this topic see here.

**Edit to add** (revision of question):

Given 3 V forward voltage and 100 Ohm series resistor one LED presumably leads to a current of about 20 mA. But since you intent to drive two LEDs in parallel (so 40 mA) from each pin, you're well out of spec and hitting Absolute Maximum Ratings:

DC current rating, source:

> DC Current per I/O Pin . . . . . . . . . . . . . . . . . . 20 mA

Absolute Maximum Rating, source

> DC Current per I/O Pin . . . . . . . . . . . . . . . . . . 40.0mA

Furthermore you intend to connect 18 pairs of LEDs (give or take the red LEDs). This would be a total current of 720 mA which is significantly above the limits of the microcontroller. Consider that all the current flowing through the LEDs into the GPIO pins also needs to flow to VCC through the controllers power supply lines (just two pins!). Those have limits too:

Absolute Maximum Rating, source

> DC Current VCC and GND Pins . . . . . . . . . . 200.0mA

You need an external driver (such as the ULN2803, as presented in this answer) or transistors.

# Answer
> 1 votes
I am putting all comments here as answer. Micro, Macro, Nano, Uno, Mega... It doesn't matter, all run at 5V. Your schematics won't work.Ghanima is giving you basic, but MUST components. Also i would suggest to use ULN2803 chips. Easy to use transistors. You won't need to calculate resistors for transistors :D

Additional, your arduino will burn in first few seconds, because the current will be to big. you should not drive LEDs from Arduino.

To make it SUPER COOL i would suggest WS2812B LEDs. They need 5V, GND, and Data in. And you can make it any color you want and control all LEDs separately.

Some video about WS2812B

I would strongly recommend it.

---
Tags: arduino-nano, electricity
---


title: Basic questions on Inputs

text:
# Question
Title: Basic questions on Inputs
I'm completely new to Arduino or even micro-controllers, I'm not even good in physics.

First of all, I'll explain what I am trying to build:

I have an Arduino Nano, for a university project (computer science) I'm trying to make an alternative controller(HID). This controller will be a simple glove, which contains conductive yarn from the Arduino to each finger. If two fingers connect their conductive yarn, I know which fingers are connected and I map this to an input for the computer, which I connected to the Arduino.

For example, if the thumb touches the index finger, it means an `X` on the computer.

To get the code done is not the problem I guess.

Since I'm completely new, I have some pretty basic questions:

1) Can I use the circuit diagram I created or won't it work? Imagine the switches are my hand, which works like a switch.

2) Does my circuit need a connection to 5V and ground, or can one of the pins be a GROUND / 5V?

3) To know if a switch is active, do I have to watch for changes on the pin? For example, the pin is LOW, is it HIGH after the circuit is "closed"?

If you guys can provide me further information for my project or nice tutorials to get in touch with micro-controllers, I would really appreciate it.

Thank you in advance!

# Answer
> 1) Can i use the circuit diagram i created or wont it work?

It won't work. The reason is when the switches are open the input pins are floating and that means they could be `HIGH`or `LOW` or flipping back and forth. You want the pins to be always in a specific state whether the switch is open or closed. To do this a pull-up or pull-down resistor is used. This resistor sets the pin to `HIGH` or `LOW` respectively when the switch is open but the value of the resistor is chosen so that when the switch is closed it overpowers the resistor and the pin reads the opposite state. Since you have your switches connected between the input pin and 5 V you would need to add a pull-down resistor to every pin. That's easy enough but there is an even easier way. The microcontroller on your Nano has internal pull-up resistors you can turn on by doing this:

```
pinMode(inputPin, INPUT_PULLUP);

```

See: https://www.arduino.cc/en/Reference/PinMode

So using the internal pull-ups meas you wouldn't need to add any extra components. But a pull-up isn't helpful if you have your switches connected to 5 V because that would make the pin read `HIGH` whether the switch is opened or closed. So you would need to connect the switches to GND instead. This would mean that the input pin will read `HIGH` when the switch is open and `LOW` when the switch is closed.

> 3) To know if a switch is active do i have to watch for changes on the Pin?

Of course. The easiest way to do this is with `digitalRead()`.

See: https://www.arduino.cc/en/Reference/DigitalRead

You need to make sure your code is non-blocking. When blocking code like `delay()` is used the microcontroller will not be able to check the state of the input pins and so you could miss touches or have the controller not be responsive enough.
> 1 votes

# Answer
When you're dealing with switches, you need to watch out for 'bounce'. This means that a switch is never perfect and when it changes state from ON to OFF or vice versa, usually there are several fluctuations that take place before the switch settles on a final ON/OFF value.

You could debounce your switches by either hardware or software. If you're debouncing your switches by software basically you run a check on each switch to see if it's digital value has stabilised over some finite time period (usually a few milliseconds) and take action on the switch value only AFTER its value has stabilised.

Hardware debouncing makes use of capacitors in your circuit that prevent high frequency fluctuations in the line from reaching your digital pin. Put simply, the capacitor acts like a channel to 'drain' away variations in voltage. If you are implementing hardware debouncing, you can just do a digitalRead() to read your pin.

http://dduino.blogspot.in/2012/03/arduino-button-debouncing.html
> 1 votes

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


# Question
Title: How to make 12V flashing LEDs using an Arduino Uno?
I have 3 LEDs powered by an Arduino; each LED has its own flash rate.

Now I want it to be powered by an external 12V power source and still have the flashing function of the Arduino?

# Answer
> 1 votes
Use a N-channel MOSFET, wire load to drain pin, source to (common) ground, and place a 1 kilo-ohm resistor in series with your arduino pins. Bear in mind that MOSFETs respond to voltage, not milliamps, on the gate - get one that responds well to 5V logic.

# Answer
> 0 votes
Or you could use a relay. Many small ones available for a couple of dollars.

# Answer
> 0 votes
As has been mentioned, you could use an N Channel MOSFET, but preferably look for a Logic Level MOSFET. These are capable of being turned on by lower voltage levels such as on the pins of an Arduino.

Having said that, i have used two non logic level MOSFEt's in Arduino projects successfully. They are the IRF3205 and IRF 520 - both are readily availalable and will work OK with the Arduino output pins for your low-current-driving-an-LED requirement.

---
Tags: arduino-uno
---


# Question
Title: SPP-C and HC-05 are they the same thing or something else?
I was actually thinking to buy a cheap HC-05 module while I was searching I found a similar (think so) module It say it is a replace for HC modules.

Is it compatible with Arduino Nano and will it work same as the HC-05 module ????

# Answer
> 4 votes
In theory they are the same and have the same capabilities. Practically they are not. With SPP-C you get twice the headache for half the price as for HC-05. In had to find it out the hard way Sending data using Bluetooth SPP-C Module without a Breakout-Board. I tried both SPP-C and HC-05 with and without breakout boards finding the same issues. So if you are willing to spend time, risk your project and save some money then use SPP-C. Otherwise use the well known HC-05.

# Answer
> 0 votes
Yes, both the SPP-C and HC-05 are compatible with the Arduino range, and they do work in pretty much the same manner!

---
Tags: bluetooth, hc-05
---


# Question
Title: Can I connect an Arduino Uno Wifi to Arduino Cloud?
Can I connect an Arduino Uno Wifi to Arduino Cloud? If yes, how? If no, what cloud is compatible?

I have tried to look online but I could not find anything that raises this question.

# Answer
> 2 votes
If you sign in to Arduino Cloud the very first thing it asks you is which board you are using. One of the options is the Arduino WiFi Shield 101. That is a shield that you can attach to any Uno-footprint board (including the Uno) to give it encrypted WiFi.

Another option is the Yun shield which turns your Uno into a kind-of Yun.

There are many many other "clouds*" that support Arduino, and many that if you are a reasonable programmer should be simple enough to make work with Arduino, since 99.99% of them all work through some form of HTML-based interface.

---

* Cloud: *n.* An idiotic buzzword used to describe pretty much any website these days.

---
Tags: arduino-uno
---


# Question
Title: How to program Fio v3 without MicroUSB port
I got given a Fio V3 but unfortunately the MicroUSB port is missing, not sure why. Is there any other way to program it? I'm thinking perhaps those 6 pins under the microcontroller?

Also can I still power the board? I notice it doesn't have a VCC or RAW pin like the Pro Micro version. I'm not to worried about using a battery, can I plug any matching voltage into the battery plug?

I tried looking through the schematics and tutorials on Sparkfun but don't really know what I'm looking at. Here are some relevant links anyhow:

# Answer
> 2 votes
The board runs at 3.3V, so you can provide 3.3V directly into the 3.3V pin on the side. Also the black connector next to the USB socket is a battery connection for a Li-Ion battery or similar. It will take any voltage between 3.6V and 5V. Any higher and, according to the schematics, you need to remove the solder link that's just below the battery connector (silver blob). With that link removed you can theoretically go up to 20V on the battery input.

Yes, you can program through the 6-pin header below the main chip if you have a suitable hardware programmer (e.g., USBASP). That is a normal ICSP header like most Arduino boards have.

# Answer
> 0 votes
Looking at the hook up guide might help. https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide

The "best" solution might be to try and get the connector replaced, if the pads are still OK. But soldering those connectors is not an easy task.

The datasheet you linked to is the Lion charger, forget about that PDF.

---
Tags: power, usb, uploading, arduino-micro
---