# Question
Title: I have a question,an error occured in my code saying TIMSK was not declared in the scope(There are no errors)
```
#include <SmartInventor.h>

void setup() {
  SmartInventor.DCMotorUse();

}
void loop() {
  // M1, M2, M3
  // CW, CCW, STOP
  // 0-100
  // 0-360

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(5000);

  SmartInventor.DCMotor(M1, CCW, 10);  //Music starts  //0:00:06
  delay(2000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(11000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0); //Music stops   //0:00:32
  delay(10000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(5000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(1000);

  SmartInventor.DCMotor(M1, CW, 10); //Music starts back up    //0:00:44
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(18000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(3000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 10);
  delay(8000);

  SmartInventor.DCMotor(M1, CW, 10); //Music stops   //0:01:15
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(5000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(3000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0); //Music starts up agian   //0:01:31
  delay(11000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0); //Music stops     //0:02:03
  delay(23000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0); //Music starts up agian   //0:02:14
  delay(12000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(6000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(6000);

  SmartInventor.DCMotor(M1, CCW, 10); //Music Ends    //0:02:40
  delay(2000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(3000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(5000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000)

  ;SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(13000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(13000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(13000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000)

  ;SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(7000);

}

```

# Answer
> 1 votes
The SmartInventor library is to be used with the Rokit Smart board. That board is based around the ATMega32.

The Arduino Mega is *not* a Rokit Smart board, so the library will not work, since the Arduino Mega us based around the ATMega2560. The two chips are different, and have different sets of internal peripherals. So the registers have different names accordingly.

---
Tags: arduino-mega, programming, arduino-motor-shield, compilation-errors, board
---


# Question
Title: NodeMCU unable to connect to mobile hotspot when I include codes for reading the temperature sensor
Good day.

The NodeMCu successfully connected to mobile hotspot when i didn't put any others codes except the Wifibegin etc.

Howveer when I include some codes for temparature sensor, it keeps on connecting whereas the everything else including the SSID, password remain the same.

