title: Multiple if statements - stuck

text:
# Question
Title: Multiple if statements - stuck
I have a robot that uses two motors to skid steer. The robot gets input from three ultrasonic sensors (left, middle, and right) and a passive infrared sensor. If the robot detects a person in front of it, then it follows.

The sensors seem to work as they are intended. The infrared sensor sees a person and the ultrasonic sensors see that the person is between 65cm and 150cm and it follows. If the left ultrasonic sensor has the person in range, it turns left, and if the right ultrasonic sensor has the person in range, it turns right.

The problem is that the robot gets stuck turning left or turning right depending on which sensor it checks first in the code. It's like it's stuck in a while loop even though I'm not using a while loop.

I have adapted NewPing and library. The code in question is at the bottom in the last function. The rest is part of NewPing to read the ultrasonic sensors.

If anybody has any suggestions, it would be greatly appreciated.

```
#include <NewPing.h>

#define SONAR_NUM     3 // Number of sensors.
#define MAX_DISTANCE 170 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 35 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
uint8_t currentSensor = 0;          // Keeps track of which sensor is active.

NewPing sonar[SONAR_NUM] = {     // Sensor object array.
  NewPing(11, 4, MAX_DISTANCE), //Left -- Each sensor's trigger pin, echo pin, and max distance to ping.
  NewPing(8, 3, MAX_DISTANCE),  //Center
  NewPing(7, 9, MAX_DISTANCE),  //Right
};

int ledR = 13;
int ledG = 2;
int ledB = A0;
int motorPinL = 5;
int motorPinR = 6;
int ePIR = 10;
boolean epirVal;

void setup() {
  Serial.begin(115200);
  pingTimer[0] = millis() + 75;           // First ping starts at 75ms, gives time for the Arduino to chill before starting.
  for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
    pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
  pinMode (ledR, OUTPUT);
  pinMode (ledG, OUTPUT);
  pinMode (ledB, OUTPUT);
  pinMode (motorPinL, OUTPUT);
  pinMode (motorPinR, OUTPUT);
  pinMode (ePIR, INPUT);
}

void loop() {
  for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
    if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
      pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
      if (i == 0 && currentSensor == SONAR_NUM - 1)
        oneSensorCycle();                             // Sensor ping cycle complete, do something with the results.
      sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
      currentSensor = i;                          // Sensor being accessed.
      cm[currentSensor] = 155;                      // Make distance 155 in case there's no ping echo for this sensor. changed from zero
      sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
    }
  }
  // Other code that *DOESN'T* analyze ping results can go here.
}

void echoCheck() { // If ping received, set the sensor distance to array.
  if (sonar[currentSensor].check_timer())
    cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
}

void allStop () {
  analogWrite (motorPinL, 0);
  analogWrite (motorPinR, 0);
  digitalWrite (ledG, LOW);    //LED corresponding to right ultrasonic sensor
  digitalWrite (ledR, LOW);    //LED corresponding to left ultrasonic sensor
  digitalWrite (ledB, LOW);    //LED corresponding to center ultrasonic sensor
}

```

# Answer
> 1 votes
Your logic is flawed. Translating your loop in pseudocode gives something like this:

```
if (PIR does not detect OR ANY sonar is out of range) {  // cond. 1
    stop
} else if (PIR does detect AND right sonar is in range) {  // cond. 2
    turn right
} else if (PIR does detect AND left sonar is in range) {  // cond. 3
    turn left
} else if (PIR does detect AND center sonar is in range) {  // cond. 4
    go straight
}

```

Notice that, if condition 1 is false, then that means that the PIR does detect AND ALL of the sonars are in range. Which implies that condition 2 is necessarily true. Which implies that the following elses have no effect. Your code can then be optimized (and the compiler probably did optimize it) into

```
if (ANY sonar is out of range OR PIR does not detect) {  // cond. 1
    stop
} else {  // cond. 2 is true if cond 1. is false
    turn right
}

```

You should rethink your problem asking yourself the following questions:

* under what conditions should the robot turn right?
* under what conditions should the robot turn left?
* under what conditions should the robot go straight?
* under what conditions should the robot stop?

Make sure that in any circumstance EXACTLY one of the above conditions holds true. In other words, the conditions should be mutually exclusive and cover every possibility. One you have the answers, the coding should be straightforward.

---

**Edit**: Your updated code still contains logic flaws. For example, if the PIR senses the person and BOTH the left and right sonars are in range, then you are asking the robot to BOTH turn left and turn right. Unless it's a quantum robot evolving in an Everett's multiverse, it won't be able to comply. To the risk of repeating myself, you must decide on one and only one action for every possible situation.

If you are struggling with that concept, I suggest you start by filling the truth table below. On each of the 16 lines of the table you should fill the last column with one (and only one) action among: `allStop`, `turnRight`, `turnLeft` and `straight`. Yes, I know it's tedious to consider all the possible situations one by one, but you *must* do that before starting to write the code. Otherwise you end up with completely broken logic.

```
+--------+----------+----------+----------+-----------+
| PIR    | sonar 0  | sonar 1  | sonar 2  |  robot    |
| senses | in range | in range | in range |  action   |
+--------+----------+----------+----------+-----------+
|  no    |   no     |   no     |   no     |           |
|  no    |   no     |   no     |   yes    |           |
|  no    |   no     |   yes    |   no     |           |
|  no    |   no     |   yes    |   yes    |           |
|  no    |   yes    |   no     |   no     |           |
|  no    |   yes    |   no     |   yes    |           |
|  no    |   yes    |   yes    |   no     |           |
|  no    |   yes    |   yes    |   yes    |           |
|  yes   |   no     |   no     |   no     |           |
|  yes   |   no     |   no     |   yes    |           |
|  yes   |   no     |   yes    |   no     |           |
|  yes   |   no     |   yes    |   yes    |           |
|  yes   |   yes    |   no     |   no     |           |
|  yes   |   yes    |   no     |   yes    |           |
|  yes   |   yes    |   yes    |   no     |           |
|  yes   |   yes    |   yes    |   yes    |           |
+--------+----------+----------+----------+-----------+

```

---
Tags: arduino-uno, sensors, code-optimization
---


# Question
Title: Confusion on array definition at Arduino website
See the below explanation about Arrays from Arduino's official site:

> **Creating (Declaring) an Array**
>
> All of the methods below are valid ways to create (declare) an array.
>
> ```
>   int myInts[6];
>   int myPins[] = {2, 4, 8, 3, 6};
>   int mySensVals[6] = {2, 4, -8, 3, 2};
>   char message[6] = "hello";
>
> ```
>
> You can declare an array without initializing it as in myInts.
>
> In myPins we declare an array without explicitly choosing a size. The compiler counts the elements and creates an array of the appropriate size.
>
> Finally you can both initialize and size your array, as in mySensVals. Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character.

I have the following problems to understand:

1. Isn't `int mySensVals[6] = {2, 4, -8, 3, 2};` wrong? I count 5 elements.
2. Isn't `char message[6] = "hello";` is wrong as well? I count 5 elements.

# Answer
> 3 votes
> 1-) Isn't int mySensVals\[6\] = {2, 4, -8, 3, 2}; wrong? I count 5 elements.

No, not wrong at all. There are 6 elements (as the definition says), and the first five are set to 2, 4, -8, 3 and 2. The sixth is undefined.

> 2-) Isn't char message\[6\] = "hello"; is wrong as well? I count 5 elements.

No. There are 6 there. To quote your quote:

> **Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character.**

So "hello" is actually "hello\0".

---
Tags: code-review
---


title: If-statement gets ignored?

text:
# Question
Title: If-statement gets ignored?
I'm kind of stuck with strange behaviour of my code and I really hope, someone could help me..

**Objective** I'm trying to build a (multiple) magnetic stirring device with which I can either control the speed via potentiometer or via serial commands from a python script from pc (usb). When the speed is set via serial, it shouldn't be possible to interfere with the potentiometer unless a button is pressed to unlock it.

**Code**

```
// Constants

const int FanPin[7] = {2,3,5,6,7,8,9}; // PWM Pins 2,3,5,6,7,8,9 for fan
const int PotiPin[7] = {A0,A1,A2,A3,A4,A5,A6}; // Analoge Pins 0,1,2,3,4,5,6 for potentiometers
const int SwitchPin[7] = {30,31,32,33,34,35,36}; // Digital Pins 30, 31, 32, 33, 34, 35, 36 for switches

// Variables
boolean ManualLock = false; // will be true if locked by serial input
int Fan[7][2] = { // [x][] for number of fan, [][0] for fan speed, [][1] for ManualLock
  {0, ManualLock},
  {1, ManualLock},
  {2, ManualLock},
  {3, ManualLock},
  {4, ManualLock},
  {5, ManualLock},
  {6, ManualLock}
};
int temp = 0; // Variable for temporary data
int FanSpeed[7] = {0,0,0,0,0,0,0}; // Variable fan speed
int PotiVar[7] = {0,0,0,0,0,0,0} ; // Variable for saving poti-input
byte bfr[2] = {7,7}; // Buffer for serial data

void setup() {

TCCR2B = TCCR2B & 0b11111000 | 0x01; // Timer2 (Pin 9, 10) @ 31000Hz
TCCR3B = TCCR3B & 0b11111000 | 0x01; // Timer3 (Pin 2, 3 und 5) @ 31000Hz
TCCR4B = TCCR4B & 0b11111000 | 0x01; // Timer4 (Pin 6, 7 und 8) @ 31000Hz

Serial.begin(9600);
delay(100);

// Declaration of Pin Modes
for (int i = 0; i < 7; i++){
  pinMode(FanPin[i], OUTPUT);
  pinMode(PotiPin[i], INPUT);
  pinMode(SwitchPin[i], INPUT);
  }
}

void loop() {
for (int i = 0; i < 7; i++){
  // ManualLock not active -> manual mode
  if (!Fan[i][1]){
    //Serial.print(i);
    //Serial.println(" ManualLock not active");
    PotiVar[i] = analogRead(PotiPin[i]);
    Fan[i][0] = map(PotiVar[i], 51, 1023, 60, 255);
    //Serial.println(Fan[i][0]);
  }
  //ManualLock active -> unlock by pressing button
  if (Fan[i][1]){
    temp = digitalRead(SwitchPin[i]);
    if (temp == HIGH){
      Serial.print(i);
      Serial.println(" ManualLock will be deactivated");
      Fan[i][1] = false;
      Serial.print("Fan[i][1]: ");
      Serial.println(Fan[i][1]);
    }
  }

  // fan off @ low poti setting
  if (PotiVar[i] < 50){
    Fan[i][0] = 0;
  }
}

// look for serial data

if (Serial.available()){
  Serial.println("Something's there!");
  Serial.readBytes(bfr, 2);
  delay(1000);
  Serial.print("Serial data: ");
  Serial.println(bfr[0]);
//  Serial.flush();
}

//Serial.print("before loop bfr[0]: ");
//Serial.println(bfr[0]);

for (int i = 0; i < 7; i++){
  if (i == int(bfr[0])){
    Serial.print("i: ");
    Serial.println(i);
    Fan[i][0] = int(bfr[1]); //set fan speed variable
    Fan[i][1] = true; // activate ManualLock variable
    byte bfr[2] = {7,7}; // clear buffer
    Serial.print("bfr[0]: ");
    Serial.println(int(bfr[0]));
  }
}

for (int i = 0; i < 7; i++){
  analogWrite(FanPin[i], Fan[i][0]); // write fan speed
  }
}

```