Below are my codes, I tried many, I mean I tried almost everything possible(that's stated in forums), read forums after forum. Please let me know if I missed something out here.

Thanks!

PS: i attached my codes here

```
#include <ESP8266WiFi.h>
#include <WifiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

/* Wi-Fi setting connect to your smartphone Wi-Fi hotspot */
const char *ssid = "Thanks";
const char *password = "For reading";

/* Variable for taking out LM35 value */
String tempValue;
int analogValue;
int tempPin = A0;
float milliVolts;
float celcius;
/* Variable for sending data to server */
String postData;
int httpCode;
String payload;
void setup(){
//delay(1000);
Serial.begin(115200);
WiFi.begin(ssid,password);
Serial.println("");
Serial.println("Connecting");
/* If Wi-Fi hotspot is not found, show ..... in serial monitor */
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.println(".");
}
/* If Wi-Fi hotspot is found, show IP address in serial monitor */
Serial.println("");
Serial.println("Connected to ");
Serial.println(ssid);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop(){
/* Getting value from LM35 */
delay(1000);
analogValue = analogRead(tempPin);
milliVolts = (analogValue/1024.0)*3300;
celcius = milliVolts/10;
tempValue = String(celcius);
Serial.println(tempValue);
/* Sending LM35 value to server */
HTTPClient http;
postData = "tempValue=" + tempValue;
http.begin("http://xxx.xxx.xx.xxx/dbInsert.php");
http.addHeader("Content-Type","application/x-www-form-urlencoded");
httpCode = http.POST(postData);
payload = http.getString();
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end();
}

```

# Answer
Get rid of the delay - this **STOPS** processing for five seconds, not really what you want in a wifi scenario - some routers might disconnect you in this time if no pingbackis are coming
If you need a 5 second- non blocking break for your routines look at this example
ArduinoIDE -\> examples -\> 2 Digital -\> blinkwithoutdelay.
For further assistance copy and paste your code in code tags and not as a picture.
> 0 votes

---
Tags: esp8266, wifi, nodemcu, iot, lm35
---


title: Soil moisture sensor, weird readings

text:
# Question
Title: Soil moisture sensor, weird readings
I'm having a small problem with my soil moisture sensor

it gives me weird readings, in the second the smallest connection is made between the legs it just gives me 4096 (which is max possible value), its either about 0 or 4095

I can't really seem to see the problem, any help is appreciated

(the output voltage is read on an ESP32, almost visible in the bottom of the image)

# Answer
> 1 votes
It looks like you're trying to measure the resistance of soil by connecting an ADC input through the soil to VCC. That is not the way to to it.

At the moment you effectively have this schematic for that portion:

simulate this circuit – Schematic created using CircuitLab

The voltage dropped across the soil is proportional to the current flowing through it. And there is no current flowing through it1 because there's no path to ground, only the very high impedance of the ADC.

So you never see anything except VCC (or a floating input when the probe is not in the ground).

To measure a resistance like that you have to have it as one half of a potential divider, just like you would for an LDR.

simulate this circuit

What actual value R2 should have depends entirely on the resistance range detected by your probe. It can be good to experiment with different values until you find one that works for you.

---

1: Actually there is some small leakage current through the ADC to ground, but that is so tiny we can ignore it.

---
Tags: sensors, esp32, electronics
---


# Question
Title: No contact between DS18B20 and WeMos D1 Mini
I have a waterproof DS18B20 sensor that I have connected to a WeMos D1 Mini microcontroller. This controller connects to Wifi and an MQTT broker, sending the temperature from the sensor and goes to deep sleep.

Everything works nicely, except for the sensor reading. It returns -127, which means the sensor is disconnected. I have checked cables, measured voltage and everything should be just fine.

I have data cable for the sensor connected to D2, so in my sketch I have tried the following pins without success: `oneWire(D2)` \- `oneWire(2)` \- `oneWire(GPIO4)` \- `oneWire(4)`. No success.

Can anyone please help me with the following sketch?

```
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// WiFi settings
const char* ssid     = "[REDACTED]";
const char* password = "[REDACTED]";

// MQTT settings
const char* mqttServer   = "[REDACTED]";
const char* mqttUser     = "[REDACTED]";
const char* mqttPassword = "[REDACTED]";
const int   mqttPort     = 1883;
const char* mqttClient   = "[REDACTED]";
const char* mqttTopic    = "[REDACTED]";

#define durationSleep   15 // deep sleep length in minutes
#define NB_TRYWIFI      20 // number of wifi connection tries
#define ONE_WIRE_BUS     4 // temperature sensor connection

WiFiClient        espClient;
PubSubClient      client(espClient);
OneWire           oneWire(ONE_WIRE_BUS);
DallasTemperature sensor(&oneWire);

float celsius = 0;

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

  // Connect to sensors
  sensor.begin();

  // Setup WiFi
  WiFi.begin(ssid, password);
  int _try = 0;

  // Connect to WiFi
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    _try++;
    if (_try >= NB_TRYWIFI) {
      ESP.deepSleep(durationSleep * 1000000);
    }
  }

  // Setup MQTT
  client.setServer(mqttServer, mqttPort);

  // Get temperature in celsius
  sensor.setResolution(10);
  sensor.requestTemperatures();
  celsius = sensor.getTempCByIndex(0);

  // Connect to MQTT broker
  while (!client.connected()) {
    if (client.connect(mqttClient, mqttUser, mqttPassword)) {
      client.publish("mspa/temperature", String(celsius).c_str(), true);
      delay(1000);
    } else {
      delay(2000);
    }
  }

  // Go to sleep
  ESP.deepSleep((durationSleep * 60) * 1000000);
}

void loop() {
}

```

# Answer
> 0 votes
//Call this function after sensor begin in setup.. share output

```
uint8_t findDevices(int DSPIN)
{
  OneWire ow(pin);

  uint8_t address[8];
  uint8_t count = 0;

  if (ow.search(address))
  {
    Serial.print("\nuint8_t pin");
    Serial.print(pin, DEC);
    Serial.println("[][8] = {");
    do {
      count++;
      Serial.println("  {");
      for (uint8_t i = 0; i < 8; i++)
      {
        Serial.print("0x");
        if (address[i] < 0x10) Serial.print("0");
        Serial.print(address[i], HEX);
        if (i < 7) Serial.print(", ");
      }
      Serial.println("  },");
    } while (ow.search(address));

    Serial.println("};");
    Serial.print("// nr devices found: ");
    Serial.println(count);
  }

  return count;
}

```

# Answer
> 0 votes
And for the stability (**Read the comments**) of your solution (Change anyway!) instead of

```
// IMPORTANT: This leads to crashes due to heap fracturing and imho does not work stable on micro controllers
 client.publish("mspa/temperature", String(celsius).c_str(), true);

 // Do this - define fixed chars before Setup - the compiler puts themto the stack
 char mqttBuffer[16] = '\0';
 char topic[] = "mspa/temperature";
 .....
 dtostrf(celsius,6,2,mqttBuffer); // convert a float to char
 client.publish(topic, mqttBuffer, true); // We use the fixed chars instead of heap fracturing Strings

```

Read more on evil Strings: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/
Hope this helps

---
Tags: esp8266, ds18b20
---


title: Why is my "mood cue" not working?

text:
# Question
Title: Why is my "mood cue" not working?
I am new to Arduino, and I am working through the "Arduino Projects book," with the Arduino Uno. I am working on project 5, "the mood cue." It is basically a potentiometer-controlled servo. I am certain that I have the code for it correct, and certain that I have all the wiring correct. I have the potentiometer value and the angle at which the potentiometer is turned printed on the serial monitor.

I upload the code, and the serial monitor begins printing correctly, changing when I twist the potentiometer. But the servo doesn't move. It lets off a faint buzzing sound, and that is it.

Does anyone know what the problem is? I don't know what I have done wrong. Do you think my servo is broken?

Here is my code:

```
#include <Servo.h>
Servo myServo;
int const potPin = A0;
int potVal;
int angle;

void setup() {
  myServo. attach(9);
  Serial.begin (9600);
}

void loop() {
  potVal = analogRead(potPin);
  Serial.print ("potVal:");
  Serial.print (potVal);
  angle = map(potVal, 0, 1023, 0, 179);
  Serial.print ("angle:");
  Serial.print (angle);
  myServo.write (angle);
  delay(15);
}

```

Here is my wiring: file:///C:/Users/matth\_000/Downloads/Arduino%20PotServ.jpg

# Answer
The classic way of wiring up motors, including servos, is to provide them with separate power. The image below should clarify this:

The batteries (in this case) have the sole function of providing power to the servo motor. The "data" pin however goes to the Arduino.

The Arduino itself is powered by the USB cable in this example.

The **important** point is the blue wire - the shared ground wire. Both the Arduino and the servo (and batteries) must have a common ground.
> 2 votes

# Answer
If you're using the components that came in the starter kit, the servo is wired differently in the book than it is in the actual kit.

Make sure the red wire on the servo is connected to the power, the black to the ground and the white to the data. The specs are also written on the side of the servo motor.

In the project book, the wires went into these rows on the breadboard:

26. GND
27. 5V
28. Signal

Whereas for me that meant it was:

26. GND
27. Signal
28. 5V

Hope this helps!
> 1 votes

# Answer
I'm new to arduino and I had the same problem of the servo buzzing but not moving. I found the reason was the servo wires came in a different order than what was written in the book. After correctly connecting the 5v, GND, and Signal by moving a few wires on the bread board things worked as planed. Hoped this helps.
> 1 votes

# Answer
At first, I had similar behavior with the servo motor in this project. The servo buzzed and either did not move or made very slight erratic movements.

**The problem in my case was that I had wrongly placed the wire that is supposed to connect the potentiometer to pin A0.**

Here's how my board looked *after* I corrected the problem:
> 1 votes

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


# Question
Title: How to set a timer for a function and be able to reset it in the middle of the process?
Hello me and my friend have to do an assignment for school but we need some help. We have to make a LED turn on and of with a button and a relay. But when I press the button the LED should be on for 10 minutes and then go off unless we press the button inside those 10 minutes then the LED should turn off. Then repeat this process when we press the button again.

```
const int relay = 6;
const int button = 5;
int stateold = 1;
int statenew = 0;
int LED = 0;

void setup()
{
  pinMode(relay,OUTPUT);
  pinMode(button,INPUT);
  time = millis();
}

void loop()
{
  statenew = digitalRead(knop);
  if(stateold==0 && statenew==1){
    if(LED==0){
      digitalWrite(relay,HIGH);
      LED = 1;
      }
    }
    else{
       digitalWrite(relay,LOW);
        LED = 0;
    }
  }
 stateold=statenew;

}

```

# Answer
Below code is an example of what you described; pressing the button will turn on the LED and it will only turn off if 10 minutes passed or button is pressed again.

Read the comments in the code:

```
#define btn 5
#define rly 6

bool btnState;
bool ledState;
unsigned long timer = 0;

void setup() {
  pinMode(btn, INPUT_PULLUP);
  pinMode(rly, OUTPUT);
}

void loop() {
  btnState = digitalRead(btn); // Read the button status (default is 1)

  if (!btnState) { // If button state == 0 (pressed)
    ledState = !ledState; // Toggle this boolean
    timer = millis(); // and reset the timer
  }

  if (ledState) { // If LED state == 1
    digitalWrite(rly, HIGH); // Turn on the Relay
  } else { // Otherwise turn it off
    digitalWrite(rly, LOW);
  }

  if (ledState && millis() - timer > 600000) { // If 10 minutes passed turn off the relay
    digitalWrite(rly, LOW);
    ledState = !ledState;
  }
}

```

You should also de-bounce the button and you may want to turn on/off the LED when button is pressed **and** released, not just when it's pressed.
> 1 votes

---
Tags: relay, time
---


title: Boolean variable with if statement

text:
# Question
Title: Boolean variable with if statement
I am trying to use boolean variables with two if statements. The second if condition never evaluates to be true. May be it's a problem with how I have defined my boolean variables. Do you see the mistake?

Here is the code:

```
int x = 0;
boolean state1 = (x <= 10);
boolean state2 = (x > 10);

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

void loop() {

  x++;

  if (state1) {
    Serial.println("x <= 10");
  } else if (state2) {
    Serial.println(" x > 10");
  }

}

```

# Answer
> 1 votes
I asked this question to be moved to Stackoverflow as it is not Arduino related.

However to answer your question, you assign the booleans before you start the program, so they are never re-evaluated and always keep their initial value, based on when `x = 0`.

What you should do is, reevaluate them within the loop:

```
int x = 0;
boolean state1;
boolean state2;

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

void loop() {
  x++;
  state1 = (x <= 10);
  state2 = (x > 10);
  if (state1) {
    Serial.println("x <= 10");
  } else if (state2) {
    Serial.println(" x > 10");
  }
}

```

Also, because if state1 is true, state2 will always be false and vice versa, so you don't need to have two booleans. This will give:

```
int x = 0;
boolean state;

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

void loop() {
  x++;
  state = (x <= 10);
  if (state) {
    Serial.println("x <= 10");
  } else {
    Serial.println(" x > 10");
  }
}

```

Beyond that, you don't need to define the boolean globally, because you only need it inside the loop and is not need to be 'stored' from one loop to another. So you get

```
int x = 0;

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

void loop() {
  x++;
  boolean state = (x <= 10);
  if (state) {
    Serial.println("x <= 10");
  } else {
    Serial.println(" x > 10");
  }
}

```

Of course you can also directly check for `x <= 10` instead of storing it in a boolean, but I assume you need the boolean elsewhere further within the `loop` function later.

---
Tags: arduino-uno
---


# Question
Title: Receiving multiple Values from android via Bluetooth
my question is, how can I receive 3 integer values in Arduino, which I send from my android phone. I send all 3 values at the same time and I also need to read them in about the same time. I hope you can help me.

# Answer
If there are no other constraints, send them as a text with delimiters and a terminating character. e.g. something like `"123;45;678\n"`

On the arduino, either manually check for those delimiters and convert the digits to a number on the fly, or use `strtok` and `atoi` after reading the whole line.
> 1 votes

---
Tags: arduino-uno, serial, bluetooth, android, data
---


title: Using PortB as a sink, not working

text:
# Question
Title: Using PortB as a sink, not working
Out of ideas here, i try using PB0-3 as sinks for a LED matrix and the pins just won't sink.

My test code:

```
void setup() {
  //bitClear(SPCR, 6);
  pinMode(PD5, OUTPUT);

  pinMode(PB0, OUTPUT);
  pinMode(PB1, OUTPUT);
  pinMode(PB2, OUTPUT);
  pinMode(PB3, OUTPUT);

  digitalWrite(PB0, LOW);
  digitalWrite(PB1, LOW);
  digitalWrite(PB2, LOW);
  digitalWrite(PB3, LOW);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(PD5, HIGH);
  delay(1000);
  digitalWrite(PD5, LOW);
  delay(1000);
}

```

(Using bog standard Blink as a starting point for tests)

My controller is an ATMega328P programmed using USBaspLoader on my own PCB.

If i connect the physical pin that should be sinking with a piece of wire to ground the LED starts blinking, so the "sending" part seems to work but the "receiving" part doesn't. As you can see i tried manually disabling the SPI port, no luck either. I tried different controllers, among them a good old ATMega8-16, nothing seems to work. I even breadboarded a test circuit but no luck, PortB wont sink.

# Answer
> 1 votes
`PB3` etc don't refer to Arduino pins. Instead they refer to the bits in the internal registers.

To use `digitalWrite()` etc you must use *Arduino pins* not internal register bit numbers.

The pin to port/bit mapping is defined by what board you have selected, and if you want to look it up you should examine the `pins_arduino.h` file for your selected board.

---
Tags: pins, atmega328
---


# Question
Title: Can't get keypad to use Keyboard.write on an Arduino Uno
I've tried to use Keypad.h and Keyboard.h libraries to get my Arduino to use my Keypad for Keyboard input.

I'll start with working keypad code (which is pretty easy but it's my first post so I want to make it as neat as possible).

*Working keypad*

```
#include <Keypad.h>

const byte Rows = 4;
const byte Cols = 4;

char hexaKeys[Rows][Cols] = {
  {'1', '2', '3', 'A' },
  {'4', '5', '6', 'B' },
  {'7', '8', '9', 'C' },
  {'*', '0', '#', 'D' },
};

byte rowPins[Rows] = {9,8,7,6};
byte colPins[Cols] = {5,4,3,2};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins
, Rows, Cols);

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

void loop() {
char customKey = customKeypad.getKey();
  if (customKey){
    Serial.println(customKey);
  }
}

```

At this point, using Serial Monitor, I can see that all keys are being read and printed out no problem. Then, I tried adding the Keyboard.h library to get it to act as an keyboard input *Not Working Keyboard Input*

```
#include <Keypad.h>
//#include <Keyboard.h>
const byte Rows = 4;
const byte Cols = 4;

char hexaKeys[Rows][Cols] = {
  {'1', '2', '3', 'A' },
  {'4', '5', '6', 'B' },
  {'7', '8', '9', 'C' },
  {'*', '0', '#', 'D' },
};

byte rowPins[Rows] = {9,8,7,6};
byte colPins[Cols] = {5,4,3,2};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins
, Rows, Cols);

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

void loop() {
char customKey = customKeypad.getKey();
  if (customKey){
    Serial.write(customKey);
    //Keyboard.write(customKey);
  }
}

```

The commented out sections are where I've added changes. The problems I've encountered: \- Can't include Keyboard.h on regular Arduino Uno. I've read that changing board type to Arduino Leonardo helps, and it does, but then the Serial Monitor is greyed out and doesn't read keypad input. Using following code I get following error message ( I'm still 'using' Leonardo board since Keyboard.h doesn't want to work with Uno)

```
#include <Keypad.h>
#include <Keyboard.h>
const byte Rows = 4;
const byte Cols = 4;

char hexaKeys[Rows][Cols] = {
  {'1', '2', '3', 'A' },
  {'4', '5', '6', 'B' },
  {'7', '8', '9', 'C' },
  {'*', '0', '#', 'D' },
};

byte rowPins[Rows] = {9,8,7,6};
byte colPins[Cols] = {5,4,3,2};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins
, Rows, Cols);

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

void loop() {
char customKey = customKeypad.getKey();
  if (customKey){
    Keyboard.write(customKey);
  }
}

```

**processing.app.debug.RunnerException at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152) at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77) at processing.app.SketchController.upload(SketchController.java:732) at processing.app.SketchController.exportApplet(SketchController.java:703) at processing.app.Editor$UploadHandler.run(Editor.java:2047) at java.lang.Thread.run(Thread.java:748) Caused by: processing.app.SerialException: Error touching serial port 'COM7'. at processing.app.Serial.touchForCDCReset(Serial.java:107) at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136) ... 5 more Caused by: jssc.SerialPortException: Port name - COM7; Method name - openPort(); Exception type - Port busy. at jssc.SerialPort.openPort(SerialPort.java:164) at processing.app.Serial.touchForCDCReset(Serial.java:101) ... 6 more An error occurred while uploading the sketch Exception in thread "Thread-28" java.util.ConcurrentModificationException at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966) at java.util.LinkedList$ListItr.next(LinkedList.java:888) at processing.app.packages.LibraryList.getByName(LibraryList.java:61) at cc.arduino.contributions.libraries.LibrariesIndexer.addToInstalledLibraries(LibrariesIndexer.java:130) at cc.arduino.contributions.libraries.LibrariesIndexer.scanLibrary(LibrariesIndexer.java:229) at cc.arduino.contributions.libraries.LibrariesIndexer.scanInstalledLibraries(LibrariesIndexer.java:201) at cc.arduino.contributions.libraries.LibrariesIndexer.rescanLibraries(LibrariesIndexer.java:161) at cc.arduino.contributions.libraries.LibrariesIndexer.setLibrariesFolders(LibrariesIndexer.java:120) at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:677) at processing.app.Base.onBoardOrPortChange(Base.java:1336) at processing.app.Editor$UploadHandler.run(Editor.java:2083) at java.lang.Thread.run(Thread.java:748)**

# Answer
> 0 votes
The UNO can't be a Keyboard. It doesn't have a real USB connection. It has a serial connection that passes through a UART to USB converter.

You cannot use the UNO as a keyboard.

Instead you need one of the boards that has a *real* USB connection, such as the Arduino Leonardo or any of the other ATMega32U4-based boards.

---
Tags: arduino-uno, library, arduino-leonardo, keyboard, keypad
---


title: Arduino bluetooth HC-05 servo control

text:
# Question
Title: Arduino bluetooth HC-05 servo control
I am using HC-05 Bluetooth module to control two servos. I use Bluetooth terminal in my android phone to control them.

Problem is that myServo1 is moving like I want but I can't control myServo2. Code is reading the variable a but it can't read variable b.

```
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myServo1;
Servo myServo2;
int servo;
SoftwareSerial BT(2, 3);
void setup()
{
myServo1.attach(11);
myServo2.attach(10);
servo = 90;

Serial.begin(9600);
BT.begin(9600);
}
char a;
char b;
void loop()
{
 if (BT.available())
{
a=(BT.read());
b = (BT.read());
if (a=='1')
{
  myServo1.write(180);
  delay(50);

}
if (a=='2')
{
  myServo1.write(-180);
  delay(50);

 }
  if (b=='3')
{
  myServo2.write(90);
  delay(50);

}
  if (b=='4')
{
  myServo2.write(-90);
  delay(50);

}
}
}

```

Where is the problem?

# Answer
> 0 votes
When using

```
if(BT.available())

```

that's doing the same as

```
if(BT.available() > 0)

```

But then you are reading 2 bytes, though you cannot be sure, that there are 2 bytes to read. The data is transmitted serially, so even when you send it on your phone in one bunch, it does not get transmitted as bunch.

Try to use

```
if(BT.available() >= 2)

```

Also makes sure, that nothing else gets send over serial besides the numbers (often there is a line ending send implicitly depending on the used app).

---
Tags: arduino-uno, servo, hc-05
---


# Question
Title: CIPSEND to ESP8266 returning bytes but no content
I am trying to send a GET request from an Arduino Uno connected to an ESP8266 through SoftwareSerial. I can't get it working directly in the code so I've stripped it down to a script that passes serial monitor queries like so:

```
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial esp8266 (rxPin, txPin);

void setup()
{
  Serial.begin(115200);
  esp8266.begin(115200);
  delay(1000);
}

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

```

I setup and connect the ESP8266 to my router like so from the serial monitor:

```
AT+RST
AT+CWMODE=3
AT+CWJAP="rwifi name","wifi password"
AT+CIFSR
AT+CIPMUX=0
AT+CIPSTART="TCP","www.abcdefg.com",80
AT+CIPSEND=61
GET /in-progress/ab/i.php?c=20 HTTP/1.0 Host: www.abcdefg.com

```

Everything works fine up until the CIPSEND, the GET request part, and the serial monitor output the following:

```
AT+CIPSEND=61

OK
> i.php?c=20 HTTP/1.0

busy s...
Recv 61 bytes
SEND OK

```

I know there is a 64 byte limit for the serial monitor. my GET is 61 bytes. I'm getting bytes back but not the content from the page (it should be the word "yes") and not even a content from a 404 page. Web side my php page is a counter that adds 1 to a number in a txt file - it doesn't increment (it does work if I call it from the web browser).

Where I am going wrong here with my CIPSEND? It looks like it is correctly formed to me.

-----edit-----

Based on comments below this is the latest GET request I have tried:

```
AT+CIPSEND=73
GET /i.php HTTP/1.1\r\nHost: www.abcdefg.com\r\nConnection: close\r\n\r\n

```

I have shortened my pathway to the php file as much as possible, added the carriage returns and newlines between request and each header, added the double carriage return and newline at the end. The request now returns `+IPD,919:HTTP/1.1 400 Bad Request`. This error 400 is not logged on my website.

# Answer
In my experience, the "busy" message appears when you try to start a new AT command or to send data before the ESP8266 is ready. You say that you are running this test with the commands in "a script" which suggests to me that there is no significant delay between lines.

You should either wait between commands until the EXP8266 responds (usually with "OK" or "\>") or add a delay of a few seconds between commands.
> 1 votes

---
Tags: serial, esp8266
---


# Question
Title: Weird behavior of variables when replacing for loops with if statement
See the picture of serial monitor showing I get a large number, 4 billion, when I multiply two called functions together. It always happens after 53 if I change the amount the if statement counts to. I serial monitored the if statement and it counts to 600 then down then up and repeats good and the sensorValue stays the same.
I get rid of the division in y and I put it all in the for loop and still get a large number. My purpose is to fade pin and adjusts analogWrite at same time. It adjusts but does not fade. Does replacing for loop with if statement or calling to many functions create a bug.

```

int analogInPin = A0;
int analogOutPin3 = 3;

int sensorValue;

int i = 0;
int a;
int y;

void sens(int &sensorValue){
  sensorValue = (((long)analogRead(analogInPin)*255)/1023);
}

void inOut(int &i){
  if (i > -1){
    i = i + a;
  if (i == 0){
     a = 1;
  }
  if (i == 600){
    a = -1;
  }
  return i;
 }
}

void updateFade(){
  sens(sensorValue);
  inOut(i);
  unsigned long y = ((sensorValue*i)/600);
  Serial.println(sensorValue);
}

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

void loop() {
  updateFade();
  delay(100);
  analogWrite(3, y);
}

```

# Answer
You define i,y,i as global variables so there is no need to hand them over to different functions. They can be accessed and changed in all parts of your program.

define instead of

```
int y;

```

change to

```
long y;

```

and change

```
 void inOut(int &i){

```

to

```
void inOut(){

```

and remove

```
   return i;// Its a global var

```

change the line

```
unsigned long y = ((sensorValue*i)/600);

```

to

```
y = ((sensorValue*i)/600);

```

Try to avoid the same names for global and local vars. It might happen that the compiler handles it as a redefinition, which might lead to all sort of trouble in complex programs. (Also for you if you look onto an ill documented code some months later)
And get rid of the delay it stops processing (also your subroutines) see Blinkwithoutdelay how to do it properly
ArduinoIDE-\>file-\>examples-\>2 Digital-\>Blinkwithoutdelay
> 2 votes

# Answer
Thanks for the help, this is my working code. I changed things to long, got rid of some long's, stopped passing variables, and forced number in sensorValue to be long. It now counts up and down were I set the potentiometer every minute.

```

int analogInPin = A0;
int analogOutPin3 = 3;

long sensorValue;

int i = 0;
int a;
long y;

void sens(){
  sensorValue = ((analogRead(analogInPin)*255L)/1023); //force 255 to be long
}

void inOut(){
  if (i > -1){
    i = i + a;
  if (i == 0){
     a = 1;
  }
  if (i == 600){
    a = -1;
  }
 }
}

void updateFade(){
  sens();
  inOut();
  y = ((sensorValue*i)/600);
  Serial.println(y);
}

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

void loop() {
  updateFade();
  delay(100);
  analogWrite(3, y);
}

```
> 1 votes

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


title: Can I connect a DS3231 and an MPU6050?

text:
# Question
Title: Can I connect a DS3231 and an MPU6050?
Can I connect a DS3231 and an MPU6050 by an Arduino Mega 2560? I have connect it:

```
MPU 6050               Arduino Mega 2560
SDA           =        SDA
SCL           =        SCL
GND           =        GND
VCC           =        5V

```

And I have connected DS3231 to SDA and SCL beside AREF pin:

```
DS3231               Arduino Mega 2560
SDA           =        SDA
SCL           =        SCL
GND           =        GND
VCC           =        5V

```