**Error(s)**

When I send a command via my python script, the speed is set correctly and I get the following output:

```
Something's there!
Serial data: 0
i: 0
bfr[0]: 7
i: 0
bfr[0]: 7
...and again and again and again...

```

Which means, although i "reset" my buffer variable to something that should prevent entering the if-statement, it will somehow fulfill the "if (i == int(bfr\[0\]))" condition.. but why? If any further information is needed, i'll happily provide that.

# Answer
> 0 votes
This (inside your `for` loop) does not do what I think you think it does:

```
byte bfr[2] = {7,7}; // clear buffer

```

You think it sets the contents of the `bfr` array you declared at the top to `{7,7}` but what it actually does is declare a new byte array in that scope, containing the values `{7,7}`. It's not used and is immediately thrown away again.

I would expect the compiler to warn about it -- does it? (If so, take it as a lesson not to ignore compiler warnings!)

I think you want to replace it with

```
bfr[0] = 7;
bfr[1] = 7;

```

or something equivalent.

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


title: Comparing two char array

text:
# Question
Title: Comparing two char array
I modified a code which replies `BAR` when I send `FOO`. The problem is the `if else` statement always lands on `else` which prints `Wrong command`. I tried comparing it to string `FOO`(??) and also comparing it to `char` `FOO` with the same buffer size but no joy. This is the code:

```
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

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

WiFiUDP Udp;
unsigned int localUdpPort = 9999;  // local port to listen on
char incomingPacket[255];  // buffer for incoming packets
char command_1[255] = "FOO"; //Tried same buffer size... no luck
char replay_1[] = "BAR";
char wrong[] = "Wrong command";

void setup()
{
  Serial.begin(74880);
  Serial.println();
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
  Udp.begin(localUdpPort);
}

void loop()
{
  int packetSize = Udp.parsePacket();
  if (packetSize)
  {
    int len = Udp.read(incomingPacket, 255);
    if (len > 0)
    {
      incomingPacket[len] = 0;
    }
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(incomingPacket); // Prints the same as from icoming packet which is FOO (Debbuging)
    if (incomingPacket == command_1) { //Tried comparing to same buffer size "FOO" and string "FOO"... no luck
      Udp.write(replay_1);
    }
    else {
      Udp.write(wrong);
    }
    Udp.endPacket();
  }
}

```

# Answer
> 8 votes
You are comparing a `char*` to a `char*`. Array's are contiguous memory locations and the variable name for an array in this case `command_1` and `incomingPacket` point to the first element in the array. Since they are two different array's, the location of the first element in `command_1` is different than the location of the first element in `incomingPacket` so `command_1` will never equal `incomingPacket`.

In order to check if the incoming packet equals "Foo" try

```
if(strcmp(incomingPacket, "Foo") == 0)

```

This utilizes the `strcmp()` compares two null terminated character arrays and returns 0 if they are equal.

Just ensure that the `incomingPacket` is null terminated I have never worked with this library before.

# Answer
> 0 votes
```
> if (incomingPacket == command_1)

```

that statement is testing if pointer incomingPacket is pointing to the same address as pointer command\_1.

to compare strings, you can either use a ready-canned function (if your compiler supports it), or to define your definition of "string equality" and execute it. most likely that requires comparing size first, and the individual characters in the string until a mismatch is found, or you have exhausted one of the strings.

---
Tags: esp8266
---


title: My servo is misbehaving

text:
# Question
Title: My servo is misbehaving
I have been trying to get my 9g tower pro servo to work and no matter what i do nothing happens. I connected the servo to the arduino with the red wire to 5v, brown to ground and orange to pin 6.

```
#include <Servo.h>
Servo myServo;

void setup(){
myServo.attach(6);
}

void loop() {
myServo.write(0);
delay(1000);
myServo.write(60);
}

```

I have been using this code to test it. Another weird occurrence is when i disconnect the servo it sometimes start moving very slowly even though it has now power. I dont think the Uno is broken as other projects work fine on there, are my servos fried?

# Answer
My guess is your drawing too much current from the Arduino 5v rail.

Try connecting the servo to it's own 5v source with of course a common ground with the Arduino.
> 1 votes

# Answer
I found your problem. There is no delay at the end of the loop. So it runs `myServo.write(0)` then pauses for one second then runs `myServo.write(60)` immediately afterwards it starts the loop over and runs `myServo.write(0)` this happens before the servo has time to move.

To fix this add a delay at the end of the loop.

Try:

```
#include <Servo.h>
Servo myServo;

void setup(){
myServo.attach(6);
}

void loop() {
myServo.write(0);
delay(1000);
myServo.write(60);
delay(1000);
}

```
> 0 votes

---
Tags: arduino-uno, servo
---


# Question
Title: How to explain the need/advantage for volatile in terms of microcontroller instruction flow
I know there are already many questions why **volatile** is used when it comes to interrupts.

But explanations like this doesn't help to picture what really happens:

> Specifically, it directs the compiler to load the variable from RAM and not from a storage register, which is a temporary memory location where program variables are stored and manipulated. Under certain conditions, the value for a variable stored in registers can be inaccurate.

Above is from the official Arduino website:

And below is the basic Atmega328 architecture:

*Is it possible to explain the use/advantage of volatile by comparing it to the usual declaration way considering the above architecture?*

I mean such way: If **volatile int x** is used, the CPU fetches this from this by this way ect. And if instead **int x** is used the instruction flow works like this so forth and so on.

Unfortunately I have difficulty to understand from plain two sentence explanations.

As you see my question is about after the compilation what do we observe as a benefit inside the hardware during the instruction flow.

# Answer
> 5 votes
Short answer: **no**, `volatile` cannot be explained in terms of the figure you show in your question.

Longer answer: there is no direct link between the meaning of `volatile` and the architecture depicted in the figure. If you insist in linking them together, it is possible to find a very *weak* and *indirect* link as follows:

1. Volatile is all about preventing the compiler from doing some optimizations when translating your program to assembly. Looking at the generated assembly **can** help understanding the effect of `volatile`.
2. When learning the assembly language, the figure you show is helpful in understanding the assembly instructions themselves.

As you see, the link is indirect, mostly because we are talking about different abstraction levels. Also, the link is weak because the figure describes specifically the AVR architecture, whereas `volatile` applies to any architectures for which there is a C compiler.

To illustrate the first point above, here is an example program which shows the effect of `volatile`:

```
volatile bool volatile_flag;
bool plain_flag;

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

void loop()
{
    Serial.print("Waiting for volatile flag... ");
    while (!volatile_flag) ; /* wait */
    Serial.println("done.");

    Serial.print("Waiting for plain flag... ");
    while (!plain_flag) ; /* wait */
    Serial.println("done.");
}

```

As such, the program is not very interesting, it will just hang on the first loop. But you can imagine there being some ISR that can set the flags when some external event happens. Then the wait loops would start to make sense, as they wait for the external event.

Here is the disassembly of the `loop()` function:

```
    Serial.print("Waiting for volatile flag... ");
  ce:   60 e0           ldi r22, 0x00   ; 0
  d0:   71 e0           ldi r23, 0x01   ; 1
  d2:   82 e5           ldi r24, 0x52   ; 82
  d4:   91 e0           ldi r25, 0x01   ; 1
  d6:   0e 94 b3 02     call    0x566   ; 0x566 <Print::print(char const*)>
    while (!volatile_flag) ; /* wait */
  da:   80 91 51 01     lds r24, 0x0151
  de:   88 23           and r24, r24
  e0:   e1 f3           breq    .-8         ; 0xda <loop+0xc>
    Serial.println("done.");
  e2:   6e e1           ldi r22, 0x1E   ; 30
  e4:   71 e0           ldi r23, 0x01   ; 1
  e6:   82 e5           ldi r24, 0x52   ; 82
  e8:   91 e0           ldi r25, 0x01   ; 1
  ea:   0e 94 d0 02     call    0x5a0   ; 0x5a0 <Print::println(char const*)>
    Serial.print("Waiting for plain flag... ");
  ee:   64 e2           ldi r22, 0x24   ; 36
  f0:   71 e0           ldi r23, 0x01   ; 1
  f2:   82 e5           ldi r24, 0x52   ; 82
  f4:   91 e0           ldi r25, 0x01   ; 1
  f6:   0e 94 b3 02     call    0x566   ; 0x566 <Print::print(char const*)>
    while (!plain_flag) ; /* wait */
  fa:   80 91 50 01     lds r24, 0x0150
  fe:   81 11           cpse    r24, r1
 100:   01 c0           rjmp    .+2         ; 0x104 <loop+0x36>
 102:   ff cf           rjmp    .-2         ; 0x102 <loop+0x34>
    Serial.println("done.");
 104:   6e e1           ldi r22, 0x1E   ; 30
 106:   71 e0           ldi r23, 0x01   ; 1
 108:   82 e5           ldi r24, 0x52   ; 82
 10a:   91 e0           ldi r25, 0x01   ; 1
 10c:   0c 94 d0 02     jmp 0x5a0   ; 0x5a0 <Print::println(char const*)>

```

The important thing to notice is how the compiler implemented the waiting loops. The first one is essentially

```
0:  lds r24, volatile_flag  ; load the flag from RAM
    tst r24                 ; test it
    breq 0b                 ; if zero, loop back

```

whereas the second loop is:

```
    lds r24, plain_flag     ; load the flag from RAM
    cpse r24, r1            ; if zero, skip the following jump
    rjmp 1f                 ; jump over the next loop
0:  rjmp 0b                 ; infinite loop
1:

```

You may appreciate the first loop has been translated to assembly in a very literal way, whereas in the second loop the compiler optimized away all but the first read of the variable. That could be translated back to C as

```
if (!plain_flag) {
    for (;;) ;  // hang in an infinite loop
}

```

The compiler assumed the flag cannot be changed by some external event, so there is no point in reading it repeatedly. The `volatile` keyword prevents the compiler from making such assumption.

And how is all this related to your figure you may ask? Well, if you happened to not understand the assembly code above, you could check the AVR Instruction Set Manual to see what each instruction does, and **that's** when the figure becomes helpful.

# Answer
> 2 votes
Let me explain it like this. Modern compilers **optimize**. They do this to make things run faster. People would complain if they didn't, or switch to another compile that does optimize.

Here's an analogy. Let's say you are wondering how many cats your brother has. You call him up on the phone, and he says "two".

A week later your friend asks how many cats your brother has. You say "I'll call him up and ask him.".

Your friend says "Didn't you do that last week? How many did he have then?"

You reply, "Yeah, that's right. He must still have two cats, right? I've just saved the expense of a phone call!"

Not making the phone call is an **optimization** \- you save time and money by not doing it. However what if your brother now has another cat? Or he gave one away? The information about the number of cats is out of date.

If your brother is a cat dealer, or frequently changes his cat configuration you might say "the number of cats my brother has is **volatile** \- I'll have to call him up again to make sure of the number."

So, if something happens *behind your back* (like in your brother's house - or in a computer program in an ISR) then you need to check again each time. However if you are sure that things haven't changed (eg. in your house you would know if you got a new cat) then you can optimize by not checking each time.

I agree with Gerben's comment on this page. This is nothing to do with the compiler architecture - any more than the number of cats you have depends on the way the house is built.

# Answer
> 0 votes
volatile varaibles are used in Shared variables, because the flow can change whit compiler otimizations. It's important to when you use timer's interrupt in sample.

---
Tags: variables
---


title: I2C communication, wrong response

text:
# Question
Title: I2C communication, wrong response
With reference from http://www.gammon.com.au/i2c I tried the example there. However I am getting the wrong response and readings. At startup the Master will request for slave address. I should get a reading of "8" but I don't get it. Subsequently, A0 on the slave is connected to a miniature solar panel, that I have tested and it is working, however I keep getting a value -1 from it. No doubt I did modify a little bit to suit my inputs not sure if what I did affected the program.

This is the master code:

```
    #include <Wire.h>

const int slaveAddressA = 8;

enum {
  cmd_slaveAddress = 1,
  cmd_read_A0 = 2,
  cmd_read_A1 = 3
};

void sendCommand_toSlaveA (const byte cmd, const int responseSize)
{
  Wire.beginTransmission(slaveAddressA);
  Wire.write(cmd);
  Wire.endTransmission();

  Wire.requestFrom(slaveAddressA, responseSize);
}

void setup() {

  Wire.begin();
  Serial.begin(9600);

  sendCommand_toSlaveA(cmd_slaveAddress, 1);

  if(Wire.available())
    {
     Serial.print ("Slave address is: ");
     Serial.println (Wire.read (), DEC);
    }
  else
    {
     Serial.println ("No response to slave address request");
    }

}

void startupTest() {
  Wire.beginTransmission(slaveAddressA);

}

void loop() {

  int val;

  sendCommand_toSlaveA(cmd_read_A0, 2);
  val = Wire.read();
  val <<= 8;
  val |= Wire.read();
  Serial.print("Value of A0: ");
  Serial.println(val, DEC);

  delay(500);

}

```

This is the slave code:

```
#include <Wire.h>

const byte my_address = 8;

enum{
  cmd_address = 1,
  cmd_read_A0 = 2,
  cmd_read_A1 = 3
};

char command;

void setup() {

  command = 0;

  pinMode (A0, INPUT);
  digitalWrite (A0, LOW);  // disable pull-up
  pinMode (A1, INPUT);
  digitalWrite (A1, LOW);  // disable pull-up

  Serial.begin(9600);

  Wire.begin (my_address);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted
}

void loop(){
  //everything is done using interrupts
}

void receiveEvent(int howMany)
{
  command = Wire.read();
}

void sendSensor (const byte which)
{
  int val = analogRead (which);
  byte buf [2];

    buf [0] = val >> 8;
    buf [1] = val & 0xFF;
    Wire.write (buf, 2);
}

void requestEvent ()
{
  switch (command)
  {
    case cmd_address: Wire.write(0x55); break;   // send slave address
    case cmd_read_A0: sendSensor(A0);   break;   // send A0 value
    case cmd_read_A1: sendSensor(A1);   break;   // send A1 value

   }

}

```

Also I'm wondering if I have to add a "Wire.begin(8);" at the slave program setup. ---------------------------**I would like to know what did I do wrongly?**

**UPDATE**: The 2 boards are now communicating with one another. However, requested address gives a '85' instead of an '8'. As for input A0, for example it should show '700' with a little bit of variant, but now it shows a repeated pattern of e.g '0 0 0 400 500 800 1040 1040 1040 800 500 400 0 0 0'

# Answer
When you send 'buf', how do you know that buf\[0\] is transmitted first and buf\[1\] is transmitted second ? Not long ago a bug in Wire library was fixed and it is now allowed to use multiple Wire.send() in the requestEvent() function. I suggest to send two bytes in sendSensor() in the Slave without using the 'buf'.

When you request the Slave addres, you send 0x55. That is not the Slave address. Do you receive 0x55 ?

It is not needed to remove pullup resistors from the analog input pins. It is also not needed to set the pinMode for those pins. You can use analogRead() without something else.

Did you connect the GNDs ? And did you connect SDA to SDA and also SCL to SCL. Which Arduino boards do you use ? Do you know that you can start the Arduino IDE twice, each connected to a board and each with its own serial monitor. That way you can work on both sketches at the same time. As soon as the Slave is running with Wire.begin(8), the Master can run a i2c\_scanner and it should find I2C address 8. That is the first test to verify that the I2C bus is working.
> 2 votes

---
Tags: arduino-uno, i2c, communication
---


# Question
Title: Setting the sampling rate for timer interrupt
I had performance problems with the data acquisition and after some reading on the web, someone told to define a timer with the frequency I need (50hz):

```
// TIMER 1 for interrupt frequency 50 Hz:
cli(); // Stop interrupts.

TCCR1A = 0; // Set entire TCCR1A register to 0.
TCCR1B = 0; // Same for TCCR1B.
TCNT1  = 0; // Initialize counter value to 0.

// Set compare match register for 50 Hz increments.
OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)
// Turn on CTC mode.
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 64 prescaler.
TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
// Enable timer compare interrupt.
TIMSK1 |= (1 << OCIE1A);

sei(); // Allow interrupts.

```

But with that, I was unable to achieve good performance; I was expecting 50 reading / seconds. Luckily, I've changed for 8 bits prescaler instead of 64 and I've start to get better performance:

```
// Set CS12, CS11 and CS10 bits for 8 prescaler.
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

```

But, honestly, I'm a newbie and I don't understand why!

# Answer
`// = 16000000 / (8 * 50) - 1 (must be <65536)` that `8` in the formula refers to the prescaler. So this formula expect you to have a /8 prescaler. But four lines below you used a /64 prescaler. So your timer runs 6.25 Hz.

When you changed it to /8, you got the correct frequency.
> 2 votes

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


title: Run 2 loops side by side

text:
# Question
Title: Run 2 loops side by side
Let's say I have 2 loops `LED()` and `IR()` with a print statement in my Arduino `loop()` function. Basically I want my `IR()` loop to be always running so that at any point in time I provide a signal to the receiver, it will print something. I currently can only run `LED()` first and then once `LED()` is finished, only then the `IR()` will run. So if I send a signal let's say while `LED()` is running, nothing is showing up. Thanks!

EDIT: **Updated with code**

```
void loop() {
  single_Check(); // delay of 500ms
  if (irrecv.decode(&results)) {   //IR code
     Serial.println(results.value, HEX);
     irrecv.resume();
  }
}

```

The `single_check()` function basically turns on 6 LED one by one and check the voltage of the LED and prints them out. However, this code takes time to finish because I put in `delay(500)`. So only after 500ms, the IR code will run.

# Answer
> 1 votes
Arduino and like Arduino hardware run only a sequential Flow, Because they usually have only one core. For running 2 loops side-by-side you have some solutions.

* A flow to test flags and execute specific code.
* Use a timer
* Use a RealTime OS, like FreeRTOS

try never use delay

# Answer
> 0 votes
Your outer loop needs to only decide whether the IR or the LED needs service. If/when one of them does, call a function that services that device. The service functions should be brief and without delay() calls.

If a service function needs to do something/delay/do something else, it should do it by parts; only do the first something and let the main loop decide when it is time to do the something-else.

If this is all you are doing - two devices and their service routines, you may not need anything more. If you need to extending this to n-devices with n or more service routines, and the servicing is time-based (such as the LED probably is), look the SimpleTimer library. Then your outer loop would only call the timers' .run() function frequently, and the timers routine would take care of calling each service routine when necessary.

You'll probably end up with something like:

```
SimpleTimer Timers;  // set of timers

void setup(){
   // some set-up stuff here
   Timers.setInterval(long 10L, LedService);  // call LedService 100x/sec
}

void loop(){
   Timers.run();
   if( IRTest() )
      IRService();
}

void LedService(void){
   // manage LED here
}

bool IRTest(void){
   // return true if IR needs service
   // or false otherwise
}

void IRService(void){
   // manage IR sensor here
}

```

# Answer
> 0 votes
On Arduino (and on most other micro controllers for what it matters) you **CANNOT** do two things at the exact same time, so forget about *running two loops* in principle.

What you can do is: run two separate piece of code one after the other, fast enough that they *look* to be running in parallel or run one continuously and run the other when an *event* occurs.

In your case the first option is not applicable, so you have to revert to the second option and you are lucky because the event we are talking about is actually handled by the Arduino MCU pretty well: it is called an interrupt.

Arduino Uno (actually the MCU at its core, the ATMega328) is capable of handling interrupts on pins 2 and 3 (so you can have 2 interrupt routines attached at the same time).

Using interrupts you can have a piece of code (the IR related part) being enabled only when pin 2 goes LOW (or HIGH). BEWARE though and use interrupts in the proper way: `millis()` does *NOT* work within an interrupt routine and also nothing else will be enabled while executing the interrupt routing, including counting time (that's the reason `millis()` does not work).

The latter part practically means you should limit your interrupt routine to capture the IR code and return, having the printing being done within the `loop()` function whenever the IR has been decoded.

Hoping all that makes sense to you, here are some references:

interrupts() Interrupts attachInterrupt()

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


# Question
Title: Understanding Soil Moisture Sensor Values
I have soil Moisture sensor inserted into the pot soil, wet in state. (not too damp) and soil moisture sensor is connected to Arduino Mega 2560.

This is the soil moisture sensor I am using:

Soil Moisture Sensor VCC is fed by 4.95 coming from Mega's 5 volt power out and soil moisture signal is connected to A0.

below are the readings

```
+---------------------+-------------------+-----------------------+
| timeStamp           | pot1_soilMoisture | pot1_avg_soilMoisture |
+---------------------+-------------------+-----------------------+
| 2017-01-26 14:31:19 |               825 |                    80 |
| 2017-01-26 14:32:19 |               816 |                    80 |
| 2017-01-26 14:33:20 |               828 |                    83 |
| 2017-01-26 14:34:20 |               826 |                    82 |
| 2017-01-26 14:35:20 |               820 |                    79 |
| 2017-01-26 14:36:20 |               833 |                    83 |
| 2017-01-26 14:37:20 |               463 |                    46 |
| 2017-01-26 14:38:21 |               546 |                    32 |
| 2017-01-26 14:39:21 |               156 |                    26 |
| 2017-01-26 14:40:21 |               157 |                    22 |
| 2017-01-26 14:41:21 |               509 |                    23 |
| 2017-01-26 14:42:22 |               204 |                    25 |
| 2017-01-26 14:43:21 |               226 |                    26 |
| 2017-01-26 14:44:21 |               190 |                    30 |
| 2017-01-26 14:45:22 |              1023 |                    84 |
| 2017-01-26 14:46:22 |               604 |                    83 |
| 2017-01-26 14:47:22 |               773 |                    79 |
| 2017-01-26 14:48:22 |              1023 |                    80 |
| 2017-01-26 14:49:23 |               599 |                    77 |
| 2017-01-26 14:50:23 |               766 |                    82 |
| 2017-01-26 14:51:23 |               579 |                    81 |
| 2017-01-26 14:52:23 |               729 |                    74 |
| 2017-01-26 14:53:24 |              1023 |                    82 |
| 2017-01-26 14:54:24 |               795 |                    80 |
| 2017-01-26 14:55:24 |               651 |                    77 |
| 2017-01-26 14:56:24 |               765 |                    83 |
| 2017-01-26 14:57:25 |              1023 |                    81 |
| 2017-01-26 14:58:25 |                 0 |                    60 |
| 2017-01-26 14:59:25 |               921 |                    30 |
+---------------------+-------------------+-----------------------+
1439 rows in set (0.02 sec)

```

I got three kind of readings of the sensor:

* `pot1_soilMoisture` reading from 825 to 833 is when the sensor was dipped in water.
* `pot1_soilMoisture` reading from 463 to 190-1023 is when soil moisture sensor was in air.
* `pot1_soilMoisture` reading from 604 to last 921 is when soil moisture sensor is in soil. The soil is moist/wet.

I don't understand how to be definitive state of soil with such values?

# Answer
> 2 votes
I had this same problem when I began experimenting with soil moisture readings. I noticed that the readings from the sensor can vary widely when not hooked up correctly, or when other nearby objects are somehow interfering.

For instance when I put a SparkFun breakout similar to yours in dry soil and continuously take readings every 50ms, the signal oscillates from 0 to 50, and simply touching the soil with my finger can affect the signal due to the electricity in my body. If you have a metal pot on a metal table, that could be affecting your readings. There's a lot to consider!

However, once I water the soil and let it soak in, the reading generally becomes much more stable. Below I included a real-time plot using a plant I watered about 24 hours ago. Here's how I set up my soil moisture sensor, including code. The readings are taken every 60s and the plotter repeats the old reading until a new one is taken. There's very little deviation when all connections are secure and the soil moisture is evenly distributed.

In general, the specs for the sensor will inform you on what kind of signal to expect. Based on your sample data I suspect yours is a 10-bit signal from 0-1023, so 800 range means the soil is quite moist. If you *just* watered the plant, then the water content around the sensor will change as it seeps through the soil, leading to fluctuations when measuring. Give the soil a few hours to absorb the moisture and try measuring again.

---
Tags: arduino-mega, sensors
---


# Question
Title: how does a bluetooth on android works and what are the best alternative in saving data receive from bluetooth?
Can anyone confirm this for me although I have tested it myself but when I send a string of data from my android app and send it to arduino say for example `data = bluetoothPort.read();` inside an if statement then when I try to use the `data` in another if statement for example `Serial.print(data);` inside another if statement it will only show a blank line which let me believe that none of the data are saved. also when a receiving a string of data for example a string of abcde and send it to arduino for example `data = bluetoothport.read()` and then `Serial.print(data)` the serial monitor shows abcde as expected but what really happens is data has the value of a then prints then replace by b then print then replace by c then print then replace by d then print then replace by e. Am I wrong or somehow right? are there any work around or parts I need that will make me store data as a whole so that I can use it for other thread or a better code to store string of data?

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

SoftwareSerial bluetoothPort(4,5);
const int RECV_PIN = 12;
const int SEND_PIN = 13;

IRsend irsend;
IRrecv irrecv(RECV_PIN);

decode_results results;
char data;

void setup()
{
   bluetoothPort.begin(9600);
   Serial.begin(9600);
   irrecv.enableIRIn();
}

void loop()
{
   if (bluetoothPort.available() > 0)
   {
       data = bluetoothPort.read(); //received bluetooth data from android
   }

   if(irrecv.decode(&results))
   {
       irreceived(); //received IR code from a remote then sends it to my android
       irsend.sendNEC(data, 32)
   }
 }

 void irreceived()
 {
     Serial.println(results.value, HEX);   //receive value of 489010
     bluetoothPort.println(results.value, HEX); //send value to android
     irrecv.resume();
 }

```

so the above is a simple sketch that receive data from a remote controller then send it to my android app then when I resend it back to my arduino I would like the data to be able to receive all the data instead of saving it per letter/number and also be able to store it for other statement to use.

# Answer
> 0 votes
Serial communications *only consist of one character*. That is what serial is - the sending of one character at a time.

How you then deal with those characters, combining them into strings, interpreting them as numbers, whatever, is completely up to you to program.

There is no such thing as a string in serial communications. There is only the character.

The Arduino API has a few (badly implemented IMHO) helper functions that can get a whole string (kinda), but it is much better (both from a learning perspective and an implementation perspective) to do it yourself.

I have a little tutorial here that may help you get to grips with it.

---
Tags: bluetooth, ir
---


# Question
Title: How to skip the first line and output the second?
My question is related to my previous question. These encoder programs outputs two line per pule/tick.

Here is the part of the code I want to use:

```
void loop()
{
    // Read the status of the inputs
    debouncerA.update();
    debouncerB.update();

    int8_t EncVariation = 0;

    if (debouncerA.rose())
    { // if input A changed from low to high, it was CW if B is high too
        EncVariation = (debouncerB.read()) ? 1 : -1;
    }
    else if (debouncerA.fell())
    { // if input A changed from high to low, it was CW if B is low too
        EncVariation = (debouncerB.read()) ? -1 : 1;
    }
    else if (debouncerB.rose())
    { // if input B changed from low to high, it was CCW if A is high too
        EncVariation = (debouncerA.read()) ? -1 : 1;
    }
    else if (debouncerB.fell())
    { // if input B changed from high to low, it was CCW if B is low too
        EncVariation = (debouncerA.read()) ? 1 : -1;
    }
//
  if (EncVariation != 0) {

        encoder0Pos = encoder0Pos + EncVariation;

        int degs = (encoder0Pos * 6) % 360 ;

        if(degs<0){ degs = 360 + degs; }

        Serial.println (degs);
   }
}

```

For **three** inputs/ticks this outputs like:

6

12

18

24

30

36

But I only need the second ones like:

12

24

36

How can I do that? (I need it to send the relevant data do a PC.)

I spend so long time on it couldnt find any solution.

# Answer
*IF* and only IF you want exactly what you have asked for which is alternate lines not to be output then this is a very crude and quick solution.

Outside of `loop()` add this declaration:

```
bool skipNextLine = true;  // true skips the odd lines, false skips even lines

```

And change the end of your code like this:

```
  if (EncVariation != 0) {
    encoder0Pos = encoder0Pos + EncVariation;
    int degrees = (encoder0Pos * 6) % 360 ;
    if(degrees<0){ deg = 360 + degs; }
    if (!skipNextLine)
    {  // This will skip alternate lines
        Serial.println (deg);
        skipNextLine = true;
    }
    else
    {
        skipNextLine = false;
    }
  }

```
> 1 votes

# Answer
Use a static variable to count loop execution and only prohibit the very first of every 3 counts.
> 0 votes

---
Tags: programming
---


# Question
Title: Does Arduino Tian/LininoOS support Python 3?
I'm using an Arduino Yun running OpenWRT and it only runs Python 2.7.

I need to find a microcontroller+processor+WiFi board that supports Python 3. Does the Arduino Tian work for this, or are there any others?

# Answer
> 1 votes
Yes, run the following

```
opkg update
opkg install python3-base_3.4.3-2_ar71xx.ipk

```

---
Tags: python
---


title: How to add SD card to store data

text:
# Question
Title: How to add SD card to store data
I'm new to Arduino and I was wondering how to add an SD card to Arduino so it can store more code and also store files such as text files.

Is there such a shield, and if so, any suggestions?

# Answer
Take a look at this:

Sparkfun OpenLog
> 0 votes

# Answer
Here's a good tutorial:

https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/intro

This is from adafruit and is for the micro sd card.
> 0 votes

---
Tags: shields, sd-card
---


title: Melzi 2.0 Board Firmware Upload problem

text:
# Question
Title: Melzi 2.0 Board Firmware Upload problem
I'm trying to flash the repetier Firmware to my Prusa i3 3D Printer, which uses Melzi 2.0 board. I uploaded it successfully 2 days ago with same settings but now is failing always.

```
@avrdude -p m1284p -b57600 -c arduino -P COM%x% -e -U flash:w:%filename%.hex
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.02s
avrdude: Device signature = 0x1e9705 (probably m1284p)
avrdude: erasing chip
avrdude: reading input file "newa.hex"
avrdude: input file newa.hex auto detected as Intel Hex
avrdude: writing flash (114266 bytes):
Writing |                                                    | 0% 0.00s
avrdude: stk500_paged_write(): (a) protocol error, expect=0x14, resp=0x64
avrdude: stk500_recv(): programmer is not responding

```

How do I solve this problem?

# Answer
> 1 votes
The Electronics Stackexchange question *avrdude error - stk500\_paged\_write() protocol error* has answers that suggest three different tactics for protocol errors:

• Upgrade the Arduino IDE from 1.00 to 1.05, or install "AVR-GCC Toolchain" via Homebrew;
• Disconnect everything from TX / RX (Arduino digital pins 0 and 1);
• Use shorter or different USB cables, hooked to a USB port on computer instead of on a hub

I've seen dozens of answers here on arduino.stackexchange with such suggestions, as well as webpages elsewhere with ideas like those in an answer to *AVRDUDE Error (Arduino Leonardo)*.

You could go through this list of programmer-is-not-responding arduino.stackexchange questions, and report back on what works and what doesn't:

"avrdude: stk500\_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program,
How do I resolve "avrdude: stk500\_recv(): programmer is not responding"?,
avrdude: stk500\_recv(): programmer is not responding after serial,
avrdude: stk500\_recv(): programmer is not responding + avrdude: stk500\_getsync() attempt 10 of 10: not in sync: resp=0x47,
avrdude: stk500\_rcv :programmer is not responding,
Arduino Nano Update failure - avrdude: stk500\_recv(): programmer is not responding,
avrdude: stk500\_getsync(): not in sync: resp=0x00,
Arduino Uno cannot upload any sketch: avrdude: stk500\_recv(): programmer is not responding,
"avrdude: stk500\_recv(): programmer is not responding" when uploading sketch,
Arduino not working / not uploading \[duplicate\],
Problems uploading sketch to Arduino Due,
FTDI stdk 500k not responding,
Arduino Prototype on Breadboard: "avrdude: stk500\_recv(): programmer is not responding",
Arduino Nano - programmer is not responding,
How do I resolve "avrdude: stk500\_recv(): programmer is not responding"?,
Arduino not in sync unique error,
Arduino nano stopped working,
Not in sync: resp=0x00,
How to troubleshoot the Arduino Mini and Arduino usb2serial?,
Atmega328P-PU: Programmer is not responding,

Note, click the “see more linked questions…” link in the sidebar to get a nice webpage with the above list and the opening lines of each question.

---
Tags: uploading, avrdude, firmware, avr-gcc
---


# Question
Title: Subtraction with doubles returning zero erroneously
I have a function that takes as parameter some doubles and does a subtraction operation on it. However I'm getting a result of 0 when one of the parameter is 0 for some reason.

```
int calcPID(double current, double desired, double k){
  double diff;
  diff = desired - current;
  Serial.print("desired = ");
  Serial.print(desired);
  Serial.print(", current = ");
  Serial.print(current);
  Serial.print(", diff = ");
  Serial.println(diff);
  int r = (int)diff;
  return r;
}

```

Output

```
desired = 250.00, current = 1.69, diff = 248.31
desired = 250.00, current = 0.00, diff = 0.00

```

When the current is 0.00 the result (diff) is also 0.00, when it should be 250. Can someone tell me what's going on?

# Answer
I can't reproduce that.

```
int calcPID(double current, double desired, double k) {
  double diff;
  diff = desired - current;
  Serial.print("desired = ");
  Serial.print(desired);
  Serial.print(", current = ");
  Serial.print(current);
  Serial.print(", diff = ");
  Serial.println(diff);
  int r = (int)diff;
  return r;
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  calcPID (1.69, 250, 42);
  calcPID (0, 250, 42);
}  // end of setup

void loop ()
{
}  // end of loop

```

That gives expected output of:

```
desired = 250.00, current = 1.69, diff = 248.31
desired = 250.00, current = 0.00, diff = 250.00

```

I strongly suspect you are passing NaN (not a number) or Inf (infinity) instead of zero. If you add another test line like this:

```
 calcPID (1.0 / 0, 250, 42);

```

Then you get the result:

```
desired = 250.00, current = inf, diff = inf

```

Now I know you reported getting zero, but earlier versions of the IDE printed 0 for NaN or Inf. I suggested a change to the way the libraries handle that which has been implemented in more recent versions.

Here, for example.

---

If this doesn't answer your question, please post a Minimal, Complete, and Verifiable example \- like I did above.
> 1 votes

# Answer
You are not providing the input values in the correct type:

```
calcPID(0.00, 250, 0.0);

```

will return 0, while

```
calcPID(0.00, 250.0, 0.0);

```

will return 250

**UPDATE**

Here you can get a working test case: it's running on a different processor, so don't expect to behave exactly as the 8bit MCU at Arduino's core.
> 1 votes

# Answer
@Roberto Lo Giacco The difference is, that on Arduino (IDE) are headers for \*.ino done before standard C++ compilation

```
#include <stdio.h> // on *.ino it is done in IDE hidden way
int calcPID(double current, double desired, double k) ; // forward definition, for *.ino it is done in Arduino IDE hidden way
int main()
{
    calcPID (1.69, 250, 42);
    calcPID (0, 250, 42);
    calcPID (0.0, 250.0, 42);
    return 0;
}

int calcPID(double current, double desired, double k) {
  double diff;
  diff = desired - current;
  printf("desired = %5.2f, current = %5.2f, diff = %5.2f, true = %i\n", desired, current, diff, diff > 0);
  int r = (int)diff;
  printf("desired = %5.2f, current = %5.2f, diff = %i, true = %i\n", desired, current, r, r > 0);
  return r;
}

```

This compiles and executes on your machine well a gives correct result same as @Nick Gammon have.

Without the definition `int calcPID(double current, double desired, double k) ;` standard C assumes definition with `ints` and makes different conversions, which leads to your "incorrect" result. So the result depends on forward definition, which Arduino does behind scene. But for \*.cpp and \*.h it may be different, so it would be interesting, how `bakalolo` organized his code.
> 1 votes

---
Tags: teensy
---


# Question
Title: Which timer does Arduino Nano use for each PWM pin?
I'm unable to find which Timer controls each PWM pin (3, 5, 6, 9, 10 and 11) in an Arduino Nano Board (ATmega328). Any guesses?

Thanks in advance,

Eduardo

# Answer
This is a good pinmapping picture of the Nano : www.pighixxx.com/test/portfolio-items/nano/

A timer has sometimes two outputs, A and B. The pins with OC0A and OC0B are timer outputs of Timer0. OC1A and OC1B are Timer1, OC2 and OC2B are Timer2.

Everything is also in the datasheet of the ATmega328P, but that picture is a lot easier.
> 3 votes

---
Tags: arduino-nano, pwm, timers
---


title: MCP23017 and stepper motors

text:
# Question
Title: MCP23017 and stepper motors
I am new to Arduino and programming and I am muddling along with some tutorials, I have a little project I am working on. It's basically an LCD screen with 5 buttons, a simple menu system that will control some stepper motors.

Now I have been able to both program and run the LCD from the Arduino and program and run the stepper motors. This was pretty straightforward due to the abundance of information. Now due to the small number of inputs on the Uno I knew I would need to expand on these so I bought some MCP23017 I/O expander chips.

Setting up the LCD on the MCP23017 was easy enough again due to the lots of tutorials and libraries, but I just cannot figure out how to work a stepper motor via the MCP23017. I am using 28BYJ-48 stepper motors and ULN2003 stepper driver boards. Yes I know cheap and nasty but they are fine for my task.

So I am basically looking for a little help on how to run stepper motors through the MCP23017 chips. I have the wiring and connections set up, just need some help on the programming.

# Answer
I couldn't understand what the problem is, since you already managed to connect an LCD to it... Anyway...

To run a stepper motor you have to first define the control technique. AFAIK there are a few, but the ones I know are

* full step
* rotated full step
* half step
* microstep

Your motor is a unipolar motor. You have to connect the common wire to +5V, the other ones to one transistor of the ULN2003, and each transistor should be directly controlled by one pin. These are called phases (and let's call these PH1, PH2, PH3 and PH4).

Now for the explanation I'll use some tables. In these tables, each row is a step, each column a pin, and if there is a X the transistor should be on during that step.

Now, the full step technique is the simplest one. It consists of four phases:

```
Step PH1 PH2 PH3 PH4
  1   X
  2       X
  3           X
  4               X

```

As you can see, you just have to power each phase through each step. Cycling the steps as 1-2-3-4-1-2-3... will rotate in one sense, 4-3-2-1-4-3-2... in the other.

The rotated full step technique powers two phases at each step:

```
Step PH1 PH2 PH3 PH4
  1   X   X
  2       X   X
  3           X   X
  4   X           X

```

This usually gives a higher current consumption, but also higher torque.

The half step is a mix of the two:

```
Step PH1 PH2 PH3 PH4
  1   X
  2   X   X
  3       X
  4       X   X
  5           X
  6           X   X
  7               X
  8   X           X

```

As you can see, the number of steps per cycle is twice as much. This means that you can increase the accuracy (since a 32 steps/rev motor will now require 64 steps to perform a complete revolution).

The microstepping technique requires a different hardware, since it better controls the current in the phases to further divide each step in different steps.

Anyway, a basic implementation using the MCP23017 and the full step technique can be this one. I used Adafruit's library, but you can change using whatever library you chose or the direct calls you used for the LCD.

```
#include <Wire.h>
#include "Adafruit_MCP23017.h"
Adafruit_MCP23017 mcp1;

const byte PH1 = 0, PH2 = 1, PH2 = 3, PH3 = 4;

const byte phasesTable[][] = {
    { HIGH, LOW,  LOW,  LOW  },
    { LOW,  HIGH, LOW,  LOW  },
    { LOW,  LOW,  HIGH, LOW  },
    { LOW,  LOW,  LOW,  HIGH }
    };

int currentPosition, targetPosition;
unsigned long previousMillis;
const int StepDelayMs = 100; // delay between steps

void setup()
{
    mcp1.begin(0);
    mcp1.pinMode(PH1, OUTPUT);
    mcp1.pinMode(PH2, OUTPUT);
    mcp1.pinMode(PH3, OUTPUT);
    mcp1.pinMode(PH4, OUTPUT);
    currentPosition = -1; // force first update
    targetPosition = 0;
}

void loop()
{
    void updatePosition(); // function prototype
    updatePosition(); // execute the update

    // ----------------------
    // Functional part
    // ----------------------
    // Edit this code according to your application
    // changing the targetPosition variable (DON'T CHANGE
    // the currentPosition variable

    if (currentPosition == targetPosition)
    {
        if (targetPosition == 50)
            targetPosition = 0;
        else
            targetPosition = 50;
    }
}

void updatePosition()
{
    if ((millis() - previousMillis) > StepDelayMs)
    {
        previousMillis += StepDelayMs;

        if (targetPosition != currentPosition)
        {
            if (targetPosition < currentPosition)
                currentPosition--;
            else
                currentPosition++;

            byte phIdx = currentPosition % (sizeof(phasesTable) / sizeof(phasesTable[0]));

            mcp1.digitalWrite(PH1, phasesTable[phIdx][0]);
            mcp1.digitalWrite(PH2, phasesTable[phIdx][1]);
            mcp1.digitalWrite(PH3, phasesTable[phIdx][2]);
            mcp1.digitalWrite(PH4, phasesTable[phIdx][3]);
        }
    }
}

```

NOTE: I did not test this code, but I'm pretty confident it should work. Maybe there are some bugs left, however, but you should be able to correct them yourself.

The program behaves this way: every 100ms (you can go a bit faster, but sometimes you can lose steps, so you have to test it) it checks if the motor has reached the final position he needs to reach (`targetPosition`). If it has, the program does nothing. Otherwise it moves one step towards the target. All this is managed in the `updatePosition` function.

You have to call this in the loop (and make a NON BLOCKING loop, otherwise also the motor will block). In the loop, modify the target position that you need to reach (the part I called `Functional part`). In the example, the program moves the motor 50 steps back and forth (so 50 steps in one direction, then back to the origin, then to 50 and so on).

The control technique used is the full step. If you want to use another, change the `phasesTable` constant variable.

If you need more functionalities, there are a lot of libraries for the steppers. Just use the proper commands to edit the pins on the MCP rather than the ones on the board.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Define a string with single quotation marks?
This is kind of a short question. All I want to know is, if I can define a string using single quotation marks ('), instead of the regular ones("). I want to use it in a function like this: print('Hello world');

I unfortunately do not have an Arduino nearby so I cannot test it myself.

# Answer
> 2 votes
No, you can't. `'x'` defines a single character or integer (note: `'ab'` is a two-byte single value \[integer\] made up from the ASCII values of both characters).

To include `"` within a string you have two options:

1. Escape the `"` with `\`, as in: `char foo[] = "He said \"Hello there\".";`
2. Use "raw strings" if the compiler is configured to support it: `char foo[] = R"(He said "Hello there".)";`

Option 1 is the most portable since it doesn't require compiler support for modern C++ standards. However it's the hardest to read, especially when you get lots of escapes in the same string.

You can make it more readable by defining QUOTE:

```
#define QUOTE "\""

char foo[] = "He said " QUOTE "Hello there" QUOTE ".";

```

# Answer
> 6 votes
**No**, you cannot. This rules comes from the basic C++ syntax on which the Arduino platform is built.

---
Tags: c++, arduino-ide
---


title: SD Initialization Failing

text:
# Question
Title: SD Initialization Failing
I am using a SEEED SD Card Shield. Everytime I attempt to write the card, I get

When Using File\> Examples\> SD \> CardInfo:

```
initialization failed. Things to check:
* is a card is inserted?
* Is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

```

Or when using File\>Examples\> SD\> Files:

```
Initializing SD card...initialization failed!

```

I even tried SdFat (IDE couldn't find anything), the "SD Library" by Adafruit (No change), and other things.

I'm using a Funduino MEGA 2560. Could that be the problem?!

# Answer
I also use a Seeed Studio SD Shield, and used to have the same problem. To rectify this I have to insert the SD card into my PC and Format it. This almost always helped. If you have a card that has too large of storage, the Arduino will take too much time to check the full memory for information stored on it (initialize). Some SD card readers require a card of 2 gigabytes or less to work. Check the Data Sheet for this limit (if there is one). That should do it for you.
> 2 votes

# Answer
I spent ages failing to get my SD card working. Then installed an earlier version (1.0.8) of the SD library which fixed the issue for me.
> 0 votes

---
Tags: arduino-mega, shields, sd-card
---


title: Interrupts on the Arduino NG

text:
# Question
Title: Interrupts on the Arduino NG
I am a newbie to using arduino.

I am using an arduino NG (using an atmega8). One of the pins is a button that triggers an interrupt.

The problem I am trying to solve is that I want an arduino NG to store the timestamp (we are using mills as a timer -no need to consider the 50 day rollover error here) when the interrupt pin is pressed.

The timer of the interrupts in milliseconds is stored in an array and there are up to 100 such interrupt button presses.

After searching around I didnt find any information for using interrupts with atmega8 on arduino NG (though there is information of how to use interrupts on atmega168 with arduino NG ).

So my question is: Is this problem solvable with an atmega8 arduino NG? Does the atmega8 arduino NG have interrupts? Just need one interrupt. And what would be the code to read an interrupt on atmega8 version of arduino NG?

# Answer
> 1 votes
> Does the atmega8 arduino NG have interrupts?-

Page 1 of the datasheet:

Yes, it has interrupts.

---

> just need one interrupt.

Page 46 of the datasheet:

It looks like you have 19 of them.

---

> regarding interrupts atmega8 is different168 there-so that may imply the the same code wont work -and I couldnt find any examples when searching

Try using the Arduino libraries. If that doesn't work post your code.

# Answer
> 0 votes
ATmega8-family chips have 19 interrupt vectors, vs 26 in ATmega48/88/168/328-family chips. (See Table 16.1, Interrupt Vectors in ATmega8A, in chapter 16 of ATmega8 documentation; and see Table 12.1, Interrupt Vectors in ATmega48A and ATmega48PA; Table 12.2, Interrupt Vectors in ATmega88A and ATmega88PA; and Table 12-4, Reset and Interrupt Vectors in ATmega168A and ATmega168PA, in chapter 12 of the ATmega48/88/168/328-family datasheet.)

Both families have INT0 and INT1 External Interrupt Request pins, so if either of those is the pin your application depends on, it should work ok on an ATmega8 system.

I don't see any mention of pin-change-interrupts in ATmega8 documentation so an application depending on PCI's probably wouldn't work.

# Answer
> -1 votes
You should check against the datasheet;

> Does the atmega8 arduino NG have interrupts?-just need one interrupt.

It has two external interrupts.

> And what would be the code to read an interrupt on atmega8 version of arduino NG?

google or read the datasheet. It is fairly simple to set up and use.

---
Tags: programming, interrupt
---


# Question
Title: Using strings inside mBlock extensions code
The following question is about a 3rd party Arduino programming enviroment mBlock and creating extensions for it. I hope that there are some of you out there, who are fammiliar with it.

I was recently making an extensions for mBlock that can be used to write code for Arduino, when I came over this obstacle. I tried to write a function inside the "work":"" statement.

It looked like this:

"work":"Serial.print("Hello world");"

The extensions could not be imported, due to the quotation marks around the Hello world string. I tried removing the quotation marks, the extension was sucessfully added, but the program did not work, beacause quotation marks are needed inside C++ code to define a string.

Is there a way to add them in the extensions, without screwing up the code?

# Answer
If that is a JSON format you could try using single quotes instead of double quotes:

```
"work":'Serial.print("Hello world");'

```

Alternatively you could escape the internal quotes:

```
"work":"Serial.print(\"Hello world\");"

```
> 1 votes

---
Tags: programming, c++, string
---


# Question
Title: Absolute encoder vs Accelerometer for calculating angles
I've been toying with this idea for a while and after some thorough research I'm more than happy that the project is realistic. However I'm in need of some direction in terms of the sensors I should be using.

There will be 3 arms all connected together (Like a poor mans Microscribe). I want to read the angle between each arm and use that info to calculate the final X and Y coordinates of the final end point on the arm.

I've looked closely into forward kinematics in robot arms and understand the principles are very much the same.

I've narrowed it down to Absolute encoders or accelerometers. Unfortunately I just can't find enough documentation about how to use the encoder with Arduino. There's plenty on using an accelerometer but I can't imagine the accuracy would be as good as the encoder.

I'm hoping to get the X and Y coordinate accuracy within +/- 0.5mm. Is this accuracy feasible?

The diagram attached shows the basic principle and formula I will use.

------EDIT-----

Thanks for the info everyone! Seems like this is going to be a little trickier than I originally thought. I've found a project achieving something very similar, however there's no mention of it's accuracy. http://fablab.ruc.dk/diy-digitizer/

Any ideas as to what sort of accuracy he could be achieving? I understand the length of the arms are considerably shorter than mine which must help a huge deal.

# Answer
> I'm hoping to get the X and Y coordinate accuracy within +/- 0.5mm. Is this accuracy feasible?

I'm only going to consider the A1 in your diagram since the accuracy of that will have the greatest impact in the final position. For the other angles any errors will have a smaller impact on the final position accuracy.

Take the most simple case, the arm is in a straight line almost completely in the X direction.

You want a Y reading of +/- 0.5 mm with an arm length of 1400 mm. That will require an angular accuracy of +/- 0.02 degrees.

Assuming you have a maximum travel of 90 degrees and you scale things such that your full ADC range is used linearly over that range then you require log(90/0.02)/log(2) = 12.1 bits resolution on your readings. So after allowing for the noise in all sensor outputs you're looking at a minimum of a 14 bit data required to give that level of resolution.

It's been suggested you use a pot connected to the internal 10 bit ADC. Assuming you used your full ADC range over 90 degrees and the 10 bit ADC reading had no noise on it you would be looking at around 2 mm accuracy. In the real world I'd be impressed if such a system could reach 5 mm accuracy.

Assuming you are working vertically accelerators could work, they typically have at least 16 bit resolution on the output but are noisy, you'd need to average for a long time in a very stable environment to get the levels of accuracy needed. Probably a non-starter.

A very quick google didn't find any easily available encoders with the required accuracy. I'm sure they exist but they are probably going to be expensive. You could possibly use gearing to improve the sensitivity of a more standard part but that's adding mechanical complexity.

In other words the accuracy you're aiming for isn't easy to achieve. You may want to look at relaxing your requirements a little.
> 1 votes

# Answer
An accelerometer is not a suitable sensor for this, unless you are working in a vertical orientation (drawing on a wall), in which case you can use the pull of gravity.

It would, though, be overly complex for what is actually a very simple requirement.

Absolute encoders in the traditional (digital) sense are also not good since they don't give great resolution without an overly complex (large number of bits) interface.

The simplest option is to use simple potentiometers. They give around 270° of rotation, which should be more than enough for most uses, and are incredibly simple to interface. They give the resolution of the ADC (10 bit) and are very very simple to read (just use `analogRead()`).

They are also very cheap.
> 0 votes

# Answer
> Is this accuracy feasible?

possible with high accuracy encoders but unlikely with accelerometers - they also drift too much.

Also, cos(x+y) can be decomposed into cos/sin(x) and (y), making a recursive calculation possible. that can be handy if you are using a lut to calculate sin/cos.
> 0 votes

---
Tags: arduino-uno, accelerometer, rotary-encoder
---


# Question
Title: Does anyone know how to connect 2 digipots to Arduino? (MCP4141)
I'm struggling with getting the code right. I'm trying to connect 2 digipots (MCP 4141) to Arduino to work separately over SPI. Has anyone got any experience with that?

# Answer
Try to read the datasheet and get a basic understanding of how the device works. in this case, it consists of 16 bits transfer (2 bytes).

Try to write a set of routines that communicates with the chip over the spi.

After that, it is all about using the \_CS pin to select a particular chip.

edit: if this helps you, here is my code driving two mcp41010 - slight different from your digit pot but very similar.

```
//write to the device wiper0
void mcp41xxx_write0(uint8_t dat) {
    spi_write(MCP41XXX_P0 | MCP41XXX_CMD_WRITE);    //send the command byte
    spi_write(dat);                                 //send the data byte
}

//write to the device wiper1
void mcp41xxx_write1(uint8_t dat) {
    spi_write(MCP41XXX_P1 | MCP41XXX_CMD_WRITE);    //send the command byte
    spi_write(dat);                                 //send the data byte
}

```

the actual writes to the devices will differ -\> mine is specific to the mcp41010 devices. It supports two wipers, P0 and P1. No increment or decrement on my digit pots.

the way to drive two digit pots are below:

```
//first pot
spi_select(MCP41XXX_CS1);           //deselect cs1 -> idles high
mcp41xxx_write0(i + i);             //send the data
spi_deselect(MCP41XXX_CS1);         //select hte device

//second pot
spi_select(MCP41XXX_CS2);           //deselect cs1 -> idles high
mcp41xxx_write0(i++);               //send the data
spi_deselect(MCP41XXX_CS2);         //select the device

```

as i'm using a single pot device, writing to the 2nd pot means writing to its wiper0.

I looked at your digit pot and the only thing you need to change are the wiper-specific routine(s), as your transmission is slightly different in the msb.

the spi\_write() routine can be replaced / mapped to the shiftOut() routine under arduino.

here is the above code, without any change, running on an arduino:

I also took a brief look at your device's datasheet (mcp4141) and I think this is all you need to change:

```
//send data on wiper0 of mcp4141
void mcp41xx_write0(uint16_t dat) {
    dat = dat & 0x03ff;                             //10-bit data
    spi_write(MCP41XX_CMD_WRITE | MCP41XX_WIPER0 | (dat >>  8));    //write the msb
    spi_write(dat);                                 //write the lsb
}

```
> 0 votes

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


title: Peer to peer communication

text:
# Question
Title: Peer to peer communication
Hello guys , I want to perform a mesh network between 3-4 modules using ESP8266 . Any one have idea how to do it?

# Answer
Peer to Peer Example
Written by Stewart Meyer (engineer retired from the FAA).
This is first time that I have given an answer, hope you can read this:

Not only can the ESP8266 connect to a WiFi network and interact with the Internet, but it can also set up a network of its own, allowing other devices to connect directly to it. This example demonstrates how to turn the ESP8266 into an access point (AP) also called a server, and serve up data to any connected client also called a station.

Server (Access Point) First we will look at the server:

```
/* Server
*  We write the server first because we need its IP address
*/

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

const char* ssid = "Meyer";       // ssid of server (Access Point (AP))
const char* password = "";        // password of server (Access Point (AP))
WiFiServer server(80);            //Service Port

int ledPin = 2; // GPIO2 of Server ESP8266

void setup()
{
    delay(1000);
    Serial.begin(115200);    // to use tools->serial monitor

    pinMode(ledPin, OUTPUT);   // set GPIO 2 as an output

    WiFi.mode(WIFI_AP_STA);  // Set WiFi to AP and station mode

    // Connect to the WiFi network
    Serial.println();
    Serial.print("Connecting to: "); Serial.println(ssid);
    WiFi.softAP(ssid, password);

    // Display the server address
    Serial.print("Connected, My address: ");
    Serial.print("http://");
    Serial.print(WiFi.softAPIP());
    Serial.println("/");

    // Tell the server to begin listening for incoming connections
    server.begin();
    Serial.println("Server listening for incoming connections");
}

void loop()
{
    // Check if a client has connected
    WiFiClient client = server.available();
    if (!client) // if not available, return
    {
        return;
    }

    // Wait until the client sends some data
    Serial.println();
    Serial.println("Client connected");
    while(!client.available())
    {
        delay(1);
    }

    // Read the request
    String request = client.readStringUntil('\r');
    Serial.print("Request = "); Serial.println(request);

    if (request.indexOf("/ON/") != -1)
    {
        digitalWrite(ledPin, LOW); // turn LED on
    }
    if (request.indexOf("/OFF/") != -1)
    {
        digitalWrite(ledPin, HIGH); // turn LED off
    }

    client.flush();
    Serial.println("Client disconnected");
}

```

Client (Station) Next we will look at the client:

```
/*  Client
*   This client will turn the LED on or off every 5 seconds
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

const char* ssid = "Meyer";   // ssid of access point (Server)
const char* password = "";    // password of access point (Server)
int port = 80;                // port number

byte ip[]= {192,168,4,1};

int LEDstatus = 0;

WiFiClient client;  // Declare client

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

    WiFi.mode(WIFI_STA);  // set mode to station (client)

    // Connect to wiFi
    Serial.println(); Serial.println();
    Serial.println("CONNECTING TO WiFi");
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");  // print dots until connection
    }
    Serial.println();
    Serial.println("WiFi CONNECTED");
}

void loop()
{
    // Connect client to server
    Serial.println("CONNECTING CLIENT TO SERVER");

    if (client.connect(ip, port))
    {
        Serial.println("CONNECTED");
    }
    else
    {
        Serial.println("CONNECTION FAILED");
    }

    // Send message to control the LED
    if (LEDstatus == 0)
    {
        client.println("/OFF/");
        Serial.println("LED OFF");
        LEDstatus = 1;
    }
    else
    {
        client.println("/ON/");
        Serial.println("LED ON");
        LEDstatus = 0;
    }

    client.println();

    client.flush();

    delay(1);
    Serial.println("CLIENT DISCONNECTED");
    Serial.println();
    delay(5000); // delay 5 seconds
}

```
> 5 votes

# Answer
You can't, that's not how the esp8266 works.

The esp8266 is WiFi, so you will either need an access point or nominate one esp8266 module to act as an access point running in softap mode.
> 4 votes

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


# Question
Title: Is there an advantage to set pinmodes via bitmask and register?
I'm working with the capacitive sensor library currently and the author does not use `digitalWrite()`, but instead sets the output of a pin via functions changing the bitmasks of certain registers:

https://github.com/PaulStoffregen/CapacitiveSensor/blob/master/CapacitiveSensor.h#L39

I looked into the OneWire library description those functions come from, but I still can't see any advantage over simply using the standard way Arduino proposes.

# Answer
> 1 votes
> I still can't see any advantage over simply using the standard way Arduino proposes.

The standard functions are slower.

---

There is a very good reason that the Arduino "standard" functions `digitalRead`, `digitalWrite` and `pinMode` are slower than direct port manipulation: They take **a variable** as the pin number and value to set it to.

This means that the functions in question then have to do a table lookup to translate the pin number to a port number and a bit position. The advantage is you can write code like this:

```
for (int i = 0; i < 20; i++)
  {
  pinMode (i, OUTPUT);
  digitalWrite (i, LOW);
  }

```

That's quite handy!

However if you have timing-critical code, and you happen to know the pin number in advance, and it won't change, then you can use a library digitalWriteFast which can optimize that for you. The library cleverly detects if a particular call is given a variable or constant. If a constant then it does the faster port manipulation method (this can now be done at compile-time to find the port and bit number).

There seem to be a few different versions of this library around. The one I linked above fails if you don't pass a constant, others fall back to just doing a `digitalWrite` (etc).

Inside the library there is code like this:

```
if (__builtin_constant_p(P) && __builtin_constant_p(V)) { \

```

In other words it uses a compiler directive to detect if the argument (P = pin, and V = value) are constants or not.

---

You can also, of course, do direct port manipulation but be warned that if you do then your code becomes pretty non-portable. Try going from an Atmega328 to an Atmega16U4 and the ports and bit positions will change.

---

Another library: https://code.google.com/archive/p/digitalwritefast/downloads

# Answer
> 1 votes
With direct access to the pin registers, there is no need to call a function (since the `digitalWrite` function itself calls some functions), which is slower than manipulating the bits directly. You are also able to set the bits of several ports at the same time.

The manipulation of port registers is described in the PortManipulation chapter. It states:

> Generally speaking, doing this sort of thing is not a good idea

However it could/should be used for time-sensitive applications. This is an interesting read on this topic.

# Answer
> 1 votes
> Is there an advantage to set pinmodes via bitmask and register?

I can name a few:

1) speed - I benchmarked the arduino pin ops vs. direct register ops here;

2) size - the code size is considerably bigger with the arduino library;

3) portability - the bitmark approach is supported by any C-compiler;

4) convention - i'm used to the bitmask approach and wrote all of my libraries around it; ...

as i'm sure others have their reasons to use the bitmasks.

# Answer
> 0 votes
The reason for using direct port operations in capacitive-sensor code is that such code works ok, and slower code won't. Here's an extract from CapacitiveSensor.cpp in Stoffregen's CapacitiveSensor code:

```
int CapacitiveSensor::SenseOneCycle(void) {
    noInterrupts();
    DIRECT_WRITE_LOW(sReg, sBit);   // sendPin Register low
    DIRECT_MODE_INPUT(rReg, rBit);  // receivePin to input (pullups are off)
    DIRECT_MODE_OUTPUT(rReg, rBit); // receivePin to OUTPUT
    DIRECT_WRITE_LOW(rReg, rBit);   // pin is now LOW AND OUTPUT
    delayMicroseconds(10);
    DIRECT_MODE_INPUT(rReg, rBit);  // receivePin to input (pullups are off)
    DIRECT_WRITE_HIGH(sReg, sBit);  // sendPin High
    interrupts();

    while ( !DIRECT_READ(rReg, rBit) && (total < CS_Timeout_Millis) ) {  // while receive pin is LOW AND total is positive value
        total++;
    }
//...
}

```

The general idea is that a source pin and receive pin are driven low, briefly, to discharge associated capacitance. Immediately upon changing the receive pin to an input we want to change the source pin high, and begin counting the total number of cycles that elapse before the receive pin charges to above about 2.5 V.

Code using `digitalWrite()`, `digitalRead()`, and `pinMode()` calls at four to five microseconds each would take so long to switch from output to input, or to read the source pin and receive pin, that the charging event would be over before the count loop began.

---
Tags: sensors, shift-register, core-libraries
---


# Question
Title: Using multiple RTC libraries in one program
There are multiple RTC libraries available, can I load several RTC libraries into my code and then use the functions I like from each one? Will there be some conflict if for example I include DS1307.h and RTCLib.h and other RTCXXXX.h libraries as well?

# Answer
If you want to load multiple RTC libraries I guess you are connecting to multiple RTCs.

If they use the same interface to communicate, i.e. I2C there is a possibility you will initialise the bus multiple times.

You should be OK with the functions not clashing, because they are within classes, but its possible some of the referenced structures/ classes my clash. You *might* be able to resolve this by namespacing the libraries.

An alternative might be to write your own library that handles all of the RTCs that you are interested in. This will force you to consider what each RTC requires and identify problems.

At the end of the day I agree with what Gerben is saying. Don't do it unless you really have to.
> 1 votes

# Answer
> can I load several RTC libraries into my code and then use the functions I like from each one?

It will depend on the libraries. Most likely they had some persistent variables, global to the routines, that help information exchange. If only some of the routines are used and others not, values in those variables may not be consistent.

> Will there be some conflict

That will depend on the way those libraries are implemented. No way of telling without seeing the code.

The point of doing this is a little bit suspect. It is not clear to me why you would want to have more than 1 RTC in an environment. If you are thinking about giving your program the option to function with multiple RTCs (but using one RTC at any given time), you can use either macro (at compile time) or wrap the RTCs in a logic layer (at run time).

For example, you can have a `rtc_init()` to reset different RTCs; and `rtc_read()` to return the time from the rtc. `rtc_read()` can be implemented based on which RTC is detected during initialization...
> 1 votes

---
Tags: rtc
---


# Question
Title: The BOOTRST fuse was disabled, but bootloader code is still running after chip reset
I am experimenting with an ATmega328P bootloader, and I created an Intel HEX (.hex) file with a program with an infinite loop in the beginning and with Optiboot code at the end of the hex file. (Code loaded into the chip is here: http://relliks.php5.cz/stackexchange/DUMP.bin.)

Then I disabled the `BOOTRST` fuse and pressed the restart button on Arduino Uno R3, but the bootloader still blinks with the LED on digital port 13.

How is it possible, that the bootloader is executed after chip restart and `BOOTRST` is disabled? My fuse settings are: Only `SPIEN` and `BODLEVEL0` are set.

I found that when I disable the `BODLEVEL0` fuse, the bootloader turns off. `BODLEVEL0` is used to set the brown-out voltage and shouldn't affect bootloader start. Where is the issue?

# Answer
Thank you very much!

I found that when I set fuses using program PONYPROG2000 and native RS232 programmer (http://3.bp.blogspot.com/-2D\_0B7...) then I read fuses again using another program (eXtreme Burner) and another programmer(USBASP 2.0), there was difference. **The PONYPROG2000 probably sets the fuses incorrectly**. Now the Atmega328P works correctly yet.
> 0 votes

# Answer
You don't seem to have filled in all the interrupt vectors. I get this from your .bin file:

```
00000000 <.sec1>:
       0:       00 c0           rjmp    .+0             ;  0x2
       2:       00 00           nop
       4:       00 00           nop
       6:       00 00           nop
       8:       fc cf           rjmp    .-8             ;  0x2
       a:       fb cf           rjmp    .-10            ;  0x2
       c:       fa cf           rjmp    .-12            ;  0x2
       e:       f9 cf           rjmp    .-14            ;  0x2
      10:       f8 cf           rjmp    .-16            ;  0x2
      12:       f7 cf           rjmp    .-18            ;  0x2
      14:       f6 cf           rjmp    .-20            ;  0x2
      16:       f5 cf           rjmp    .-22            ;  0x2
      18:       ff ff           .word   0xffff  ; ????
      1a:       ff ff           .word   0xffff  ; ????
      1c:       ff ff           .word   0xffff  ; ????
      1e:       ff ff           .word   0xffff  ; ????
      20:       ff ff           .word   0xffff  ; ????
      22:       ff ff           .word   0xffff  ; ????
      24:       ff ff           .word   0xffff  ; ????
...
    7dfc:       ff ff           .word   0xffff  ; ????
    7dfe:       ff ff           .word   0xffff  ; ????
    7e00:       11 24           eor     r1, r1           <--- bootloader
    7e02:       94 b7           in      r25, 0x34       ; 52
    7e04:       14 be           out     0x34, r1        ; 52
    7e06:       89 2f           mov     r24, r25
    7e08:       8d 70           andi    r24, 0x0D       ; 13
    7e0a:       11 f0           breq    .+4             ;  0x7e10
    7e0c:       89 2f           mov     r24, r25
    7e0e:       de d0           rcall   .+444           ;  0x7fcc
    7e10:       85 e0           ldi     r24, 0x05       ; 5

```

Now I can't quite see the relationship between the brown-out and those higher interrupts, but if one of them happened to fire I think it would waddle its way past all those 0xFF instructions and hit the bootloader.

The Atmega328P has 26 interrupt vectors (including Reset).
> 0 votes

---
Tags: bootloader
---


title: Cannot move TM1637 from Uno to Pro Mini

text:
# Question
Title: Cannot move TM1637 from Uno to Pro Mini
I have a very simple setup which works fine with an *Uno*.

```
#include <SevenSegmentTM1637.h>
#include <SevenSegmentExtended.h>

const byte PIN_CLK = 2;
const byte PIN_DIO = 3;
SevenSegmentExtended display(PIN_CLK, PIN_DIO);

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

  display.begin();
  display.print(F("TEST"));
}

void loop() {}

```

When I use the very same setup with a *Pro Mini* (XCSOURCE ATMEGA 328P, 5V 16Mhz), the display doesn't light up. I get monitor outputs and can blink the onboard LED, but no reaction from the *TM1637* display.

I get this output in the console:

```
�E%MA1e� 10001111
Acknowledged: 0
ADDR :  11000000
DATA0:  0
write byte: 84
ADDR :  11000000
DATA0:  1111000
write byte: 69
ADDR :  11000000
DATA0:  1111000
write byte: 83
ADDR :  11000000
DATA0:  1111000
write byte: 84
ADDR :  11000000
DATA0:  1111000

```

Does anyone have an idea how to debug or fix this?

# Answer
> 1 votes
Since you're using a Grove Display, I believe it will be using I2C.

For better debugging, try using the actual I2C pins on your Pro mini, which are A4 and A5.

> I2C: A4 (SDA) and A5 (SCL). Support I2C (TWI) communication using the Wire library. https://www.arduino.cc/en/Main/ArduinoBoardProMini

I2C may need pull-up resistors on your data lines.

(https://en.wikipedia.org/wiki/I%C2%B2C)

It can also be nice to use "verified to be working" code, like example code from the manufacturer.

```
/*
 * TM1637.cpp
 * A library for the 4 digit display
 */
#include "TM1637.h"
#define CLK 39 //pins definitions for TM1637 and can be changed to other ports
#define DIO 38
TM1637 tm1637(CLK,DIO);
void setup()
{
    tm1637.init();
    tm1637.set(BRIGHT_TYPICAL);//BRIGHT_TYPICAL = 2,BRIGHT_DARKEST = 0,BRIGHTEST = 7;
}
void loop()
{
    int8_t NumTab[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};//0~9,A,b,C,d,E,F
    int8_t ListDisp[4];
    unsigned char i = 0;
    unsigned char count = 0;
    delay(150);
    while(1)
    {
        i = count;
        count ++;
        if(count == sizeof(NumTab)) count = 0;
        for(unsigned char BitSelect = 0;BitSelect < 4;BitSelect ++)
        {
            ListDisp[BitSelect] = NumTab[i];
            i ++;
            if(i == sizeof(NumTab)) i = 0;
        }
        tm1637.display(0,ListDisp[0]);
        tm1637.display(1,ListDisp[1]);
        tm1637.display(2,ListDisp[2]);
        tm1637.display(3,ListDisp[3]);
        delay(300);
    }
}

```

You will need to adapt the pin numbers.

But after these steps it should work just fine.

Source: http://wiki.seeed.cc/Grove-4-Digit\_Display/

# Answer
> 0 votes
4.7k resistors on 2 and 3 pins does not help.

Works great if the tm1637 directly connected to 12 and 13 pins.

---
Tags: arduino-uno, arduino-pro-mini, display
---


title: Analog inputs on ATtiny85 don't work

text:
# Question
Title: Analog inputs on ATtiny85 don't work
I want to use a ATtiny85 to check the voltage of two 12 V batteries (later to control a relay). Therefore I'm using the `analogRead()` function. For programming I'm using an Arduino Mega 2560 board.

```
//                           +-\/-+
//  Ain0       (D  5)  PB5  1|    |8   VCC
//  Ain3       (D  3)  PB3  2|    |7   PB2  (D  2)  INT0  Ain1
//  Ain2       (D  4)  PB4  3|    |6   PB1  (D  1)        pwm1
//                     GND  4|    |5   PB0  (D  0)        pwm0
//                           +----+

```

For A1 this works perfectly fine. But for A2 or A3 I'm getting always a value of 15 V (thus the analog input gives 1023 respectively it thinks there is 5 V on the pin, which is not the case). I tried A0 as well, but it's the same.

For seeing the current value I put a serial - USB converter on RX, TX on PB3, PB4. So I guess they cannot work properly as analog inputs then. But still A0 does not work and without serial my LED is always on without having a voltage over 12 V.

At the moment I don't know what to do about it. No matter which of the analog pins I choose, I'm getting always a wrong value (except A1).

I'm not a hundred percent sure about A0. On some diagrams there is an A0 pin, on some not. But I tried to remove all the serial communication code and still having the LED 0 on high.

Thanks in advance!

```
void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  digitalWrite(0, LOW); // led for displaying the voltage
  digitalWrite(1, LOW); // blinking status led
  int sensorValue1 = 0;
  int sensorValue2 = 0;
  Serial.begin(9600);
}

void loop() {
  int sensorValue1 = analogRead(A1);
  int sensorValue2 = analogRead(A0);
  // <- the problem, A2, A3 do not work as well
  float voltage1 = sensorValue1 * (5 / 1023.00) * 3;
  float voltage2 = sensorValue2 * (5 / 1023.00) * 3;
  Serial.print(voltage1);
  Serial.print("--");
  Serial.print(voltage2);
  Serial.println();
  if ((voltage1 > 12) || (voltage2 > 12)) {
    digitalWrite(0, HIGH);
  } else {
    digitalWrite(0, LOW);
  }
  digitalWrite(1, HIGH);
  delay(1000);
  digitalWrite(1, LOW);
  delay(1000);
}

```

SOLUTION: As suggested by Andrei Dragan the problem was the serial communication, which uses just the same pins as the analog inputs A2 and A3. When turned off, the problem disappeared.

As the serial communication is quite useful for me, right now I'm still using the serial communication but only with the pin for sending data. The pin for receiving data is turned off. It looks like this:

```
#include <SoftwareSerial.h>

#define RX    -1   // *** turned off
#define TX    4   // *** D4, Pin 3

SoftwareSerial Serial1  (RX, TX);

```

(I don't know if this is the best way, but it works for me.)

Once again, thanks for the help!

# Answer
Any type of communication protocol uses pull-up resistors (not 100% sure that all of them do but still, it's a rule of thumb) so using the serial trick on the attiny enables the internal pull-up resistors on PB3 and PB4. I can bet the ADC value is near 1023 isn't it? Disabling the serial communication should in theory fix your problem.
> 1 votes

---
Tags: arduino-mega, attiny, avr
---


# Question
Title: How can I convert PID correction values to an PWM brushless command?
Please I'm working on a quadcopter, and I have to made my own flight controller based on arduino uno.
First of all please how can I get a filtred angular velocity and linear acceleration from the MPU6050, is the following code give us the angular velocity in deg/sec and the linear velocity in m/s² ?

`accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);`

and is this pid value in this following code is right ?

```
  accel_reading = ax;
  accel_corrected = accel_reading - accel_offset;
  accel_corrected = map(accel_corrected, -16800, 16800, -90, 90);
  accel_corrected = constrain(accel_corrected, -90, 90);
  accel_angle = (float)(accel_corrected * accel_scale);

  err = angle_setpoint - accel_angle  ;

  P = Kp * err ;
  I += (Ki * err) ;
  D = Kd * (err - errp);

  pid = P + I + D;