The problem is when I connect both of them MPU6050 prints nan, after opening the DS3231 pin from the arduino, MPU6050 prints the correct angles. Can someone please help me?

Code:

```
#include "MPU6050.h"
#include "Wire.h"
#include <DS3231.h>
MPU6050 accelgyro;
int16_t ax, ay, az, gx, gy, gz;

DS3231 rtc(SDA, SCL);

double timeStep, time, timePrev;
double arx, ary, arz, grx, gry, grz, gsx, gsy, gsz, rx, ry, rz;

int i;
double gyroScale = 131;

void setup() {
  Wire.begin();
  accelgyro.initialize();
  Serial.begin(9600);
  rtc.begin();
}

void loop() {
  timePrev = time;
  time = millis();
  timeStep = (time - timePrev) / 1000;
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
  gsx = gx/gyroScale;   gsy = gy/gyroScale;   gsz = gz/gyroScale;
  arx = (180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
  ary = (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));
  arz = (180/3.141592) * atan(sqrt(square(ay) + square(ax)) / az);
  if (i == 1) {
    grx = arx;
    gry = ary;
    grz = arz;
  }
  else{
    grx = grx + (timeStep * gsx);
    gry = gry + (timeStep * gsy);
    grz = grz + (timeStep * gsz);
  }
  rx = (0.1 * arx) + (0.9 * grx);
  ry = (0.1 * ary) + (0.9 * gry);
  rz = (0.1 * arz) + (0.9 * grz);
  Serial.print("X axis == ");
  Serial.println(arx);
  Serial.print("Y axis == ");
  Serial.println(ary);
  Serial.print("Z axis == ");
  Serial.println(arz);
  Serial.println(rtc.getTimeStr());
  i = i + 1;
  delay(1000);
}

```

# Answer
> 1 votes
The DS3231 library you are using works (for some bizarre reason) exclusively with its own internal bit-bang implementation of I2C. This cannot be used on the same pins as the hardware Wire library which the MPU6050 uses.

Either move the DS3231 to a different pair of pins, or find a better DS3231 library that uses the Wire library for communication.

# Answer
> 0 votes
Yes. Using i2c, you need to change the address of the MPU6050 because the default is (0x68) which is also the default and only address the DS3231 can use.

Example of changing the address from a personal sketch:

MPU6050 mpu(0x69);

So try:

MPU6050 accelgyro(0x69);

---
Tags: arduino-mega
---


title: Arduino HTTP Command - ESPEasy

text:
# Question
Title: Arduino HTTP Command - ESPEasy
I am new to Arduino and although I am starting with and creating some basic projects my end goal right now is to be able to turn my Sonoff on and off via a momentary switch attached to my Wifi enabled Arduino board (Particle Photon). I'm not looking for the code I would just like to pointed in the right direction.

I flashed my Sonoff so that it now runs ESPEasy and set it up so that I can control it from my browser using http://10.0.1.35/control?cmd=event,TurnOn to turn it on and http://10.0.1.35/control?cmd=event,TurnOff to turn it off. I have been reading about using POST or GET requests but none of the examples I find seem to send a similar command to how I currently have my Sonoff set up.

My question is what should I be looking at and reading about to be able to send these types of commands via the Arduino?

Any recommendations are greatly appreciated. I'm thoroughly enjoying getting into coding but finding this step quite challenging to say the least!

Thanks!

# Answer
Thanks for the heads up that the GET request was indeed the right way to go. I managed to work through this a bit today got the GET request to work. I also hooked up the button and got that to send the two requests on both press and release. I know this code is for the Photon but I hope it'll help someone else out

```
// TCPClient
#define LIB_DOMAIN "10.0.1.252"
TCPClient client;

// This constant won't change:
const int  buttonPin = D1;    // the pin that the pushbutton is attached to
const int ledPin = D7;       // internal LED pin

// Variables will change:
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  pinMode(ledPin, OUTPUT); // Initialize D7 pin as output
  pinMode(buttonPin, INPUT_PULLUP);
  // Initialize D1 pin as input with an internal pull-up resistor
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, turn on or off
    if (buttonState == HIGH) {
        digitalWrite(ledPin, LOW);
        //TCPClient
        client.connect(LIB_DOMAIN, 80);
        client.println("GET /control?cmd=event,TurnOff HTTP/1.0");
        client.println("Host:" LIB_DOMAIN);
        client.println("Content-Length: 0");
        client.println();
    } else {
        digitalWrite(ledPin, HIGH);
        //TCPClient
        client.connect(LIB_DOMAIN, 80);
        client.println("GET /control?cmd=event,TurnOn HTTP/1.0");
        client.println("Host:" LIB_DOMAIN);
        client.println("Content-Length: 0");
        client.println();
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

}

```
> 1 votes

---
Tags: wifi, http
---


# Question
Title: ESP8266, I am trying to establish a SoftAP and I cant seem to get the WiFilocalIP function to give me my IP
I am just trying to establish a server and it seems that I can't get the serial monitor to read the local IP of my device and my Client can't establish a connection to update the sensor value. when I run the monitor I get this:

IP Address: (IP unset)

here is my code:

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

    /// Config parameters for Access Point
    char * ssid_ap = "This Little Buddy";
    char * password_ap = "guessing";
    IPAddress local_ip(192,168,4,4);
    IPAddress gateway(192,168,4,1);
    IPAddress subnet(255,255,255,0);

    //Setup Server Object
    ESP8266WebServer server;

    //Sensors and what not here
    float sensor_value = 0.0;

    void setup() {
        //identify and start WiFi
      WiFi.mode(WIFI_AP);
      WiFi.softAPConfig(local_ip, gateway, subnet);
      WiFi.softAP(ssid_ap, password_ap);
      //sanity check
      Serial.begin(115200);
      Serial.println();
      Serial.print("IP Address: "); Serial.println(WiFi.localIP());
      //Configure the server's routes
      server.on("/", handleIndex); //using top root path for last sensor value
      server.on("/update", handleUpdate); //use this to update sensor value
      server.begin();
    }

    void loop() {
      // put your main code here, to run repeatedly:
    server.handleClient();
    }

    void handleIndex(){
      server.send(200, "text/plain", String(sensor_value));//need to refresh page to get information
    }

    void handleUpdate(){
      //value is passed by an URL argument
      sensor_value = server.arg("value").toFloat();
      Serial.println(sensor_value);
      server.send(200,"text/plain", "Updated");
    }

```

# Answer
The WiFi.localIP() is a function of the STA. To print the IP address of the SoftAP, use WiFi.softAPIP().
> 1 votes

---
Tags: esp8266, wifi
---


# Question
Title: How to split a *char and pass to a function needing uint8_t?
I have a requirement where an event has `char *newvalue`.

```
void event(char *newValue) {
//Code here
}

```

`newValue` is 2 digits. If it's 1-9 it is " 1" " 2" and 10+ is "10" "11" etc. It also can contain alpha characters as well not just numbers.

I am passing this to a function `void function(uint8_t ascii)` to display on a single digit display. If I pass `newValue` it doesn't register less than 10 as it picks up the space.

So what I am trying to achieve is if it's a single character, strip the space somehow into a `uint8_t` and if it's 2 digits strip just the right digit as a `uint_8` and have a bool where I will turn on the decimal point.

I've googled like crazy and can't seem to get something workable. If somebody can help it would be appreciated. If the above is not clear please let me know what more info you need.

The code below, 'value here' is where I want to put the rightmost value from `*newvalue`.

```
void onUfcComm2DisplayChange(char *newValue) {
  comdisp.setBrightness(9);
  comdisp.writeDigitAscii(0, 'valuehere');
  comdisp.writeDisplay();
}

void Adafruit_AlphaNum4::writeDigitAscii(uint8_t n, uint8_t a,  boolean d, boolean w) {
  uint16_t font;
  if (w == false) {
    font = pgm_read_word(alphafonttable + a);
  } else {
    font = pgm_read_word(alphafonttableWD + a);
  }
  displaybuffer[n] = font;
  if (d) displaybuffer[n] |= (1 << 14);
}

```

# Answer
> 0 votes
I'm not real clear on exactly what you want to have there, but here are a few ideas that may help:

If you know what character you want, then just get it. Like if you always want the second character (I think this is what you need):

```
void someFunc(char *p)
{
  char secondChar = p[1];
  Serial.print(secondChar);
}

```

If you just want the last character in the string no matter how long, get the length of it and then pull that character:

```
void someFunc(char *p)
{
  int len = strlen(p);
  char lastChar = p[len-1];
  Serial.print(lastChar);
}