```

Thank you.

# Answer
> How can I convert PID correction values to an PWM brushless command?

you have to do that yourself. you have to figure out first how to correct a pid value directionally. for example, should you increase the duty cycle if pid is positive or negative?

after that, you will need to map the pid value to a range for your pwm dc.

basically, it is application / task specific, and you are in complete charge.
> 1 votes

# Answer
You convert PID outputs to process outputs by selecting appropriate Kp, Ki, and Kd constants -- they translate the error components into a process output. For example, if you want 10 degrees of error to give you a full-scale analogWrite() adjustment, set Kp=255.0/10. Ki and Kd will depend on the (unspecified) sampling interval. If the measurements are noisy, you can use the Ki term to do some filtering work, but if you filter it prior to the PID, it will reduce the performance of the PID.

Code-wise, you are missing some sort of`errp=err;` code, you need more than acceleration in the x direction to calculate an angle, (atan2(az,ax) or some such, depending on orientation), and your PID scheme doesn't protect against common problems like out-of-range, integral windup, or inconsistent sampling interval. You should investigate the http://playground.arduino.cc/Code/PIDLibrary for a more robust implementation than you've half-coded above.
> 0 votes

---
Tags: arduino-uno, pwm, mpu6050, pid
---


# Question
Title: Arduino Uno Wunderground weather station - Ethernet connection failed
I'm new to Arduino. For my first project, I've decided to build a weather station where data is collected via sensors and is then sent to Wunderground. I'm using an arduino uno, an ethernet shield as well as a DHT22 sensor for temperature and humidity.

Everything worked for an hour and then I'm getting "connection Failed" constantly.

I would really appreciate it if you could look into my code. I've tried everything and it doesn't explain the sudden failure of the project. I occasionally get a successful upload after dozens of connection failed messages.

Here's my code. I've removed my weather station password for security reasons.

```
#include <Wire.h>
#include <SPI.h>
#include <Wire.h>
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include "DHT.h"

// Sensor Pins
#define DHTPIN 7
#define DHTTYPE DHT22
// Variables
float temp;
float hum;

byte mac[] = {
  "de,ad,be,ef,fe,ed"
};
EthernetClient ethernetClient;
unsigned int localPort = 8888;
// Wunderground server details
char SERVER[] = "rtupdate.wunderground.com";
char WEBPAGE[] = "GET /weatherstation/updateweatherstation.php?";
char ID[] = "ICHESTER24";
char PASSWORD[] = "iwqnrlex";

DHT dht(DHTPIN, DHTTYPE);
unsigned int connections = 1;
unsigned int timeout = 30000;

void setup(void) {
  Serial.begin(38400);
  Wire.begin();
  dht.begin();

  // Connect to internet
  Serial.print(F("\nInitialising Ethernet module"));
  if (Ethernet.begin(mac)){

    Serial.println("Initialisation completed successfully!");
  }
  else {
    Serial.println("Something went wrong during ethernet module setup!");
  }
} //END OF SETUP

void loop(void) {
  hum = dht.readHumidity();
  temp = dht.readTemperature();
  float tempf = (temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
  float dewptf = (dewPoint(tempf, hum));
  Serial.println("++++++++++++++++++++++++++");
  Serial.println("temp = ");
  Serial.println(tempf);
  Serial.println("Humidity = ");
  Serial.println(hum);
  Serial.println("DewPoint = ");
  Serial.println(dewptf);
  // Send all data to WUNDERGROUND
  if (ethernetClient.connect(SERVER, 80)) {
    ethernetClient.print(WEBPAGE);
    ethernetClient.print("ID=");
    ethernetClient.print(ID);
    ethernetClient.print("&PASSWORD=");
    ethernetClient.print(PASSWORD);
    ethernetClient.print("&dateutc=");
    ethernetClient.print("now");
    ethernetClient.print("&tempf=");
    ethernetClient.print(tempf);
    ethernetClient.print("&humidity=");
    ethernetClient.print(hum);
    ethernetClient.print("&dewptf=");
    ethernetClient.print(dewptf);
       ethernetClient.print("&softwaretype=Arduino%20UNO%20version1&action=updateraw&realtime=1&rtfreq=2.5");//Rapid Fire
    ethernetClient.println();
    Serial.println("New data uploaded");
  }else{
    Serial.println("Connection Failed...");
  }
  delay(2500);

}
void resetEthernet() {
 ethernetClient.stop();
 delay(1000);
 Ethernet.begin(mac);
 delay(1000);
 ethernetClient.available();
}
double dewPoint(double tempf, double humidity)
{
  double A0= 373.15/(273.15 + tempf);
  double SUM = -7.90298 * (A0-1);
  SUM += 5.02808 * log10(A0);
  SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
  SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
  SUM += log10(1013.246);
  double VP = pow(10, SUM-3) * humidity;
  double T = log(VP/0.61078);
  return (241.88 * T) / (17.558-T);
}

```

# Answer
> 1 votes
I assume u used a W5100 shield. This shield is capable of having 4 connections open. If the connections are not closed for some reason the chip is unable to make another connection. This means after sending u need to close the connection. (else it will work 4 times).

`ethernetClient.stop()`

Just before or after

`Serial.println("New data uploaded");`

https://www.arduino.cc/en/Reference/ClientStop

---
Tags: shields, ethernet
---