```

If you want the last digit in the string no matter how long and no matter how many random characters that aren't digits after it:

```
void someFunc(char *p)
{
  int len = strlen(p);
  char lastDigitChar = 0;
  // Cycle backwards til we get the first digit
  for(int i=len-1; i>=0; i--){
    if(isDigit(p[i]){
      lastDigitChar = p[i];
      break;
    }
  }
  Serial.print(lastDigitChar);
}

```

---
Tags: c++, convert
---


# Question
Title: Sending MIDI CC to multiple midi Channel
Hi so i would like to send CC messages to different MIDI Channel (volume control). The CC messages are coming from one knob.

The solution i found kind of work but i'm pretty sure is not ideal and seems to introduce drift or lag: the volume isn't getting the same value from one channel to another.

My question is: is there a better way to do it than what i have done.

I use and tweak the following exemple provided in the Teensy Exemple library "USB MIDI AnalogControlChange Example"

The exemple was using this line of code to send CC (controlChange) to a specific channel:

MIDI.sendControlChange(controlNumber, controlValue, channel);

As i wanted to have multiple target channels for the third parameter i tried things like this:

MIDI.sendControlChange(controlNumber, controlValue, 1-2-3);

or

MIDI.sendControlChange(controlNumber, controlValue, (1,2,3));

or

MIDI.sendControlChange(controlNumber, controlValue, 1+2+3);

But it didn't worked. I didn't find in the documentation if this parameter could accept more than one number.

What worked is to multiply analog read of the same knob and multiply the sent message. It's not elegant (i'm new to programing of course) but also i noticed i strange latency or drift if you will: the volume of the channel did went from 0 to full volume but the one on channel 2 didn't go to zero, so the purpose failed. The idea here is to have all the midi channels (1 to 8) but the 11 to be affected by the volume knob.

Hope you can help, in advance, thanks

```
    /* USB MIDI AnalogControlChange Example

   You must select MIDI from the "Tools > USB Type" menu
   http://www.pjrc.com/teensy/td_midi.html

   This example code is in the public domain.
*/

#include <Bounce.h>

// the MIDI channel number to send messages
const int channel = 11;

// the MIDI continuous controller for each analog input
const int controllerA9 = 1; // param 1
const int controllerA8 = 2; // param 2
const int controllerA7 = 3; // cutoff
const int controllerA6 = 4; // reso
const int controllerA5 = 16; // volume (for channel 11)
const int controllerA4 = 16; // volume (for other channels exept 11

void setup() {

}

// store previously sent values, to detect changes
int previousA9 = -1;
int previousA8 = -1;
int previousA7 = -1;
int previousA6 = -1;
int previousA5 = -1;
int previousA4 = -1;

elapsedMillis msec = 0;

void loop() {
  // only check the analog inputs 50 times per second,
  // to prevent a flood of MIDI messages
  if (msec >= 20) {
    msec = 0;
    int n0 = analogRead(A9) / 8;
    int n1 = analogRead(A8) / 8;
    int n2 = analogRead(A7) / 8;
    int n3 = analogRead(A6) / 8;
    int n4 = analogRead(A5) / 8;
    int n5 = analogRead(A4) / 8;
    int n6 = analogRead(A4) / 8; //i duplicated this to be able to have a different channel target
    // only transmit MIDI messages if analog input changed
    if (n0 != previousA9) {
      usbMIDI.sendControlChange(controllerA9, n0, channel);
      previousA9 = n0;
    }
    if (n1 != previousA8) {
      usbMIDI.sendControlChange(controllerA8, n1, channel);
      previousA8 = n1;
    }
    if (n2 != previousA7) {
      usbMIDI.sendControlChange(controllerA7, n2, channel);
      previousA7 = n2;
    }
    if (n3 != previousA6) {
      usbMIDI.sendControlChange(controllerA6, n3, channel);
      previousA6 = n3;
    }
    if (n4 != previousA5) {
      usbMIDI.sendControlChange(controllerA5, n4, channel);
      previousA5 = n4;
    }

    if (n5 != previousA4) {
      usbMIDI.sendControlChange(controllerA4, n5, 1);
      previousA4 = n5;
    } // 1 here is the channel who's different from the int channel = 11

     if (n6 != previousA4) {
      usbMIDI.sendControlChange(controllerA4, n6, 2);
      previousA4 = n6;
    } // 2 here is the channel who's different from the int channel = 11

  }

  // MIDI Controllers should discard incoming MIDI messages.
  // http://forum.pjrc.com/threads/24179-Teensy-3-Ableton-Analog-CC-causes-midi-crash
  while (usbMIDI.read()) {
    // ignore incoming messages
  }
}

```

# Answer
> 0 votes
A single CC message applies to a single channel. If you want to affect multiple channels, you have to send multiple messages:

```
usbMIDI.sendControlChange(controllerAx, nx, 0);
usbMIDI.sendControlChange(controllerAx, nx, 1);
usbMIDI.sendControlChange(controllerAx, nx, 2);
usbMIDI.sendControlChange(controllerAx, nx, 3);
...

```

And this should of course be done in a loop:

```
for (int c = 0; c < 16; c++)
    if (c != 10)
        usbMIDI.sendControlChange(controllerAx, nx, c);

```

---
Tags: teensy, midi
---


title: A problem in l led or arduino nano

text:
# Question
Title: A problem in l led or arduino nano
When I am working on arduino nano and i uploaded a file that will blink led at 13th pin but rather than at 13th pin l-led is blinking. I even tried resetting it and uploading an empty file and again uploading the 13th pin blinking code but still l-led is blinking. What is the problem?

# Answer
> 0 votes
The `L` LED and pin 13 are one and the same thing. That LED is connected directly to pin 13. If you blink pin 13 then that LED will blink.

---
Tags: arduino-nano
---


# Question
Title: Arduino bluetooth HC-05 data reading problem
I have a problem with bluetooth module HC-05 and servos. If I type in bluetooth terminal 4,1 I want that servo1 turns 60 degrees 3 times. Briefly servo1 turns 60 degrees and then servo2 goes 180 and turns back and again servo1 turns 60 degrees and so on.

The bluetooth mixes the numbers. If I type "1" it gives me "49" and that's why the system is not working properly. How do I fix this data problem?

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

Servo myservo1;
Servo myservo2;
long players, cards;
int pos1 = 0;
int pos2 = 0;
int servo;
int pos = 0;
int deal = 0;

SoftwareSerial BT(2,3);

void setup() {
  Serial.begin(9600);
  BT.begin(9600);
  myservo1.attach(10);
  myservo2.attach(11);
  servo = 90;

}

void loop() {
  if(BT.available()>0) {
    players = BT.read();
    cards = BT.read();

    Serial.println(players);
    Serial.print(cards);

    pos = 180/(players-1);
    for(deal = 0; deal < cards; deal++) {
      for (pos1 = 0; pos1 <= 180 ; pos1 += pos ) {
          delay(20);
          myservo1.write(pos1);

          for (pos2=0; pos2<=180 ; pos2 +=1){
            myservo2.write(pos2);
            delay(10);
          }

          for (pos2=180; pos2>=0 ; pos2 -=1){
            myservo2.write(pos2);
            delay(15);
          }

    }
      for (pos1 <= 180; pos1 >= 0; pos1 -=1 ) {
          pos2=0;
          myservo1.write(pos1);
          delay(10);
      }
    }

  }
}

```

# Answer
You are mixing ASCII characters and integer values.

The serial data is a pure binary stream, a series of bytes. It is up to the programs on both sides to interpret, how these bytes are meant. When you type `1` into your bluetooth serial app, it already does this. It complies to the ASCII standard, which gives a meaning to every binary value between 0 and 127. Google "ASCII" to get a table of the mapping. Each character (alpha numeric and some special characters and control characters) has a binary value associated with it. That way we can interpret a binary data stream as text.

The ASCII character `1` corresponds to the decimal value 49. You are saving the read byte from the bluetooth serials as `long`, which is a big integer. So, when you are printing it, you will see the decimal value, which is 49.

**What to do now?** The easiest way is to subtract the ASCII value of `'1'` from the received byte:

```
players = BT.read() - '0';

```

`'0'` is the C/C++ representation of a single ASCII encoded character. It's the same as subtracting the decimal value `48`, but it's a bit clearer to see, what happens here. We are shifting the numbers row (0 to 9) from position 48 to position 0. That way the ASCII `'0'` is transformed to a decimal 0, the ASCII `'1'` to a decimal 1, and so on up to 9.

Note: You might want to make sure, that only numbers are used for these variables, as the principle will result in garbled data, when the user inputs some other characters. You would need to read the binary data into a temporary variable (here called `c`) and then check, if they are numeric. Either by hand:

```
if(c >= '0' && c <= '9')

```

or by a convinient function

```
if(isDigit(c))

```
> 1 votes

---
Tags: arduino-uno, bluetooth, hc-05
---


# Question
Title: What are the applicable processor for the ATmega32u4? And what are higher versions of ATmega32u4?
Can arduino uno smd r3 version handle a Keyboard.h library? it is not applicable for that arduino?

# Answer
> 1 votes
The Arduino Uno cannot use the `Keyboard` library. The microcontroller needs to have a native USB interface. The Uno uses the Atmega328p, which does not have one.

You can use the Arduino Micro or Arduino Leonardo for this.

---

For more experienced hackers: If you need to use the Uno, but still want to use extended USB capabilities (more than USB to Serial), it is possible to reprogram the Atmega32U4 on the Uno, which is only used as USB to Serial adapter chip, but of course has native USB capabilities and could create a HID/Keyboard input on the USB interface. Since that is not a task for beginners, it is not applicable for this question, but should be mentioned for future readers.

---
Tags: arduino-uno, keyboard, atmega32u4, arduino-uno-smd
---


title: Convert JSON into string for MQTT

text:
# Question
Title: Convert JSON into string for MQTT
I am trying to publish json object into string with following snippet

```
JSONVar data;
data["chipid"] = chipId;
data["co2_equivalent"] = co2_equivalent.c_str();
data["tvoc"] = tvoc.c_str();
data["h2_signal"] = h2_signal;
data["ethanol_signal"] = ethanol_signal;
data["humidity"] = humidity;
data["temperature"] = temperature;
data["absolute_hum"] = v.absolute_hum;
data["co2_equivalent_baseline"] = co2_equivalent_baseline;
data["tvoc_baseline"] = tvoc_baseline;

String data_json = JSON.stringify(data);
Serial.print(data_json);
Serial.println();
client.publish("/devices/data", data_json);

```

This give me following error during compilation.

```
  /Users/ubuntu/Desktop/Arduino/data_collection/esp32-svm30-mqtt.ino/esp32-svm30-mqtt.ino.ino: In function 'void loop()':
  esp32-svm30-mqtt.ino:271:46: error: no matching function for call to 'PubSubClient::publish(const char [14], String&)'
       client.publish("/devices/data", data_json);
                                                ^
  In file included from /Users/ubuntu/Desktop/Arduino/data_collection/esp32-svm30-mqtt.ino/esp32-svm30-mqtt.ino.ino:2:0:
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:141:12: note: candidate: boolean PubSubClient::publish(const char*, const char*)
      boolean publish(const char* topic, const char* payload);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:141:12: note:   no known conversion for argument 2 from 'String' to 'const char*'
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:142:12: note: candidate: boolean PubSubClient::publish(const char*, const char*, boolean)
      boolean publish(const char* topic, const char* payload, boolean retained);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:142:12: note:   candidate expects 3 arguments, 2 provided
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:143:12: note: candidate: boolean PubSubClient::publish(const char*, const uint8_t*, unsigned int)
      boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:143:12: note:   candidate expects 3 arguments, 2 provided
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:144:12: note: candidate: boolean PubSubClient::publish(const char*, const uint8_t*, unsigned int, boolean)
      boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:144:12: note:   candidate expects 4 arguments, 2 provided
  Multiple libraries were found for "PubSubClient.h"
   Used: /Users/ubuntu/Documents/Arduino/libraries/PubSubClient
  Multiple libraries were found for "Arduino_JSON.h"
   Used: /Users/ubuntu/Documents/Arduino/libraries/Arduino_JSON
  Multiple libraries were found for "svm30.h"
   Used: /Users/ubuntu/Documents/Arduino/libraries/svm30
  Multiple libraries were found for "Wire.h"
   Used: /Users/ubuntu/Library/Arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/Wire
  Multiple libraries were found for "WiFi.h"
   Used: /Users/ubuntu/Library/Arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/WiFi
   Not used: /Applications/Arduino.app/Contents/Java/libraries/WiFi
  exit status 1
  no matching function for call to 'PubSubClient::publish(const char [14], String&)'

```

Line `Serial.print(data_json)` does print it in serial monitor.

Update :

If I do`client.publish("/devices/data", data_json.c_str());`, it gets compiled, but data doesn't appear in mqtt.

`Serial.print(data_json.length());` prints **236**

Is my json to string conversion correct ?

# Answer
> 1 votes
> Please note: the question originally had no mention of trying to use `c_str()` \- so I'm not a retard

Point 1 JSON actually is a string
Point 2 your `data_json` varibale is a `String`
Point 3 `client.publish` doesn't work take `String` as the *payload* argument, it takes either `const char *` or `const uint8_t *`

So, what you can simply do is use `String`s `c_str` method to pas a `const char *` as the payload

i.e.

```
client.publish("/devices/data", data_json.c_str());

```

Point 4 - if you read the pubsubclient documentation, you'll see that

> The maximum message size, including header, is 128 bytes by default. This is configurable via MQTT\_MAX\_PACKET\_SIZE in PubSubClient.h. Longer messages can also be sent with the publish\_P() method.

so what you may be experiencing now is a message size too big for pubsubclient to handle - set a larger packet size before including the PubSubClientHeader.h

```
#define MQTT_MAX_PACKET_SIZE 1024
#include <pubsubclient.h>

```

If that also doesn't work, try

```
client.publish_P("/devices/data", data_json.c_str());

```

---
Tags: string, mqtt, c-string
---


title: How to subtract micros()?

text:
# Question
Title: How to subtract micros()?
I am attempting to calculate the time between pulses by comparing the micros() timestamp. I understand that you cannot just simply subtract unsigned longs, but I cannot understand what the alternative for it is.

Below is a simplified version of code. On pin 6 I receive 2ms long pulses every 2ms comparing the times returns "-19728". I'm planning to make the pulses much shorter once I figure out this math problem.

Site note: I'm using pulses to make two Arduinos send simple data via digital pins.

Thanks you.

```
int pinReceiver = 6;
int val = 0;
int isReceiving = 0;
int pauseLength = 0;
unsigned long timeStart = 0;

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

void loop() {
  noInterrupts();
  val = digitalRead(pinReceiver);

  if(val==HIGH){
    if(isReceiving==0){ //Pulse begins
      isReceiving = 1;
      pauseLength = micros() - timeStart;
      Serial.println(pauseLength);
    }

  } else {
    if(isReceiving==1){ //Pulse ends
      isReceiving = 0;
      timeStart = micros();
    }
  }
  interrupts();
}

```

# Answer
Long to Integer conversion will overflow the value and you'll get values in negative numbers.

Define the `pauseLength` as `unsigned long` to make it work.
> 1 votes

---
Tags: arduino-uno, time, mathematics
---


title: ESP-01 Programming

text:
# Question
Title: ESP-01 Programming
I have had so many problems with this board. I have a detailed list of everything I've tried at the link below, but for simplicity I will just summarize where I am now:

https://forum.arduino.cc/index.php?topic=673618.new

**What I am trying to do**

I want to connect my Arduino Nano to the internet using an ESP8266 ESP-01. Links to board references below:

Arduino Nano: https://128217-368301-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2017/06/NSE-1004-2\_7.jpg

ESP01:

My Arduino is a clone. Here is the exact model: https://www.amazon.com/Longruner-ATmega328P-Controller-Module-Arduino/dp/B01MSYWE6B/ref=sr\_1\_7?dchild=1&keywords=arduinonano&qid=1585358071&sr=8-7

I have a server running on my network that will take two types of requests from these Arduinos. One Arduino/ESP pair will send data from sensors to the server, another pair will take that data from the server. These are dedicated processes. The sender will never receive and the receiver will never send.

**Circuit**

Three devices are at play: Arduino Nano (AN), ESP, and External Power Supply (EXPWS)

*ESP*: VCC -\> 3.3v EXPWS

GND -\> GND EXPWS

CH\_PD -\> 3.3v EXPWS

RX -\> RX AN\*

TX -\> TX AN\*

GPIO0 -\> 3.3v EXPWS\*

RESET -\> 3.3v EXPWS\*

*Arduino*

GND -\> GND EXPWS

GND -\> Reset AN\*

* I have tested various configurations of these. GPIO0 to ground, Reset of ESP to nothing, inverting RX and TX depending on what I am doing, etc. GND to Reset on the Arduino is when I try to upload to the ESP using the Arduino as a USB TTL converter. More on that later.

**Where I am**

I have been able to communicate with the ESP using the Arduino IDE via AT commands in the Serial monitor. I have connected the ESP to my WiFi network, can ping it from my Mac, and have set the default baud rate to 9600.

**Things I cannot do**

I cannot access AT commands when this sketch is uploaded to the Arduino:

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

}

void loop() {
  // put your main code here, to run repeatedly:

}

```

But I can access AT commands with the following two:

```
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

```

and

```
void setup() {
  int i = 0;

}

void loop() {
  // put your main code here, to run repeatedly:

}

```

This tells me that trying to use Serial commands is causing a problem. I considered trying to work the ESP by sending AT commands via Serial communications, but, as per my description above, I received no responses from the ESP.

I also cannot use libraries intended for the ESP, namely WiFiEsp. I receive the error:

```
[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] No tag found
WiFi shield not present

```

When I run any example sketches provided by the library (even when I change parameters such as baud rate and adding delay statements to the library code). Here is a link to that library, you can find the examples there: https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClientRepeating/WebClientRepeating.ino

I also cannot upload sketches directly to the ESP using the Arduino as a USB TTL converter. I have tried grounding the Arduino reset pin while uploading, grounding it during compiling then pulling that connection when it starts to upload, and doing nothing to the Arduino reset pin. I have tried different combinations with the GPIO0 pin (ground, vcc, nothing), as well as the other pins.

**Conclusion**

I am really open to some suggestions here. The root of the problem seems to be Serial communications - it is the common thread between basic sketches on the Arduino and uploading to the ESP itself. I have four of these modules and all of them behave the same way. If I can't get a solution here, I'm going to have to give them back to Satan.

# Answer
> 1 votes
Wow this was complicated to figure out. I am able to upload code to the esp, though it doesn't run yet.

Thanks to all who commented, the suggestions did not solve the problem, but they pointed me in the right direction. Rather than using my Arduino to interface with the ESP01, I switched to a Raspberry Pi so that I could connect it directly to the pins of the computer doing the flashing. Beyond that, it is still a complicated process, which I will go through here:

**Wiring**

Format: ESP -\> Raspberry Pi

VCC -\> 3.3v (I used a breadboard to allow multiple connections)

CH\_EN -\> 3.3v

GND -\> GND

GPIO0 -\> GND

TX -\> RXD (GPIO 15)

RX -\> TXD (GPIO 14)

GPIO0 needs to be connected to GND *before you connect VCC to 3.3v*. The purpose of this is so that the chip boots in programming mode.

**Uploading**

My methodology may be less useful for some, but there is probably something useful here for others.

My Raspberry Pi is headless so I needed to interface with the ESP via command line. Arduino does not have up to date resources for this, so I tried a couple of my own.

1. First, I tried Arduino-cli - a package that can be downloaded from GitHub to compile and upload. I followed the tutorial provided by the video on the page posted below, but Arduino-cli requires you to include the FQBN of the device you are uploading to. I could not find this for the ESP and my Raspberry Pi did not recognize it on its own, so this was ultimately a dead end for me.

https://www.hackster.io/jithinsanal1610/arduino-cli-c26e6e

2. esptool.py requires python and can be installed using pip. I created a virtual environment for the package to keep it separate from the rest of my system. The tool had trouble compiling sketches, so I used the Arduino Ide on my Mac, exported a compiled binary, and then transferred that to the Raspberry Pi via a smb drive. Using the command below, I was able to flash the compiled file to my ESP01.

esptool.py --port /dev/ttyS0 write\_flash 0x1000 SketchFolder/Sketch.ino.generic.bin

Now here is the important part. **Restart the ESP01 after each flash attempt**. Unplug it from VCC, plug it back in, then upload. If you upload successfully, then run the exact same command again, it will not upload! *I suspect this may be the same problem I was running into when I was originally using the Arduino Ide*. I haven't tested this, but I received a similar message when uploads failed on the Arduino and esptool.py:

```
Connecting: ----....----....----
Failed to connect

```

and

```
Invalid head of packet

```

These are not copy/pasted error messages, but they should be enough for anyone googling the error.

It is also worth noting that I used an AT command previously to change the default baud rate to 9600. I specified in the esptool.py command -b 9600. This did not allow me to upload. Leave the command alone - the default is 115200 but you don't need to specify it even if you changed the ESP baud rate (though it may be the case that I reset this somehow. I really don't know enough about the board to say).

**Conclusion**

There are a lot of bad resources out there for this board. Frankly, I would have bought a different one had I known. But it taunted me, and I don't play games. Good luck to anyone else who tries to work with this board! I am going to post a new question for my current problem, but for now I would say this one deserves to be marked as solved.

---
Tags: esp8266
---


# Question
Title: Why are begin() functions needed to initialize hardware (if they are)?
I'm writing a program for an ATmega microcontroller using the Arduino framework. While implementing an hardware-related class (one to manage LEDs), I put some hardware initialization code such as `pinMode(OUTPUT)` in the class constructor. Then I realized that in all Arduino libraries I know the hardware initialization is done in a `begin()` or `init()`, so I created one for my Led class as well and moved `pinMode()` there.

Now I'm wondering if I really should define such initialization funcitons, i.e. why they are needed - or, if they are not, why so many libraries have them. I played around a bit and found that for example this code works on an ATmega1284 (it makes the LED on pin 28 light up).

```
struct Test {
  Test() {
    pinMode(28, OUTPUT);
    digitalWrite(28, HIGH);
    // other stuff
  }
  // ...
};

Test test;

void setup() {
}

void loop() {
}

```

I presume that this code is somehow ill-conceived, letting alone the fact that it lights up a led without any code in the main function (or maybe that is exaclty the problem?), but if so I can not see why. What did I not consider? Should the code above be rather writte as in the following snippet, as the existence of all these `begin()` functions leads me to believe?

```
struct Test {
  Test() {
    // other stuff
  }
  void begin() {
    pinMode(28, OUTPUT);
    digitalWrite(28, HIGH);
  }
  // ...
};

Test test;

void setup() {
  test.begin();
}

void loop() {
}

```

# Answer
> 1 votes
It's all to do with the order of execution.

Constructors are executed before normal functions. That includes the `main()` function which eventually calls `setup()` and (repeatedly) `loop()`. One of the other things that `main()` does is call `init()` (or some variant of) which configures the hardware.

Since that happens *after* any global constructors have been run anything that the constructor did to the hardware could potentially be undone.

Thus it is normal to defer any hardware configuration until *after* `main()` has done the work of setting things up, and the convention is to use a `begin()` function to do it.

---
Tags: programming
---


# Question
Title: Cannot power up Arduino Uno + Ethernet Shield with other than computer USB
I have successfully wrote a sketch for Ethernet Shield and Arduino. If I plug it into computer's USB, it works.

But if I plug into any other power source, like USB power adapter from iPhone or laboratory power source to power socket -- it doesn't work.

LEDs are doing various strange bursts, very different than if powered from computer.

What can be the reason?

**UPDATE**

I have updated sketch so that it doesn't refer serial:

```
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
// B6-62-C5-CC-48-81
byte mac[] = {
  0xB6, 0x62, 0xC5, 0xCC, 0x48, 0x81
};
IPAddress ip(192, 168, 10, 90);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

long requestCount = 0;
long upCounts[] = {0, 0, 0, 0, 0, 0};
long downCounts[] = {0, 0, 0, 0, 0, 0};
int currVals[] = {0, 0, 0, 0, 0, 0};
int prevStats[]= {0, 0, 0, 0, 0, 0};
int upThreshold = 1024-32;
int downThreshold = 32;

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

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
//  Serial.print("server is at ");
//  Serial.println(Ethernet.localIP());
}

void loop() {

  for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
    int sensorReading = analogRead(analogChannel);
    currVals[analogChannel] = sensorReading;

    if( prevStats[analogChannel] == 0 ) {
      if( currVals[analogChannel] >= upThreshold ) {
        prevStats[analogChannel] = 1;
        if( requestCount>0 ) {
          upCounts[analogChannel] ++;
        }
      }
    }
    else {
      if( currVals[analogChannel] < downThreshold ) {
        prevStats[analogChannel] = 0;
        if( requestCount>0 ) {
          downCounts[analogChannel] ++;
        }
      }
    }
  }

  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    //Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        //Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 2");  // refresh the page automatically every 2 sec

          client.print("X-Inthemoon-Request-Count: ");
          client.println(requestCount);
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            client.print("X-Inthemoon-Analog-To-Digital: ");
            client.print("Channel=");
            client.print(analogChannel);
            client.print("; ");
            client.print("Min-Value=0; ");
            client.print("Max-Value=1023; ");
            client.print("Value=");
            client.print(currVals[analogChannel]);
            client.print("; ");
            client.print("Up-Change-Count=");
            client.print(upCounts[analogChannel]);
            client.print("; ");
            client.print("Down-Change-Count=");
            client.print(downCounts[analogChannel]);
            client.println(";");
          }

          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          client.print("Was counting: ");
          if( requestCount>0 ) {
            client.print("YES (request count is ");
            client.print(requestCount);
            client.print(")");
          }
          else {
            client.print("NO");
          }
          client.println("<br />");
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(currVals[analogChannel]);
            client.print(", up changes count is ");
            client.print(upCounts[analogChannel]);
            client.print(", and down changes count is ");
            client.print(downCounts[analogChannel]);
            client.println("<br />");
          }
          client.println("</html>");

          requestCount++;
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    //Serial.println("client disconnected");
  }
}

```

The situation is the same:

https://youtu.be/vypaNOxZ5KI

It is plugged into Samsung tablet USB power of 2A, so insufficient current is unprobable reason.

**UPDATE 2**

I also tried to remove inclusion of `SPI.h`

**UPDATE 3**

If I connect another Arduino board (but of the same vendor, it is from AliExpress), the behavior is the same.

**UPDATE 4**

I have compiled blink example and it works in any combination. If I connect Ethernet shield, then it blinks with both LEDs on Arduino board and on Ethernet shield.

**UPDATE 5**

I bought different Ethernet Board and it doesn't work too.

Please help. Have anybody ever powering Arduino + Ethernet not from USB?

# Answer
> 2 votes
Sorry I didn't see this earlier but I suspect you have a bad earth, because:

1. It works with the PC
2. You are using a wall wart
3. You are wiring your board to another electrical source (Ethernet)
4. You are saying the LEDs are flashing differently.

Run a lead from the GND connector on the board to an Earth point.
(It might be the Ethernet that is at fault, but unless you have access to the switch I don't know how you could ground that properly)

# Answer
> 0 votes
There should be absolutely no difference between powering your Arduino from a computer USB port or a wall plug, especially if you keep your serial monitor closed.

So this is the debug procedure I would advice:

1. disconnect the shield
2. connect the Arduino and upload a firmware with

* no calls to `Serial`, but the most important one you must avoid is the `while` loop in the `setup()` function
    * a short blink of an LED (you can use the onboard one, if you wish so) every time the `loop()` function iterates
3. power your Arduino (without the shield attached) from your computer with **no serial consoles** and check the LED blinks at constant intervals
4. power your Arduino (without the shield attached) from your wall plug and check the LED blinks at constant intervals
5. disconnect the wall plug, attach the ethernet shield **without** an ethernet cable, reconnect the wall plug and check the *debug* LED and the LEDs on the shield are all blinking as expected
6. plug the ethernet cable and hit the Arduino reset button and check all the LEDs are blinking as expected

Possible faults i can currently think of:

* **STEP 3**
    + the firmware running on your board is incorrect: double check the compilation and upload process has completed successfully and you have no error in the Arduino IDE console
* **STEP 4**
    + the firmware still contains some code which expects some input from the serial console: start opening the libraries you use in search for such code
    + the voltage measured at the board between `GND` and `5V` pins is insufficient and the board browns out: check the voltage is above 4.5V and the USB cable is not damaged or faulty
* **STEP 5**
    + some of the code inside the ethernet shield library is trying to read data from a serial connection: check the library code again
    + some of the components on the ethernet shield are faulty and they are pulling enough current from your wall wart to actually make your board go into protection (hard to believe, a 2A *serious* wall plug should be much better power source than your PC)
* **STEP 6**
    + same as for step 5, but your ethernet cable might be playing a role

This might not be an answer *per se*, but it might help you find out the answer you need.

# Answer
> 0 votes
Maybe your laboratory power source is of poor quality. A computer's USB is a good power source. Try using a pack of 4x1.5v AA batteries. I have use this setup with arduino+ethernet shield+cheap servo.

# Answer
> 0 votes
I too have had this problem with a Mega. It was working with my SCADA package, running on linux and you could ping the Mega/ Ethernet board, but then something changed, and it wouldn't run/ read using the ehternet port. Had two units, and both behaved the same.

When connected to the programming laptop ( runing W7) and the ethernet port, and running serial monitor, ethernet functions would work. De powering and repowering using W7 usb port wouldn't work. Tried removing all calls to Serial.print(ln) via if Debug type logic , didn't fix the problem.

Restoring the Serial messages didn't change the behaviour.

The "fix" is to press the reset button on the ethernet board after powering up, power source independent. Giving the stack a general reset via the reset pins doesn't work, it needs to be the reset button on the ethernet module.

Did it via the unit connected to the linux machine and instantly got ping, and the SCADA system reading data.

If anyone can shed more light on the need to reset the ethernet module after power up I would be delighted.

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


# Question
Title: Remove blocking delay() toneMelody function?
I would like to change the delay() into a nonblocking function in the code below. I've implemented it (a part of a tutorial from arduino.cc) in my code, but the delay() is blocking the rest of my code. Can anyone help me to change this?

```
void speelMelodie(int melodie){

if(melodie == 1){

      for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      tone(speaker, melody1[thisNote], noteDuration);

      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes); // <-- this one has to be changed

      noTone(speaker);
      }
  }

else if (melodie == 2) {
      // the same part as previous part (for loop)
  }

else if (melodie == 3) {
      // the same part as previous part (for loop)
  }
}

```

# Answer
Define global vars befor setup()

```
unsigned long timeStamp = 0;
bool pauseOn = false;

```

and use it

```
void speelMelodie(int melodie) {

  if (melodie == 1) {

    for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      if (millis() - timeStamp < noteDuration && pauseOn == false) {
         tone(speaker, melody1[thisNote], noteDuration);
      } else { // reset value and change pauseOn to true
        pauseOn = true;
        timeStamp = millis();
      }
      int pauseBetweenNotes = noteDuration * 1.30;

      //delay(pauseBetweenNotes); // <-- this one has to be changed
      if (millis() - timeStamp < pauseBetweenNotes && pauseOn == true) {
          noTone(speaker);
      } else {
         pauseOn = false;
         timeStamp = millis();
      }
    }
  }
}

```

We need the state variable pauseOn to differentiate between the two states play note or silence. The code compiles, but you have to finetune in your program.
**A final tip** Tutorials **using delay()** other than

* for debuging or
* in setup for initializing hardware

are of very low quality
-\> Its like a blind person talking about color composition.
> 1 votes

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


title: Using esp8266 instead of xbee

text:
# Question
Title: Using esp8266 instead of xbee
I am using xbee pro s2c to get data from arduino (temp, pressure etc.) and I am sending data another xbee module and read these data from serial port.

Question is that I want to use esp8266 instead of xbee. Is it possible? Can I communicate 2 esp module like xbee?

# Answer
You can make two ESP8266 modules talk together, yes. It's not "simple" like an XBee, since you have a generic WiFi network interface, so there's many many different ways of doing it. Typically one would be running as a WiFi Access Point (SoftAP) and the other would connect to it. Then you'd run some "server" code on one module (typically the SoftAP one) and the other acts as a client and connects to it (or sends data to it).
> 1 votes

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


# Question
Title: Counter variable gets reset to 0 without resetting it(Mega)
(Arduino Mega2560) I'm trying to test placing a counter n in a for loop, the problem is, every time it gets out and goes back to the for loop, the n is reset again, so it prints "counter: 245" every time. However, when I comment out \*b++=data; and data++; it does count properly. What exactly is going on ?!

Code:

```
uint8_t i=0;
uint8_t buf[245];
uint8_t *b=buf,*b2=buf;
uint8_t data=10;
int n=0;

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

void loop() {
for(i=0; i<245 ;i++){
  *b++=data;
  data++;
  delay(50);
  n++;
  Serial.println(buf[i]);
  }
  data=0;
  delay(5000);
  Serial.println("counter:");
  Serial.println(n);
  delay(5000);
}

```

# Answer
> 2 votes
You never reset your `b` pointer. The first time through it works its way through the memory reserved for `buf`. The second time through your loop it's already at the end of that memory and you then start incrementing (and filling) past that overwriting other variables - the first of which sounds like it might be `n` \- so `*b++=data` is writing `data` (245) to `n`.

You need to reset `b` each time you go through loop so it starts at the beginning of the array each time:

```
b = buf;

```

---
Tags: arduino-mega
---


# Question
Title: Is there a way to make a function take an exact number of clock cycles?
Is it possible to use something like a compiler directive to pad a function with do nothing instructions so that as you add lines of code or take them away it always executes in the same amount of time? I know there is the blink without delay style of writing a loop, but I want something a little more exact.

# Answer
> 1 votes
To the best of my knowledge, there is not. What you speak of *is* possible, but it must be done manually by counting cycles, and I suspect it wouldn't actually help you. (And then you get into CISC issues where instructions can take different amounts of time to execute, potentially depending on arguments. Arduino (the actual one) is kinda safe from that, but branch instructions still take multiple cycles, for instance. This says nothing about all the boards that work with, but aren't, Arduinos.)

There are two potential routes for this.

1. If this is for crypto, where you want to avoid side-channel attacks by detecting the length of an authentication or hashing function, it's not a good idea. Use a well-known library to do it instead, since in practicality it's not a good or safe idea to write your own (although if it's for a homemade door lock or safe lock, it's *probably* not a relevant issue since there are larger and more important security issues that will likely be found first despite your best efforts).
2. If, as I suspect, you simply want a piece of code to run at very precise time intervals, I suggest you look up something like the FreeRTOS port for Arduino. That will let you schedule a task to run preemptively so that it will always run at intervals. The BWOD sketch is still quite accurate, mind you, and below is a self-correcting version that compensates for any times that it might run a bit late (meaning that it should ALWAYS execute with millisecond precision, repeatably):

```
  unsigned long currentMillis = millis();//and you could always use micros()

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis += interval;//adjustment for additional accuracy

    //The task you want to run would go below:
    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }

```

The caveat to your stated goal is that any microprocessor WILL NOT execute code exactly when you want. Arduino too is incapable of this, since even a blank sketch runs several interrupts that will take over the processor for short periods of time, causing your hypothetical sketch to be delayed. You HAVE to use a reference method like BWOD or a scheduler like FreeRTOS. These use a reference or set up their own interrupt to make sure that they run on time, with the only interrupts that could be an issue being the ones that run during that instance of the task.

What this means is that they have a bit of overhead to add spacing between tasks so that if one is delayed, it won't cause the next to run late. So do mind that you'll lose a *quite* small percentage of CPU time to your scheduler, but if that's really an issue, find a better board (like TI TIVA/Energia IDE).

# Answer
> 0 votes
You can use a timer with prescaler set to 1 in combination with a counter module. Attach interrupts to the compare and the overflow events. In the corresponding ISRs you handle the counting... I have no example for you and it might be a bit tricky how to implement the ISRs, but it's possible for sure, as long as you count a reasonable amount of clock cycles (firing an interrupt each cycle e.g. will not work as the calculations in the ISR take some time).

---
Tags: c++, loop
---


# Question
Title: Im having another problem with my code the error is "redefinition of 'AF_DCMotor motor'?
Heres the code

```
#include <AFMotor.h>

AF_DCMotor motor(1, MOTOR12_8KHZ);
AF_DCMotor motor(2, MOTOR12_8KHZ);
AF_DCMotor motor(3, MOTOR34_1KHZ);

void setup()  {
  Serial.begin(9600);
  Serial.printIn("Motor Test!");
  motor1.setSpeed(15); //set speed of motor
  motor2.setSpeed(15); //set speed of motor
  motor3.setSpeed(15); //set speed of motor

}
void loop() {
  Serial.print("tick");
  motor1.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor1.run(RELEASE);
  delay(5000);

  Serial.print("tack"); //first song starts
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor1.run(RELEASE);
  delay(9000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song ends
  motor1.run(RELEASE);
  delay(20000);

  Serial.print("tick");
  motor1.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(5000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song stops
  motor2.run(RELEASE);
  delay(14000);

  Serial.print("tock"); //first song stops
  motor3.run(RELEASE);
  delay(11000);

  Serial.print("tick"); //first song stops
  motor3.run(FORWARD);
  delay(22000);

  Serial.print("tock"); //first song stops
  motor3.run(RELEASE);
  delay(19000);
}

```

Here is the error:

```
   ^~~~~~

   motor

snowmanDC_Motor:13:3: error: 'motor3' was not declared in this scope

   motor3.setSpeed(15); //set speed of motor

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:13:3: note: suggested alternative: 'motor'

   motor3.setSpeed(15); //set speed of motor

   ^~~~~~

   motor

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino: In function 'void loop()':

snowmanDC_Motor:18:3: error: 'motor1' was not declared in this scope

   motor1.run(FORWARD);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:18:3: note: suggested alternative: 'motor'

   motor1.run(FORWARD);

   ^~~~~~

   motor

snowmanDC_Motor:47:3: error: 'motor2' was not declared in this scope

   motor2.run(FORWARD);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:47:3: note: suggested alternative: 'motor'

   motor2.run(FORWARD);

   ^~~~~~

   motor

snowmanDC_Motor:115:3: error: 'motor3' was not declared in this scope

   motor3.run(RELEASE);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:115:3: note: suggested alternative: 'motor'

   motor3.run(RELEASE);

   ^~~~~~

   motor

exit status 1
redefinition of 'AF_DCMotor motor'

```

# Answer
> 1 votes
Adafruit has a V1 and a V2 motor shield. They have different libraries too. AFMotor.h is for the V1 shield. From the error, I can tell you installed V2 lib. For that you need to include:

```
#include <Adafruit_MotorShield.h>

```

---
Tags: arduino-mega, adafruit, sketch, arduino-motor-shield, error
---


title: Stuck in While loop!

text:
# Question
Title: Stuck in While loop!
I am using 4 LDR To track the sun for solar panels. Not using servos, but linear actuators(a little irrelevant but just to give scope)

my code gets stuck in this while loop as soon as it enters it, even tho the conditions are changed to break the loop. I want to leave the motors running in one direction until the "dvert"=Vertical difference is less then "tol"=tolerance. there are 4 of these loops. there is an if condition before each. so no adjustment is made if its already in tolerance.

Segment of code

<pre><code>  if (avgtop > avgbot)
  {  Serial.println("enter avgtop > avgbot");
    Serial.println( "");

   while (abs(dvert) > tol)
     {
      Serial.println("Enter While loop vert up....");
      Serial.println("Moving Vertical Axis begin...Moving UP  ");

                   digitalWrite(vrelay1, HIGH);              // Setting frame down
                   digitalWrite(vrelay2, LOW);              // Setting frame down
      delay(200);
      int topl = analogRead(ldrtopl);
      int topr = analogRead(ldrtopr);
      int botl = analogRead(ldrbotl);
      int botr = analogRead(ldrbotr);
      int avgtop = (topl + topr) / 2; //average of top LDRs
      int avgbot = (botl + botr) / 2; //average of bottom LDRs
      int dvert = avgtop - avgbot; // check the diffirence of up and down

      Serial.print("NEW DVERT:"  );
      Serial.println(dvert);

  }  ```
</code></pre>

# Answer
You're masking your outer `dvert` variable (and potentially others that you want to keep) with local variables inside the loop:

```
  int dvert = avgtop - avgbot; // check the diffirence of up and down

```

If you're just assigning a new value to an existing variable you do *not* want to declare a new variable!

Instead it should be just:

```
  dvert = avgtop - avgbot; // check the diffirence of up and down

```

And the same for anything else inside the loop that you want to assign to a variable that you have created outside the loop.
> 1 votes

---
Tags: loop
---