# Question
Title: I2c device disappear from bus after writing
I am currently experiencing a really odd I2C problem on a Atmega32u4 based card. I'm trying to use a TLV493D connected by I2C. I know from this thread that before using this device, I have to set the powermode :

```
Wire.beginTransmission(HallAddressWrite);       // Address the sensor
Wire.write(configReg);              // Address the Configuration register
Wire.write(powerMode);              // Set the Power Mode to Low
errorCode = Wire.endTransmission();             // Stop transmitting

```

But each time I'm trying to write on the TLV493D register, the device simply disappear from I2C bus ! I know it sounds strange, but I can demonstrate it with a modified version of default I2C scanner

```
if (error == 0)
{
  Serial.print("I2C device found at address 0x");
  if (address<16)
    Serial.print("0");
  Serial.print(address,HEX);
  Serial.println("  !");

  Serial.println("Beginning write test...");
  Wire.beginTransmission(address);
  // no register writing
  errorCode = Wire.endTransmission();
  Serial.print("Test ended with code : ");
  Serial.println(errorCode);

  Serial.println("SECOND Beginning write test...");

  Wire.beginTransmission(address);       // Address the sensor
  Wire.write(0x00);              // Address the Configuration register
  Wire.write(0x05);            // Set the Power Mode to Low
  errorCode = Wire.endTransmission();
  Serial.print("Test ended with code : ");
  Serial.println(errorCode);

  nDevices++;
}

```

which gives the output:

```
I2C device found at address 0x5E  !
Beginning write test...
Test ended with code : 0
SECOND Beginning write test...
Test ended with code : 0

```

And next scan doesn't find anything. As you can see, I don't lost my device when I don't write anything. But it disappears from my bus as soon as I write something (here, it's for setting low power mode, but any value will do the same).

More informations :

* My code is correct. I know that because I don't have any problem when using an Arduino Uno or Arduino Mega. Unfortunately, I don't have an Arduino Leonardo to see if my problem comes from Atmega32u4.
* My wiring is correct. I checked the signal on SDA and SCL pin on the TLV493D with an oscilloscope and everything is as expected : 3.3V and 100kHz.
* I also have a SRF02 on my I2c bus : it is working as expected.
* I don't think my TLV493D is damaged. In deed, I thought it was because of that. So I changed it for another one but the problem is still here.
* I noticed than when beginning an I2C transmission at address 0x00, I am able to see my TLV493D again. But it is pointless since I have to set power mode again and thus, it disappears from bus once again.

# Answer
To sum up this problem : TLV493D configuration work by writing two bytes with I2C. You must begin by writing 0x00, which will be ignored since the first register is reserved. Then, you write a second byte that will actually do the configuration (second register). The three smalest bits enable or disable INT, FAST and LOW mode.

I still don't understand why I am not able to enable INT mode on my Atmega32u4 while it doesn't seem to be a problem on Uno or Mega (on LOW mode). Anyway, two configurations work for me :

0x07 --\> INT, FAST and LOW are all enabled

0x01 --\> only LOW is enabled

I don't think it's a issue to disable INT. If I understood correctly, it will make the device send an interrupt pulse to request microcontroller reading. If you manage readings by yourself, I don't think you need INT to be enabled.

Many thanks to CodeGorilla for his support.

**UPDATE:**

I managed to get an Arduino Leonardo. Indeed, all my obsevations on my Atmega32u4 based card are still corrects (writing 0x05 second register make the device disappear from bus, but not with 0x01 or 0x07). But again, it works normally on Uno or Mega... Really odd ! If anyone has an explanation to offer, it would be greatly appreciated.
> 0 votes

# Answer
By default the FAST register is set to 0 at power up. When the FAST mode is 0 and you set LOW to 0 you are entering Power Down mode.

Looking at your code it looks like you are not altering the FAST register which means I can simplify your question to "Why does my device disappear from the I2C bus every time I turn it off".

Just looking at page 34 of the English User Manual I would say you have to set FAST to 1 before setting LOW to 0.

Also - Do you have pull-up resistors on the I2C bus? You might encounter problems without them. They are normally around 4.7K for 5V, but I don't know what they should be for 3.3v systems.
> 1 votes

---
Tags: i2c, atmega32u4
---


title: Read pc volume percentage?

text:
# Question
Title: Read pc volume percentage?
is there a way to read the current pc volume? This is going to be a part of a project that I have in mind that is essentially reading curent pc volume value and giving it an RGB value (green=\>30, yellow=\<30\>60, red=\<60) and lighting up an RGB led accordingly.

# Answer
There is no way for any hardware device, Arduino or otherwise, to request information like that from a computer.

HID is a protocol which (when used as a keyboard) allows you to *send* keypresses, including "media keys", which tell the computer to change the volume (amongst other things). There is no provision, other than three status LEDs, for getting any data back from the computer.

You will have to write software for your computer to query that information using whatever API may be available for your operating system, and pass that information through whatever communication channel you choose to the Arduino (such as through serial).

Some pointers:
> 2 votes

# Answer
There are external devices that show the volume, but you need a driver for that. I don't know if there is an open source driver which you could adapt to send the volume via a serial port to the Arduino.

The Windows PowerShell has the possibility to get the volume and transmit it to a serial port. You could do that a few times per second. In linux it might even be easier, a bash script with gawk with "amixer sget Master".

Another problem is to select the right serial port for the Arduino. I don't know how to automatically select the right port.
> 1 votes

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


title: Waterlevel sensor disrupts PH reading

text:
# Question
Title: Waterlevel sensor disrupts PH reading
I have a water level sensor and a PH sensor connected to my nodemcu via an ADS1115. When I insert only the PH sensor into the water then everything works fine. But when I insert the waterlevel sensor into the same container the PH sensor seems to shortcircuit and I get 5V no matter the actual PH level. Is there anything im missing or a way to prevent that from happening?

# Answer
That water level sensor uses bare metal which is in contact with the water. The PH sensors are sensitive for that kind of voltage in the water, even if it would be 0V.

There are isolated PH sensor amplifier modules. On forums are often discussions whether to ground an aquarium or not for a PH sensor. With a isolated PH sensor, you avoid most of those problems.

There are also non-contact water level sensors. For example capacitive sensor or even sensors that can be attached on the outside. Some sensors use the water pressure, but I don't know if this one is isolated: https://www.sparkfun.com/products/10221
> 4 votes

---
Tags: sensors, nodemcu, adc
---


title: Robot car speed issue

text:
# Question
Title: Robot car speed issue
If I'm connecting it in this way I have no issue and I can control the speed. here is a video

```
const int speedMotorA = 9;
const int speedMotorB = 3;
const int motorPin1  = 4;
const int motorPin2  = 7;
const int motorPin3  = 12;
const int motorPin4  = 13;

void setup() {
  Serial.begin(9600);
  pinMode(speedMotorA, OUTPUT);
  pinMode(speedMotorB, OUTPUT);
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
}
void loop(){
  TurnMotorA();
  TurnMotorB();
}

void TurnMotorA() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  Serial.println(Speed);
  analogWrite(speedMotorA,Speed);
  digitalWrite(motorPin1, HIGH);
  digitalWrite(motorPin2, LOW);
}

void TurnMotorB() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  analogWrite(speedMotorB,Speed);
  digitalWrite(motorPin3, HIGH);
  digitalWrite(motorPin4, LOW);
}

```

now I'm trying to expand my mini-project with servo and ultrasonic sensor with this code and wiring, I have tried many ways to control speed but it's not working properly while increasing speed motor A respond but motor B stay off till I reach maximum speed 255 motor B start working. here is a video

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

#define TRIG_PIN A4
#define ECHO_PIN A5
#define MAX_DISTANCE 200
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
Servo myservo;

const int laser = 8;
int distance = 0;
const int speedMotorA = 9;
const int speedMotorB = 3;
const int motorPin1  = 4;
const int motorPin2  = 7;
const int motorPin3  = 12;
const int motorPin4  = 13;

int hitlaser(){
  digitalWrite(laser, HIGH);
  delay(200);
  digitalWrite(laser, LOW);
}

void setup() {
  pinMode(laser, OUTPUT);
  pinMode(speedMotorA, OUTPUT);
  pinMode(speedMotorB, OUTPUT);
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
  myservo.attach(5);
  myservo.write(65);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop() {
 int distanceR = 0;
 int distanceL =  0;
 delay(40);
 digitalWrite(laser, HIGH);
 if(distance<=50)
 {
  moveStop();
  delay(100);
  moveBackward();
  delay(300);
  moveStop();
  delay(200);
  distanceR = lookRight();
  delay(200);
  distanceL = lookLeft();
  delay(200);

  if(distanceR>=distanceL)
  {
    turnRight();
    moveStop();
  }else
  {
    turnLeft();
    moveStop();
  }
 }else
 {
  moveForward();
 }
 distance = readPing();
}

int lookRight()
{
    myservo.write(5);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(65);
    return distance;
}

int lookLeft()
{
    myservo.write(150);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(65);
    return distance;
    delay(100);
}

int readPing() {
  delay(70);
  int cm = sonar.ping_cm();
  if(cm==0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
    analogWrite(speedMotorA, 0);
    analogWrite(speedMotorB, 0);
    digitalWrite(motorPin1, LOW);
    digitalWrite(motorPin2, LOW);
    digitalWrite(motorPin3, LOW);
    digitalWrite(motorPin4, LOW);
  }

void moveForward() {
    int Speed = analogRead(A2);
    Speed = Speed*0.24926686;
    Serial.println(Speed);
    analogWrite(speedMotorA,Speed);
    analogWrite(speedMotorB,Speed);
    digitalWrite(motorPin1, HIGH);
    digitalWrite(motorPin2, LOW);
    digitalWrite(motorPin3, HIGH);
    digitalWrite(motorPin4, LOW);
}

void moveBackward() {
    int Speed = analogRead(A2);
    Speed = Speed*0.24926686;
    Serial.println(Speed);
    analogWrite(speedMotorA,Speed);
    analogWrite(speedMotorB,Speed);
    digitalWrite(motorPin1, LOW);
    digitalWrite(motorPin2, HIGH);
    digitalWrite(motorPin3, LOW);
    digitalWrite(motorPin4, HIGH);
}

void turnRight() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  Serial.println(Speed);
  analogWrite(speedMotorA,Speed);
  analogWrite(speedMotorB,Speed);
  digitalWrite(motorPin1, HIGH);
  digitalWrite(motorPin2, LOW);
  digitalWrite(motorPin3, LOW);
  digitalWrite(motorPin4, HIGH);
  delay(300);
  moveForward();
}

void turnLeft() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  Serial.println(Speed);
  analogWrite(speedMotorA,Speed);
  analogWrite(speedMotorB,Speed);
  digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, HIGH);
  digitalWrite(motorPin3, HIGH);
  digitalWrite(motorPin4, LOW);
  delay(300);
  moveForward();
}

```

update :

after removing servo from the project it seems working but how can i use servo with this project Thanks to Majenko♦ **update 2** after attaching servo to pin 9 i can now controle speed but still some issues as when Robot car have obsticles it should make backword \>\> issue is \>\> one motor only go backword!.

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

#define TRIG_PIN A4
#define ECHO_PIN A5
#define MAX_DISTANCE 200
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
Servo myservo;

const int laser = 8;
int distance = 0;
const int speedMotorA = 11;
const int speedMotorB = 3;
const int motorPin1  = 4;
const int motorPin2  = 7;
const int motorPin3  = 12;
const int motorPin4  = 13;

int hitlaser(){
  digitalWrite(laser, HIGH);
  delay(200);
  digitalWrite(laser, LOW);
}

void setup() {
  pinMode(laser, OUTPUT);
  pinMode(speedMotorA, OUTPUT);
  pinMode(speedMotorB, OUTPUT);
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
  myservo.attach(9);
  myservo.write(65);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop() {
 int distanceR = 0;
 int distanceL =  0;
 delay(40);
 digitalWrite(laser, HIGH);
 if(distance<=50)
 {
  moveStop();
  delay(100);
  moveBackward();
  delay(1000);
  moveStop();
  delay(200);
  distanceR = lookRight();
  delay(200);
  distanceL = lookLeft();
  delay(200);

  if(distanceR>=distanceL)
  {
    turnRight();
    moveStop();
  }else
  {
    turnLeft();
    moveStop();
  }
 }else
 {
  moveForward();
 }
 distance = readPing();
}

int lookRight()
{
    myservo.write(5);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(65);
    return distance;
}

int lookLeft()
{
    myservo.write(150);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(65);
    return distance;
    delay(100);
}

int readPing() {
  delay(70);
  int cm = sonar.ping_cm();
  if(cm==0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
    analogWrite(speedMotorA, 0);
    analogWrite(speedMotorB, 0);
    digitalWrite(motorPin1, LOW);
    digitalWrite(motorPin2, LOW);
    digitalWrite(motorPin3, LOW);
    digitalWrite(motorPin4, LOW);
  }

void moveForward() {
    int Speed = analogRead(A2);
    Speed = Speed*0.24926686;
    Serial.println(Speed);
    analogWrite(speedMotorA,Speed);
    analogWrite(speedMotorB,Speed);
    digitalWrite(motorPin1, HIGH);
    digitalWrite(motorPin2, LOW);
    digitalWrite(motorPin3, HIGH);
    digitalWrite(motorPin4, LOW);
}

void moveBackward() {
    int Speed = analogRead(A2);
    Speed = Speed*0.24926686;
    Serial.println(Speed);
    analogWrite(speedMotorA,Speed);
    analogWrite(speedMotorB,Speed);
    digitalWrite(motorPin1, LOW);
    digitalWrite(motorPin2, HIGH);
    digitalWrite(motorPin3, LOW);
    digitalWrite(motorPin4, HIGH);
}

void turnRight() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  Serial.println(Speed);
  analogWrite(speedMotorA,Speed);
  analogWrite(speedMotorB,Speed);
  digitalWrite(motorPin1, HIGH);
  digitalWrite(motorPin2, LOW);
  digitalWrite(motorPin3, LOW);
  digitalWrite(motorPin4, HIGH);
  delay(300);
  moveForward();
}

void turnLeft() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  Serial.println(Speed);
  analogWrite(speedMotorA,Speed);
  analogWrite(speedMotorB,Speed);
  digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, HIGH);
  digitalWrite(motorPin3, HIGH);
  digitalWrite(motorPin4, LOW);
  delay(300);
  moveForward();
}

```

Appreciate your support

# Answer
> 0 votes
The problem here is a conflict of resources. Both the Servo library and the PWM for pin 9 require the same timer.

> The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

You should choose a different PWM pin (not pin 10) instead of pin 9.

---
Tags: robotics, speed
---


# Question
Title: Why can't my bluetooth receive serial data from my android phone, but can send serial data from my bluetooth to my android phone?
I can receive serial data from my phone but I can't send serial data to the arduino using bluetooth. I can see my input from serial monitor to my Android but not the other way. I'm using ARF7044A bluetooth module if that matters. Any help would be appreciated please.

Arduino to Android: Working
Android to Arduino: Not working.

Here is the wiring:

Here is the code:

```
char state;
void setup()
{
pinMode(8, OUTPUT);
Serial.begin(9600);
}

void loop()
{

  if(Serial.available())
  {
    state = Serial.read();
    Serial.println(state);
  }
  if (state == 'a')
  {
    digitalWrite(8, HIGH);
  }
  else if(state == 'b')
  {
    digitalWrite(8,LOW);
  }
}

```

# Answer
Your erroneous level shifting attempt from Bluetooth TX to Arduino RX is the root of your problem.

Pins 0 and 1 are also connected to the on-board USB interface chip via a pair of 1kΩ resistors. These resistors serve two purposes:

1. To "weaken" the drive of the USB chip's UART interface (actually only needed on the USB chip's TX -\> Arduino RX connection), and
2. To protect both the USB chip and the main MCU from damage should two connected pins be set to opposing levels, which would cause high currents to flow through both output drivers.

The TX pin of the USB chip is actively driven HIGH all the time when idle (stupid design by Arduino, it should be Hi-Z when the port is not open), and the RX pin is pulled up by the internal pullup resistor in the USB chip. Further, when the Arduino's `Serial` is in use the TX pin of the Arduino is actively driven HIGH when idle (or LOW when transmitting a "1" bit).

The actual circuit you have looks more like this:

simulate this circuit – Schematic created using CircuitLab

Transmitting from the Arduino to the BT module is straight forward enough - the "high" point of the circuit is the Arduno's TX pin at 5V when idle. Current flows through R2 to the USB RX pin, and through R5 to the BT RX pin, with a portion split off to ground, which is what you want for your level shifting.

Communication in the other direction, however, is different, because you have two balanced "high" points in your circuit - one at the USB TX and one at the Bluetooth TX - and the fact you have 1kΩ resistors in both branches means that neither transmitter is "stronger" than the other. This means that when the BT TX is LOW (0V) you have around 2.5V at the Arduino RX pin (5V over two 1kΩ resistors = 2.5V in the center tap - see here).

Since 2.5V is neither within the Arduino's HIGH nor LOW voltage ranges (which are more than 3.5V for HIGH and less than 1.5V for LOW when running from 5V) the input is completely ignored.

The 3.3V transmitted by the Bluetooth module is a little under the *official* threshold for a HIGH signal on an Arduino, but in practice, it usually is detected fine. So remove the resistor network from the Bluetooth's TX pin and connect it directly to the Arduino. Since the input threshold voltage is a function of the supply voltage (0.7 * Vcc) it depends very much on your power supply as to whether it will work reliably or not. If you find it doesn't, you should use some *upward* level shifting. There are simple MOSFET based bi-directional level shifters available cheaply that are a better solution than resistors, and will allow proper operation in both directions, shifting a high voltage to a low one and a low voltage to a high one. These are good for lower frequency communications such as UART. If you should need higher frequency, or you find a simple MOSFET based shifter isn't working for you then a 74HCT08 or similar chip (be sure to use the HCT range not the HC range) or a dedicated level shifting chip may be in order.
> 1 votes

# Answer
For a reliable solution you must move the Bluetooth device to pins other than digital 0 and 1 and use a software serial instance to communicate with it.

Digital pins 0 and 1 are for communication with the host computer, and the USB-serial chip is permanently wired to them, *even if you are not trying to communicate with the computer*.

There is on many boards a series resistor which allows an external circuit to overpower the USB-serial, but your mis-conceived level shifter has enough resistance itself that it is not able to do this.

Fortunately, while ill-conceived the level shifter is still wired with the idea that the Arduino side is the higher voltage one, so while it adds some load to the Bluetooth, it mostly just adds series resistance. If the Arduino pin were an ordinary high-impedance once, this would probably still work. But instead it is one which the USB-serial is trying to control through its own comparable value resistor, and the result is an invalid logic level or a tug-of-war which the USB-serial wins.
> -1 votes

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


# Question
Title: How do I execute some code at a certain time without RTC module?
I am building a project when I need my arduino to execute some code at two given hours of the day, for example one at 19:00 and another at 06:00. I know that with a RTC module I can do this easily, however how can I do that without a RTC module? I do not want to have to connect my arduino to a computer neither to the internet. It does not also have to be precise, a couple of minutes off would be ok.

My board is an Uno R3.

# Answer
If you start with the "BlinkWithoutDelay" sketch that comes with the Arduino IDE, you can execute your code alternating between 11 hours and 13 hours.

```
// Power up the circuit at exactly 06:00.
unsigned long delayInterval = 0;
unsigned long previousMillis = 0;
bool twoHoursAdded = false;

void setup(){

}

void loop(){

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis >= delayInterval){

    // previousMillis = currentMillis;

    // Use this "method" of incrementing the previousMillis variable
    // instead of the code used in the BlinkWithoutDelay sketch.
    previousMillis += delayInterval;

    if(twoHoursAdded == false){
      delayInterval = 1000UL * 60UL * 60UL * 13UL;
      twoHoursAdded = true;
    }
    else{
      delayInterval = 1000UL * 60UL * 60UL * 11UL;
      twoHoursAdded = false;
    }

    // Your code here that is run at 06:00 and 19:00.

  }
}

```

"Down sides" to using this code.

1. If there is a "power failure", the timing will be off, WAY off until you reboot the Arduino at exactly the right time.
2. You have to power up the Arduino at exactly the right moment for "it's" timing to match your "clock" timing.

If it's within your budget, have a look at the DS3231 modules available on aliexpress.com / ebay.com. They have a lithium battery backup incase of power outage and are really easy to connect to your Arduino using I2C. There are several libraries on Github that simplify using the DS3231 modules.
> 3 votes

# Answer
I am not sure why you are opposed to the RTC or whether you were excluding all external circuitry for the solution. So, I am just throwing this out there...

A CMOS-4060 ripple counter can be programmed for just about any time period and using two of them would give you two separate time constants.

source Substitute the relay for a signal wire to the CPU.

The Cmos 4060 is a 14-bit binary counter. However - only ten of those bits are connected to output pins. The remaining bits - Q1, Q2, Q3 and Q11 - do exist. You just can't reach them.

The 4060 also has two inverters - connected in series across pins 11, 10 & 9. Together with R3, R4, R5 and C3 - they form a simple oscillator.

While the oscillator is running - the 14-bit counter counts the number of oscillations - and the state of the count is reflected in the output pins.

By adjusting R4 you can alter the frequency of the oscillator. So you can control the speed at which the count progresses. In other words - you can decide how long it will take for any given output pin to go high.

When that pin goes high - it switches the transistor - and the transistor in turn operates the relay.

In single-shot mode - the output pin does a second job. It uses D1 to disable the oscillator - so the count stops with the output pin high. .

If you want to use the timer in repeating mode - simply leave out D1. The count will carry on indefinitely. And the output pin will continue to switch the transistor on and off - at the same regular time intervals.

For example, if you want a period of 9 Hours - the Range table shows that you can use the output at Pin 2. You need Pin 2 to go high after 9 x 60 x 60 = 32 400 seconds. The Setup table tells you to divide this by 512 - giving about 63 seconds. Adjust R4 so that the Yellow LED lights 63 seconds after power is applied. This will give an output at Pin 2 after about 9 Hours.

If you increase the value of R3 - and reduce R4 by the corresponding amount - you can set the time delay more precisely. Select a value for R3 that takes you close to the time you're after. And use the reduced value pot - to make the fine adjustment. Note that even finer adjustments are possible with a multi-turn pot.

---

As mentioned with *VE7JRO's* solution, this solution (while being pretty accurate) will eventually drift with time and must be powered up at an exact time that is synchronized with the desired trip times.
> -1 votes

---
Tags: time
---


# Question
Title: Is it possible to burn a bootloader to an ATTiny85 with USB TTL and avrdude?
I have:

1. An Digispark clone (with no Arduino bootloader)
2. A USB -\> TTL serial device
3. A development breadboard
4. Avrdude

I want to burn the micronucleus bootloader to the chip.

Is this possible, are there instructions?

ISP programmer is in the post but I'm not expecting it for 3 weeks.

# Answer
> 1 votes
No, you can't because a USB -\> TTL serial device is not made for that. You CAN however use an Arduino Uno to burn a bootloader to another Atmel micro, including the Attiny85.

Now you may ask, can you use the Digispark in place of the Uno (and thus burn more Attiny chips). The answer is a *qualified yes*. Another Arduino can do this -- search the web and find many examples.

You might (?) even adapt that sketch from the Uno to the Digispark (saving the cost of an Uno). I can't advise further and you're looking at a rabbit hole of possible issues.

Sparkfun does sell a chip which can perform boot-loading using minimal components: https://learn.sparkfun.com/tutorials/how-to-install-an-attiny-bootloader-with-virtual-usb

# Answer
> 0 votes
Short answer, no. You can burn a bootloader onto the chip using a programmer, and then the bootloader does the serial communication magic so you can upload your sketches via serial or even low-speed USB (if your bootloader knows how to do USB bit-banging). But you can burn the bootloader only through SPI.

# Answer
> 0 votes
you can't program your hardware with just USB to tty converter you need a programmer for that now instead of buying expensive programmers you can buy an Arduino board and use it as ISP (In System Programmer) here is the link describing the whole process.

Adruino as a ISP

---
Tags: attiny, bootloader, digispark
---


title: Output voltage of PIR sensor

text:
# Question
Title: Output voltage of PIR sensor
Case 1 I am measuring output voltage of PIR sensor, I am getting 3.3v

Case 2 I have connected a resistor and a led to output of PIR sensor. Now when I measure voltage at the output pin of the sensor, I am getting 2.04v only.

In case 2 as the output voltage is dropped, it is not able to trigger a high state to arduino pin.

Where am I going wrong? What shall I change?

# Answer
> 4 votes
The PIR can’t provide enough current to drive the led. The maximum current for the BIS0001 is 10mA.

Either increase the resistor value, and accept that the led is less bright.

Or use a transistor to drive the led.

Or connect the led to an Arduino pin and turn the led on by code, based on the input pin connected to the PIR

---
Tags: arduino-mega
---


# Question
Title: Background "static" on side of TFT screen?
I recently bought an XC4629 128x128 TFT screen and noticed that failing to initialise a background for the screen produced this RBG static.

A red line drawn on the screen without a background:

The problem, however, is that when I did initialise a background, the "static" remained on 3-4 pixels down the side of the screen:

Here is the code I used:

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

 #define CS   10
 #define DC   9
 #define RESET  8

 TFT myScreen = TFT(CS, DC, RESET);

 void setup(){
   myScreen.begin();
   myScreen.background(0,0,0);
 }

 void loop(){
   myScreen.stroke(255, 0, 0);
   myScreen.line(0, 128, 128, 10);
 }

```

Is this a problem with the screen itself? I have searched around the internet and have found no similar issues. Due to the behaviour it seems like an code issue but I have made it as simple as possible and experimented and only found it goes away if I remove the signal and just have the screen on backlight only. I also double checked that the wiring was all in the correct slots (both referencing the code and the datasheet for the screen).

Many thanks in advance.

# Answer
It will be a problem with the library you are using. Not all screens that use the same CoG are wired in quite the same way. Often a CoG that supports a larger number of columns is used with a screen that doesn't have that many columns (132 in this case), and the actual screen is placed at an offset within the available columns, and it's up to the manufacturer of the screen where that offset is.

So the library has to initialize the CoG with where the screen actually is within its physical column range, and your screen is different to what the library is expecting. Looking at the TFT library bundled with the IDE most screen configurations appear to impose a couple of pixels offset in the columns, which you don't want.

I would suggest investigating other TFT libraries, such as UTFT, which may give better control over screen parameters.
> 1 votes

---
Tags: lcd, tft
---


title: How to use a digital RGB LED Strip?

text:
# Question
Title: How to use a digital RGB LED Strip?
I know this is probably a little bit basic but I need SERIOUS help with using my new led strip. You can see here the type of strip I have, and the packet.

It's difficult because it looks slightly different to all the other ones I've seen in tutorials so I don't really know where to start now...All I've done is cut off the ends of the wires already on there and replace them with the regular pins that I can use on the Arduino and breadboards too. Where do I have to go from here? Are there any code libraries I need to use?

# Answer
> 1 votes
As far as I understand the DAT (Green wire) is a digital data wire. Try the following: 1. VCC to +5V pin 2. GND to GND pin 3. DAT to 2 Digital pin.

Then try to change the state of the 2 digital pin from high to low and see if anything happens... That's what I would start out with.

# Answer
> 1 votes
I had the same issue, in every example you see wiring diagrams with 3 wires, and my ledstrip had 5 wires, but it seems the two red wires (5v) are connected and the two white wires (gnd) are connected to eachother, so basicly you have 3 wires like in every wiring diagrams what's out there

---
Tags: led, digital, rgb-led
---


title: warning: variable 'b' set but not used

text:
# Question
Title: warning: variable 'b' set but not used
I got the following error:

`warning: variable 'b' set but not used`.

I think I do a really small thing wrong but I can't figure out what it is.

```
#define array_size(array) ((int)(sizeof(array) / sizeof((array)[0])))

typedef struct Boid {
  unsigned long start_animate_time;
} Boid;

Boid boids[4];

Boid create_boid() {
  unsigned long start_animate_time = 0L;
  Boid b = {start_animate_time};
  return b;
}

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

  boids[0] = create_boid();
  boids[1] = create_boid();
  boids[2] = create_boid();
  boids[3] = create_boid();

  for (int i = 0; i < array_size(boids); i++) {
    Boid b = boids[i]; // <<<<<<<<<<<<< this line!
    b.start_animate_time = 456;
  }

  for (int i = 0; i < array_size(boids); i++) {
    Boid b = boids[i];
    Serial.println(b.start_animate_time); // BUG always 0
  }
}

void loop() {

}

```

> flock\_01\_ino\_debug.ino:28:10: warning: variable 'b' set but not used \[-Wunused-but-set-variable\] Boid b = boids\[i\]; ^

# Answer
C++ is not Java. You can't just assign structs like that - it copies them (if anything).

```
Boid b = boids[I]; // <<<<<<<<<<<<< this line!
b.start_animate_time = 456;

```

Instead just access the array slice directly:

```
boids[i].start_animate_time = 456;

```

And later on as well:

```
Serial.println(boids[i].start_animate_time);

```

Basically, you create a "Boid" variable called "b", copy the content of `boids[i]` to it, set a value in that variable, and then throw it away. Hence the "not used". If you want to reference a specific array slice as a separate variable either get a pointer to it:

```
Boid *b = &boids[i];
b->start_animate_time = 456;

```

Or use a reference:

```
Boid &b = boids[i];
b.start_animate_time = 456;

```

Of the two I prefer using a pointer, but I come from a C background and understand pointers, but it took me many years of trial and error to get to that point...
> 2 votes

---
Tags: arduino-uno, variables
---


title: HEF4094 with 12v Vcc

text:
# Question
Title: HEF4094 with 12v Vcc
Using old NXP HEF4094BP shift register chips, for the reason of fixing some old hardware. These chips were popular in the 90's because they could accept 3-15V VCC and directly drive series+parallel LED chains. Think: gas station price signs, etc.

I'm green. Using this post and the 4094 datasheet, I've successfully modeled your typical shift register count-to-100 binary, with an LED on each SR out. Powered by 5V, works great. This was phase 1 for me.

For phase 2, I powered the Arduino via 12V (via p30, Vin). Still supplying 5V to the 4094 (Nano pin 27 output), works great.

Phase 3, I need help. I remove the 5V jumper that was from Nano pin 27 going into 4094's VCC pin. In it's place, I run 12V directly from the (regulated) PS and I get NO LED output. I know I haven't burned anything out because at 12V I get brief "flashes" when I'm "plugging" in the 12V power supply. I can revert to 5V VCC input and it works fine as before.

I've read the datasheet 3X and it's not clear how the chip's output pin voltage is managed when you alter the VCC to be higher (is it limiting current or voltage on the outputs?)

# Answer
The part of the datasheet you need to understand is this bit:

That's the input logic levels, and as you can see they vary depending on the supply voltage.

At 10V you need to supply at least 7V to get a HIGH registered. At 15V you need 11V or more. So at 12V you can expect that level to be around 9V and upwards.

The Arduino outputs 5V. That's nowhere near 9V, so the chip completely ignores it.

These chips are not designed to be level translators. They are designed to work with other chips that also run at the same voltage. To use it at a higher voltage that the chip that's driving it you will need to employ some form of 5V to 12V level translation.
> 2 votes

---
Tags: arduino-nano, shift-register
---


# Question
Title: Is it possible to print a custom object by passing it to Serial.print()?
I googled about it, but can't find the answer. As I would guess I would have to inherit from the Print class and somehow pass to its print methods the part of my object I would like to be printed. But I am not sure how to go about it or if it is even possible.

# Answer
> 15 votes
There is a class called `Printable`. If you inherit from that, and implement the `size_t printTo(Print& p)` function, your object can then be passed to the print functions:

```
class myClass : public Printable {
    private:
        int _val1;
        int _val2;

    public:
        myClass(int v1, v2) : _val1(v1), _val2(v2) {}
        size_t printTo(Print& p) const {
             size_t r = 0;

             r += p.print("One: ");
             r += p.print(_val1);
             r += p.print(" Two: ");
             r += p.print(_val2);
             return r;
       }
};

```

Then:

```
myClass ob(4, 5);

Serial.println(ob);
=> One: 4 Two: 5

```

---
Tags: esp8266, stream
---


# Question
Title: CH34x board fails with avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 Atemel Mega328P AU1640
I have been given a board(*Atmel ATmega328P-AU 1640*) to program. I googled and found category of board *Arduino Uno*/ CH34x-based clone.

But when I program an empty program:

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

}

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

}

```

I get this error:

```
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

```

These are all the ports that are available to me. I have connected my Arduino with one of the USB ports on my Macbook running MacOS Sierra

# Answer
> 3 votes
You have an Arduino nano clone using a CH340G chip for serial communication. You to down load and install a driver for your computer to recognize it. I don't use OSX, so there's not one I can recommend.

# Answer
> 3 votes
The board is an Arduino Nano clone, not an Uno.

1. Plug the Nano's USB cable into your computer.
2. Download and install the CH340 driver from here: http://www.wch.cn/download/CH341SER\_MAC\_ZIP.html
3. In the Arduino IDE, select the port of your Nano from the **Tools \> Port** menu.
4. **Tools \> Board \> Arduino Nano**
5. **Sketch \> Upload**

If the port of your Nano doesn't appear in the **Tools \> Port** menu (and no, dev/cu.Bluetooth-Incoming-Port is not the correct port) then you may have a damaged or charge-only USB cable. Try using a known-good cable or verify that your cable works for data on another device. If you have it plugged into a USB 3.0 port on your computer then try a USB 2.0 port instead.

# Answer
> 2 votes
That looks like a clone of an Arduino Nano to me, with a CH340G chip as the USB interface chip. You need to:

1. Install the CH340G drivers
2. Ensure that the ATMega328PU chip has a bootloader installed on it

The last Nano I bought from China didn't have a bootloader installed. There are many tutorials online for teaching you how to install the bootloader using another Arduino as the programmer.

# Answer
> 1 votes
Try this instructions from install driver. https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver

Installation with Homebrew-Cask.

Then try this, and all work fine ;) http://www.instructables.com/id/How-to-fix-bad-Chinese-Arduino-clones/

# Answer
> 1 votes
Remove the old driver by issuing one of the following commands (depending on your installation):

* sudo rm -rf /System/Library/Extensions/usb.kext
* sudo rm -rf /Library/Extensions/usbserial.kext

Restart your Mac.

**Install with Homebrew-Cask** Install the driver by the following commands

Restart your Mac.

Try upload some code in your Arduino. In some cases the board might still not work.

This is because there is no bootloader installed on the Atmel microcontroller ship. To solve this problem we need a working Arduino and the clone Arduino we want to fix.

!\[Make an ISP Programmer From Your Working Arduino \]

First we connect the working Arduino to our computer and open the Arduino IDE.

We go to File -\> Examples and click ArduinoISP and upload this to the Arduino. Ones uploaded disconnect the Arduino.

\**

## Connecting the Wires

\**

**Next we connect the wires from the working Arduino to the clone as follows.**

**Without 10 uF capacitor.**

Go to Tools -\> Board and select the chinese board that is not working. in my case it's an Arduino Genius/Uno

Next we go to Tools again -\> Programmer and select Arduino as ISP.

Go to Tools again and select "Burn Bootloader".

Go back to Tools -\> Programmer and set back to ArduinoISP.

Your clone should work just fine now. ;)

---
Tags: arduino-nano, osx, ch340
---


title: ESP8266 communication issue

text:
# Question
Title: ESP8266 communication issue
I have an issue communicating with ESP8266 via Arduino Uno's serial ports.

I can connect to it using `python -m serial.tools.miniterm /dev/ttyUSB0 115200` command but when trying to send an `AT` command, it looks like this:

```
�tC�

ERROR
�v[�
ERROR
at

OK

```

So, sometimes I'm able to properly send a command, but usually what I type turns to gibberish. I've tried other baud values, but only `115200` works.

I'm powering Arduino via USB from my laptop. I've seen some mentions that this behavior may be caused by low voltage but unfortunately, I'm currently unable to verify it whether that's a case here.

My schematic looks like this:

I'm new to this, so if there is any crucial information I've missed, then please let me know and I'll do my best to provide it.

# Answer
The issue, as Maximilian Gergardt suggested in comments, was with Arduino's TX/RX sending 5V signal. Adding voltage dividers on RX line solved the issue. Refer to diagram below for details:
> 2 votes

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


# Question
Title: Is there any problem in running Arduino logic to 12V LEDs?
I want to run a strip of 300 12V LEDs (Adafruit Neopixels with WS2811), with my Arduino. Is it safe to connect a follows, or is there some "separation" between voltage levels needed?

* 5V voltage/out and ground (from converter 1) to Arduino Voltage-in and ground.
* 12V voltage-out (from converter 2) to LED strip voltage-in.
* 12V ground (from converter 2) to Arduino ground and LED strip ground.
* Arduino data pin to LED strip data pin.

# Answer
The signalling of those LEDs is 5V and the power supply 12V. Basically you have a 5V-powered chip with constant current sinks driving LED chains that are powered from 12V. The 5V power for the chip is created from the 12V power for the LEDs. So, you need to:

* Provide +12V and GND to the chain of LEDs from a 12V power supply
* Connect the data line to an Arduino
* Connect the GND connection to the Arduino as well.

Nothing more is needed.
> 2 votes

---
Tags: power, led-strip
---


title: What is this? Looks like a sensor

text:
# Question
Title: What is this? Looks like a sensor
I got an Arduino kit from my dad. But inside this box is a thing, maybe a sensor. But I can't find what it is. Anyone recognize this 'thing' on the picture?

# Answer
> 3 votes
Appears to be a touch sensor that can be found on various on-line retail web pages:

http://www.satistronics.com/

https://www.arduiner.com/

Also, the back may have a URL as this one does:

...however, the URL appears not to function.

---
Tags: sensors
---


title: Run Time Error in arduino

text:
# Question
Title: Run Time Error in arduino
I am trying to communicate multiple clients to a server, all using nodeMCUs. I am getting a weird run time error at the Server Serial Monitor of Arduino IDE when I upload the code.

Here's my server code:

```
#include <ESP8266WiFi.h>
#define Max_Clients 5

WiFiServer server(80);
WiFiClient *clients[Max_Clients] = {NULL};
String inputs [Max_Clients] = {""};                           //Initializing to store the string received from clients

void setup() {
  pinMode(D1,OUTPUT);                                         //Intializing pins for showing output and input
  pinMode(D2,OUTPUT);
  pinMode(D3,OUTPUT);
  pinMode(A0,INPUT);

  Serial.begin(9600);                                         //Start communication between the ESP8266-12E and the monitor window

  WiFi.mode(WIFI_AP);                                         //This ESP8266-12E is an AccessPoint
  WiFi.softAP("NodeMCU_js", "12345678");                      //Provide the (SSID, password)

  IPAddress myIP = WiFi.softAPIP();                           //Obtain the IP of the Server
  Serial.println("Server IP is: ");                           //Print the IP to the monitor window
  Serial.println(myIP);
  server.begin();                                             //Start the HTTP Server
}

void loop() {
  WiFiClient client = server.available();                     //Check if a new Client has connected to the server

if (client) {
Serial.println("A new Client has connected :)");

for (int i=0 ; i<Max_Clients ; ++i){              //Acknowledges and sets up new clients
  if (NULL == clients[i]){
    clients[i] = new WiFiClient(client);          //nothing in clients[i] means it is a new client
    break;
    }
  }
}

for(int i=0 ; i<Max_Clients ; ++i){                           //For available clients
  if (NULL != clients[i] && clients[i]->available()){
    String request = clients[i]->readStringUntil('\r');
    Serial.println("The string of client "+String(i+1));    //Print client's message
    inputs[i] = request;
    Serial.println(inputs[i]);

    int duty[4];
    duty[i] = inputs[i].toInt();

    if (i == 0){
      analogWrite(D1, duty[i]);
      clients[i]->println("To client 1.\r");
    }
    if (i == 1){
      analogWrite(D2, duty[i]);
      clients[i]->println("To client 2.\r");
    }
    if (i == 2){
      analogWrite(D3, duty[i]);
      clients[i]->println("To client 3.\r");
    }

    clients[i]->flush();                                    //Waiting for transmission to complete
    clients[i]->stop();
   }
  }
 }                                                                 //void loop closure

```

Here's my client code (which will be same for all clients):

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

char ssid[] = "NodeMCU_js";
char password[] = "12345678";

WiFiClient client;                // Creates a client that can connect to to a specified internet IP address and port as defined in client.connect()

IPAddress server(192,168,4,1);

void setup() {
  pinMode(A0,INPUT);
  pinMode(D6,OUTPUT);

  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);

  Serial.begin(9600);                 //Serial connection
  WiFi.begin(ssid,password);          //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {         //Wait for the WiFI connection completion
    delay(500);
    Serial.println("Connecting...");
  }
  Serial.println("Connected.");
  client.connect(server, 80);   // Connection to the server
  }

void loop() {

  if(WiFi.status() == WL_CONNECTED){   //Check WiFi connection status

    int sense = 200;
    client.println(sense+"\r");  //Client's message to the server
    String answer = client.readStringUntil('\r');         //Reading response from the server
    Serial.println("from server: " + answer);             //Printing the response
    client.flush();

    delay(3600000);
    }
  else{
    Serial.println("Error in WiFi connection");
    }
  }

```

On uploading this code, the Serial Monitor at the server shows:

> A new Client has connected :) The string of client 1 nt8\_t\* BufferedStreamDataSource::get\_buffer(size\_t) \[with TStream = \>ProgmemStream; uint8\_t = unsigned char; size\_t = unsigned int\] The string of client 1

While the Serial Monitor at the client shows:

> Connecting... Connecting... Connecting... Connecting... Connecting... Connecting... Connecting... Connected. from server: To client 1.

I have no clue of the source of this error. Any help is appreciated.

Thanks in advance.

# Answer
I suspect the problem stems from the client side. This line:

```
client.println(sense+"\r");  //Client's message to the server

```

doesn't do what you think it does.

`sense` is a number (200). `"\r"` is a string constant located at an address in memory. When you add the two together you are not concatenating two strings, but you are adding 200 to the address of the string constant - and then sending whatever it finds at that location.

The "\r" is actually redundant anyway, since you are using `println` which adds `\r\n` to the end of a print. However if you do want to do it manually you just need to split it into two prints:

```
client.print(sense);
clienr.print("\r");

```
> 1 votes

# Answer
1. Research WL\_CONNECTED, I think you find that is the connection state to your Access Point not the state if a device has connected, also their are issues with this variable. It doesn't change state when the connection is dropped.
2. to make a connection you need to make a GET or POST request to a page on your server something like...

`if (client.connect(server, httpPort)) {
 // connected to resource
 // send data
 client.print("GET /myfile");
 client.println(" HTTP/1.1");
 client.println("Host: IPADDRESS");
 client.println("Connection: close");
 client.println();
 } else {
 // No connection to server
 // should maybe keep retrying else waits till next call
 } // end if connect`
3. Your server code needs to server a page and keep checking for connection with

webServer.on("/", doRoot);
4. Then have a function that writes the HTML back to client like...

void doRoot() { // write HTML String html; html = ""; html += "

## My Page

"; // and send it webServer.send(200, "text/html", html); }
> -1 votes

---
Tags: esp8266, arduino-ide, nodemcu
---


title: HTTP Requests using Arduino

text:
# Question
Title: HTTP Requests using Arduino
I use this simple HTTP Post request to post some values on my API from Arduino using Switch. each time I push the switch it send a different values to API.

```
void switch_led() {
bool SwitchReading = digitalRead(SWITCH);
if (SwitchReading == HIGH) {
Serial.println("Now pressed....");
state = state + 1;
if (state % 2 != 0) {
  digitalWrite(LED, HIGH);
  char data1[] = "{""LDRValue"": 88888888}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data1));
    client.println();
    client.print(data1);
    Serial.println("1.finish");
  }
  Serial.println("2.finish");
}
else {
  digitalWrite(LED, LOW);
  char data2[] = "{""LDRValue"": 1111111111}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data2));
    client.println();
    client.print(data2);
    Serial.println("3.finish");
  }
  Serial.println("4.finish");
}
delay(500);
   }
}

```

It works perfect for the first and second posts in both Arduino and API but at the third post it works fine on Arduino but it takes long time on the API(about 2 minutes to get the post). The fourth and the fifth posts also works fine but the sixth is same as the third. Knowing that my API works 100% with Raspberry Pi and it has no errors.

The same thing for PUT and GET.

After Edition: After I remove the port number from the host line and using strlen(data)instead of sizeof(data), the POST request works but only for first 7th posts. The output of serial monitor on Arduino is like that:

```
Attempting to connect to WPA SSID: WiFi-Repeater1

WiFi connected
SSID: WiFi-Repeater1
IP Address: 192.168.2.149
signal strength (RSSI):-66 dBm

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...

Starting connection to post server...

Starting connection to post server...

```

Before the Editing, it was always giving me "connected to post server" and It always posts but as I told you before It takes a lot of time at the 3rd 6th 9th 12th ..... Now after the 7th post it will not posts.

# Answer
I figure out the problem.

To solve the session between Arduino and the server must ended after each Post using `client.stop();`

```
void switch_led() {
      bool SwitchReading = digitalRead(SWITCH);
      if (SwitchReading == HIGH) {
        state = state + 1;
        if (state % 2 != 0) {
          digitalWrite(LED, HIGH);
          char data1[] = "{""LDRValue"": 88888888}";
          Serial.println("\nStarting connection to post server...");
          if (client.connect(server, 8040)) {
            Serial.println("connected to post server");
            client.println("POST /api/sensor HTTP/1.1");
            client.println("Host: 192.168.2.116");
            client.println("Content-Type: application/json");
            client.print("Content-Length: ");
            client.println(strlen(data1));
            client.println();
            client.print(data1);
          }
          client.stop();
        }
        else {
          digitalWrite(LED, LOW);
          char data2[] = "{""LDRValue"": 11111111111}";
          Serial.println("\nStarting connection to post server...");
          if (client.connect(server, 8040)) {
            Serial.println("connected to post server");
            client.println("POST /api/sensor HTTP/1.1");
            client.println("Host: 192.168.2.116");
            client.println("Content-Type: application/json");
            client.print("Content-Length: ");
            client.println(strlen(data2));
            client.println();
            client.print(data2);
          }
          client.stop();
        }
       }

```
> 0 votes

# Answer
I *THINK* the problem might be the `client.println()` statement. I believe REST messages should be terminated with a \r\n and I think println just does \n. So if you change it to `client.println("\r")` it should start working on every message.

Also you might want to consider moving creating the message into a function to reduce the amount of code you have.
> 0 votes

# Answer
you may wish to do more than just client.stop:

```
// ensure the client is clean
while (client.connected()) { while (client.available()) client.flush(); }
client.stop();

```

also; if you are using a WiFi shield; you may want to take a look at a known issue where on a failed connection; the socket isn't released. i simple patch is required to make it work flawlessly:

https://github.com/arduino-libraries/WiFi/issues/5
> 0 votes

# Answer
I've observed that virtually every example of an Arduino web server posted online fails to adhere to the HTTP standard. When a "GET" request is received, the server should parse the "Content-Length: xxx" attribute to get "xxx", then read xxx characters. When sending a web page to a client, the length of the request should be calculated, omitting the HTTP headers (everything before the "html" tag) and the "Content-Length: xxx" attribute should be included in the header, where xxx is the length of the response from "html" tag to "/html" tag, inclusively.

I had the same problem described here, and nothing I did fixed it until I implemented the standard-compliant code described here.
> -1 votes

---
Tags: arduino-uno, arduino-yun
---


# Question
Title: I cannot upload any code to my arduino uno
I am using ardunio uno on a windows 10 machine.

I have never been able to upload any code whatsoever.

Every time i get different errors, sometimes it's about com port, sometimes about memory, baud rate and what not.

This time I am getting the following error.

What should I do next?

```
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Jayesh Patel\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982 -warnings=none -build-cache C:\Users\JAYESH~1\AppData\Local\Temp\arduino_cache_625197 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jayesh Patel\Documents\Arduino\sketch_jun21a\sketch_jun21a.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Jayesh Patel\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982 -warnings=none -build-cache C:\Users\JAYESH~1\AppData\Local\Temp\arduino_cache_625197 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jayesh Patel\Documents\Arduino\sketch_jun21a\sketch_jun21a.ino
Using board 'uno' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "nul"
Generating function prototypes...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core
Linking everything together...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp.o" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/..\arduino_cache_625197\core\core_arduino_avr_uno_0c812875ac70eb4a9b385d8fb077f54c.a" "-LC:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982" -lm
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.eep"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -R .eeprom  "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.hex"
Sketch uses 1030 bytes (3%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "\\.\COM5": The semaphore timeout period has expired.

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

# Answer
> 0 votes
If you have arduino with ch340 you need to install driver for board.

---
Tags: avrdude, baud-rate
---


# Question
Title: Averaging input from multiple input over a fixed amount of time (estimated)
I am trying to average input values for a number of inputs and have it then store those averages into a string to write to a txt doc on a sd card.

I am using:

```
// read 6 sensors and append to the string:
for (int analogPin = 0; analogPin < 6; analogPin++) {
  int sensor = analogRead(analogPin);
  dataString += String(sensor);
  if (analogPin < 6) {
    dataString += ",";
  }
}

```

to read the pins at the moment, but I want to change the analogRead(analogPin) to an average value and then use the averages to create the string.

but when I try to average the data I run into errors, or I get output that is 0 for something that should be higher (3.3V).

I am doing this to stabilize my values a bit better and remove jitter.

Any suggestions?

# Answer
> 0 votes
This function will average readings on an analog pin, include it and use it in place of analogRead(...) and it should do what you want.

```
int aveAnalogRead(int pin, int ave=10, int delayms = 0)
{
    int tot = 0;
    for(int i=0; i<ave; i++)
    {
        tot += analogRead(pin);
        if(delayms) delay(delayms);
    }
    return tot/ave;
}

```

in your loop():

```
for (int analogPin = 0; analogPin < 6; analogPin++)
{
   int sensor = aveAnalogRead(analogPin);
     <<do your work here>>
}

```

---
Tags: input, datalogging, loop
---


# Question
Title: Arduino Wifi Works one way but not the other? (ESP32) (Possible Variable Type Problem)
I am working on a code that accepts input from serial monitor and connects to Wifi, and have been getting issues.

my SSID for my wifi is "SamF" but for some reason arduino only likes it when I initialize at the top, not when I accept it from serial monitor even though they are the same..

Example The below code works:

```
#include <WiFi.h>

char ssid[] = "SamF"; //OR const char* = "SamF"
char pass[] = "secretPassword";
void setup()
{
WiFi.begin(ssid, pass);
}
void loop () {}

```

The Code Below Does not work..

```
#include <WiFi.h>
char pass[] = "secretPassword";
void setup()
{
ssidSerial = my code that receives Serial input and converts to char

for(int k=0;k<=3;k++){
ssidPlaceHolder[k]=ssidSerial[k];
}
const char* ssid = ssidPlaceHolder;
WiFi.begin(ssid, pass);
}
void loop () {}

```

Everything compiles fine, I debugged by using Serial.print and they are both displaying "SamF" and sizeof(ssid) for both is 4... so I am not sure why one works and the other doesn't? any ideas?

Thanks in advance for any help, and if anyone needs the code after I am done I will be more than glad to share it on git!

# Answer
Basic string in C is an array of characters terminated by a 0. All functions taking char\* or const char\* use this 0 to determine the end of the string, because there is no other information about the length of that string.

In your question you copy characters from one characters buffer to other, but you do not set the terminating 0, so the function `begin` takes the data after the `pass` pointer until some random memory location with 0.
> 0 votes

---
Tags: wifi, esp32
---


# Question
Title: Interfacing Figaro KE25 Oxygen Gas Sensor with Arduino Uno
I have been trying to interface the **Figaro KE25 2 lead fuel cell type oxygen gas sensor** with **Arduino Uno**. I am not getting the required output on the Serial Monitor for regular air (Oxygen concentration of 19%).

I have attached the **sketch** I have typed out, the **output I have obtained on the Serial Monitor**, the **output(mV) vs Oxygen concentration (%) graph** of the Figaro KE25 sensor I have obtained from the datasheet, the **chemical reactions governing the working of the sensor**,the **circuit diagram** I have used, and the **construction of the sensor**.

In this question; I will explain the sensor first, then my circuit, then my sketch, and lastly the problem I have with my output.

In **electronics**, the **Anode is the positive electrode** and the **cathode is the negative** electrode. In ***electrochemistry***, the ***Anode is the Negative electrode*** and the ***Cathode is the positive electrode***. Do check the image of the construction of the sensor I have provided obtained from the datasheet.\[!\[image of the construction of the sensor\]\[1\]\]\[1\] Full Technical Datasheet

The **Cathode**, that is, **the positive electrode** is the **sensing electrode** (Oxygen gets consumed here and an electric current is generated). Since a current is being generated by the sensor (fuel cell), **no power supply needs to be given to the sensor**. Check the image of the chemical reactions provided (obtained from the full technical datasheet of the sensor). Technical Datasheet

The sensor in question is an analog voltage type sensor. Keeping this and everything I have mentioned above in mind, I have constructed the following circuit with Arduino Uno. Refer the picture I have put up. I have connected the **Cathode (the sensing positive electrode, red in colour) to the Arduino's analog A0 pin** and **the Anode (negative electrode) to the Arduino's ground**.

The sketch I have used is as follows:

```
 /*the analog pin of the alcohol sensor goes into analog pin A0 of the
 Arduino*/

 void setup()
 {
     Serial.begin(9600); //sets the baud rate
 }

 void loop()
 {
     float v1;
     float oxy = 0.0;
     float v2 = 0.0;
     pinMode(A0,INPUT_PULLUP);

     /*To make sure that reading is zero when the circuit is open*/

     v1 = analogRead(A0);

     /*reads the analog value from the Oxygen gas sensor and this value can
     be anywhere from 0 to 1023 (10 bit ADC used in Arduino Uno)*/

     if(v1>900) //To make sure that reading is zero when the circuit is open
     {
         v1=0;
     }
     v2 = (v1*3000)/992;

     /*The above line calculates the output of the sensor in mV using the
     fact that a HIGH reading in an input pin of an Arduino Uno board is
     equivalent to a voltage of 3V or higher. When I displayed just 'v1',
     the lowest of the high values I got was 992. So I equated it to 3V
     (3000mV) and used the unitary method to find out what a non-HIGH v1
     value would be in terms of mV.*/

     oxy = v2/0.6;

     /*The above line calculates the Oxygen concentration from the mV output
     of the sensor using the output(mV) vs concentration(%) graph from the
     sensor's datasheet. The graph is a straight line passing through (0,0)
     and hence the governing equation is of the form y = m * x. Where 'y' is
     'v2' and 'x' is Oxygen conc. in %.*/

     Serial.print("Oxygen value: ");
     Serial.print(v1);
     Serial.print("    ");
     Serial.print(v2);
     Serial.print("mV    ");
     Serial.print(oxy);//prints the Oxygen value
     Serial.println("%");

     delay(1000);
 }

```

he output(mV) vs Oxygen concentration(%) graph provided in the datasheet is shown below. The straight line labeled as 'KE25' is to be considered.  Product information (datasheet)

he output I have obtained on the serial monitor is as follows:

Such a high voltage from the sensor is not possible. My output reading is not possible at all. Where have I made a mistake and how do I correct it?

> **Update 1 :** I changed the line `pinMode(A0,INPUT_PULLUP)` to `pinMode(A0,INPUT)`. Now I am getting sensible values on my Serial Monitor. However, I am also getting many '0' outputs **(many)**. I am also getting many random values **(many)**. I need more information on how to interface a fuel cell type Oxygen sensor using Arduino Uno in terms of how to get a proper voltage reading across such a sensor. I have found no question on electrochemical, fuel cell type Oxygen gas sensor interfacing. All questions asked are regarding sensors that require a power supply. In case of fuel cell type Oxygen gas sensors, current is generated when Oxygen is sensed and hence, no power supply is required. Also, if anyone is into electrochemistry, how do I check the voltage output of a fuel cell type Oxygen gas sensor using a voltmeter? Do I use a DC voltmeter or an AC voltmeter?
>
> **Update 2:** I've made changes to the code based on @EdgarB's suggestions. The output I am getting now is better but still wrong. I checked if the sensors I am using are functional using a multimeter (I confirmed if the method I am using is right, and it is), and they are. The Oxygen values I am getting now are still really low: 6-8%. I should be getting: 19-21%. I used a reference voltage of 600 mV and modified the code.
>
> Modified code:

```
 void setup()

 {

     Serial.begin(9600);//sets the baud rate
     analogReference(INTERNAL);
 }

 void loop()
 {
     const float A_REF = 0.6e3;
     const float Scalc = (1/0.6);

     float v1;
     float oxy = 0.0;
     float v2 = 0.0;
     pinMode(A0, INPUT);
     v1 = analogRead(A0);
     v2 = (v1 * A_REF) / 1024;
     oxy = v2 * Scalc;
     Serial.print("Oxygen value: ");
     Serial.print(v1);
     Serial.print("    ");
     Serial.print(v2,4);
     Serial.print("mV    ");
     Serial.print(oxy,4);//prints the Oxygen value
     Serial.println("%");
     delay(1000);
 }

```

> Output:

# Answer
> 1 votes
Your problem stems from having the internal pullup resistor for A0 turned on.

The sensor is a current generator with a load resistor (plus thermistor) built in to convert the current into a voltage. By adding a pullup resistor you turn it into a voltage divider across 5V with a small current being injected into the central node:

simulate this circuit – Schematic created using CircuitLab

Since the datasheet doesn't specify the load resistance nor the source current I have made up some values to demonstrate.

If we take just the current source and load resistance RL+RT and calculate the voltage drop across that we get:

```
V=R×I = 5000 × 0.00001 = 50mV

```

Which is a reasonable value. It's a lot of oxygen, but that's because these are made-up values.

Now what would be the voltage with the pullup resistor added? Well, this is where it gets a little more complex. At times like this it's easier to just simulate the circuit in something like the falstad simulator and I can tell you it's **757.1mV** (If you want to learn how to do this kind of circuit analysis manually you should learn superposition theory).

A massive change.

Obviously you're not seeing a change *that* big - and that's because the pullup resistor is *more* than just a simple resistor. There's many more factors that influence the reading, including the output impedance of the network, as well as the rest of the internal ADC circuitry.

Suffice it to say, though, adding a pullup resistor is a bad idea when using the ADC.

But you want to keep the pullup resistor so you can know if the sensor is connected or not. That's not a problem. Just turn it on and off at will:

```
pinMode(A0, INPUT_PULLUP);
delay(1);
bool connected = analogRead(A0) < 900;
if (connected) {
    pinMode(A0, INPUT);
    delay(1);
    v1 = analogRead(A0);
}

```

It's recommended to wait a moment after changing the pullup resistor state before reading from the ADC to reduce electrical noise picked up by the ADC - hence the `delay(1)` calls.

# Answer
> 0 votes
You calculation of v2 is incorrect.

```
v2 = (v1 * 3000) / 992;

```

The maximum value v1 will have is 1023 and this equates to 5v (not 3v). So to calculate the voltage v2 I think you should be doing:

```
v2 = (v1 / 1023) * 5000;

```

But this will make your calculations even further out!

# Answer
> 0 votes
You have three different issues here:

1. improper use of the pullup resistor
2. incorrect interpretation of the analog reading
3. too small input signal

## Pullup resistor

Majenko already covered the first issue, with very good advice.

## Interpretation of the analog reading

Code Gorilla already explained the second issue. However, since you do not seem to understand, I will add my take here.

The formula to convert an analog reading to an actual voltage is

voltage = reading × analog\_reference ÷ 1024.

Yes, it's 1024 rather the often seen (but erroneous) 1023. See the manufacturer's datasheet, which is the *only* authoritative reference. Doesn't make much of a difference anyway. The main issue is the analog reference voltage which, in the default configuration, is the same as the voltage powering the Arduino, i.e. 5 V.

In a comment, you wrote:

> if a pin is configured as INPUT, then the voltage at the pin is 3V or higher

This is complete nonsense. The voltage on an input pin is whatever voltage is provided by the circuit connected to that pin. If you actually mean the *threshold voltage* for the pin reading `HIGH`, well, that threshold is typically 2.6 V (see the “typical characteristics” in the datasheet), but the exact value is not guaranteed. The number you quote is “the lowest value where the pin is guaranteed to be read as high”. In other words, the voltage threshold can be lower than 3 V, but not higher.

And all this is completely irrelevant to you. The input thresholds are a feature of the digital input circuitry attached to the pin. This circuit is responsible for deciding whether the pin is `LOW` or `HIGH` when you `digitalRead()` it. But you don't care about the digital value: you are using the pin as an analog input. The ADC converter is a different circuitry that has *absolutely nothing to do* with the digital input. You can even disable the digital input of the pin and still use the ADC.

## Low signal

According to the graph you provide, the sensor should output 12.6 mV in normal air (21% O2). That's about 2.58 ADC steps. Thus you expect the reading to fluctuate between the digital values 2 and 3. This is really quite low for your ADC.

A simple way to mitigate this problem is to change the analog reference. The default is 5 V, but you can switch it to an internal 1.1 V reference that will significantly increase your resolution: in `setup()`, call

```
analogReference(INTERNAL);

```

Then you can compute the oxygen level as follows:

```
const float A_REF = 1.1e3;         // analog reference = 1,100 mV
const float SENSOR_CAL = 1 / 0.6;  // calibration: %(O2) / mV

void loop()
{
    int reading = analogRead(A0);
    float voltage = reading * (A_REF / 1024);
    float oxygen = voltage * SENSOR_CAL;
    // ...
}

```

Another way to mitigate the signal weakness is to average multiple readings. This can make your effective resolution better than the raw ADC resolution.

## ADC offset

The formula

voltage = reading × analog\_reference ÷ 1024

applies only to an ideal ADC. In practice, any ADC has some offset error and gain error. Taking them into account, the formula becomes:

voltage = (reading + offset\_error) × analog\_reference ÷ (1024 + gain\_error)

In many cases these errors are too small to care about. However, since you are working near the resolution limit of your ADC, the offset error can be an important concern. The gain error is no issue here, so you can forget about it.

If you have a voltmeter, you can easily determine the offset error: measure a low voltage, like the one from your sensor, with both the voltmeter and the ADC. Ideally, you would average many ADC readings to get a better resolution. From the voltmeter measurement, you compute the average reading you would expect from your ADC, then you get

offset\_error = expected\_ADC\_reading − actual\_ADC\_reading

Then you use this measured offset to correct your readings:

```
const float offset_error = ...;  // measured with the voltmeter

void loop()
{
    int reading = analogRead(A0);
    float voltage = (reading + offset_error) * (A_REF / 1024);
    // ...
}

```

---
Tags: arduino-uno
---


# Question
Title: Ethernet shield/WebServer problem: 'server is at 0.0.0.0'. Any suggestions how to debug it?
Ethernet shield problem. When running the WebServer example sketch, the Serial Monitor shows that `server is at 0.0.0.0`. Any suggestions how to debug it?

# Answer
That's what it's supposed to be. It's called INADDR\_ANY. Read an introductory text on networks and you'll understand what that means.

If you try to connect to the IP address you specified, you'll see that you can indeed connect.
> 1 votes

# Answer
The arduino only tells what it reads from the ethernet module and 0.0.0.0 is what you get when Arduino is not connected to it. It's a hardware problem, you either didn't connect the wires right or something's fried. I think it can also happen if your ethernet cable is unplugged.

This is absolutely not a sign that your module is accepting all connections. It would be the case if you set it that way but you are obviously expecting another ip adress. Someone should delete that answer.
> 1 votes

# Answer
If possible, try running the same code on an identical Arduino. I had a similar issue, and it turned out one of my ICSP pins were burned.

Contrary to other answers here, the IP address will show the correct value in the Serial Monitor even though nobody is connected.
> 1 votes

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


# Question
Title: fatal error: avr\wdt.h: No such file or directory in Arduino Due
I am using an Arduino Due for vehicle tracking with a GPS/GPRS device. Before using Arduino Due I used an Arduino Uno. When I tryi to load my code in the Arduino Due, it shows me "fatal error: avr\wdt.h: No such file or directory". I can't delete the watchdog from my code as it is important for my device.

Now how can I solve this problem?

# Answer
The Due is a very different board than the Uno. It uses a completely different architecture (ARM vs AVR). You can't use AVR-specific code on an ARM chip, and the Watchdog code is AVR-specific.

You will have to find (or write) the equivalent ARM code using the Due's register set instead.
> 1 votes

---
Tags: arduino-due
---


# Question
Title: How can I control 4 DC motors with an Arduino?
In a few months, I am planning to construct an Arduino robot with multiple sensors etc. I will use an arduino mega and a 4wd chassis like the one here: Chassis. The chassis uses 4 DC motors. I was planning to use a motor shield, but I realized that it only fits an Arduino Uno(not Mega) and it controls only 2 DC motors. What can I do to make all 4 DC motors move forward and backward? If I use a motor driver board that controls 2 motors, can I connect the 2 right and 2 left motors in parallel together and the control it through the Arduino?

# Answer
Yes, you can do this using 2 L293D motor drivers, each motor driver can run 2 motors and it is very easy to use.

You should connect Vcc 1(used to power on the chip) to 5V and Vcc 2 to a power supply that is needed to run your motors, Enable 1,2 and Enable 3,4 are used to enable the 2 sides of the chip and should be connected to 5V. Outputs 1-4 are the outputs to 2 motors and Inputs 1-4 are the inputs from the micro-controller.
> 2 votes

# Answer
Yes, you can actually do this, but you have to consider the current of the motors and the motor driver. For example, if you have 12V, 2 Amps motors, then you need a 2-channel motor driver that is able to output a little higher that 4 Amps (2\*2 Amps) for each channel at 12V. You will need to connect each two motors on the same side in parallel to one channel.
> 0 votes

---
Tags: arduino-mega, motor, arduino-motor-shield, robotics
---


# Question
Title: Help connecting ILI9341 LCD SPI Display to arduino uno
I got this lcd with touchscreen from a store but i have no idea on how to connect it to the arduino uno. Any help is appreciated.

This is where i bought it from.

The display

My Arduino

# Answer
> 1 votes
You can get it working by two methods

1. using a voltage divider e.g to shift from 5V to 3.3V you could use two resistors, 100k and 200k respecfully and between both resistors there is voltage of 3.3. One for each pin that needs it.
2. Using 10K resistors in series between the LCD and the arduino. I really don't know how is working but it works fine that way.

I tested both methods, also the MISO pin from the LCD can be connected directly to your arduino.

# Answer
> 0 votes
1. Download and install a suitable library
2. Wire the display to the Arduino as per the markings on the display
3. Try some of the examples for the library you are using.

---
Tags: lcd
---


title: Too many amps for Step motor

text:
# Question
Title: Too many amps for Step motor
I have an adafruit motor shield and attached the Nema 17 stepmotor. Now the big problem is trying to power it without it overheating. I was originally using a 12v 6a power supply but quickly switched to a 12v 2a and then a 12v 1a. All of them still make the Nema stepper motor very hot.

I'm using the accelstepper and adafruit modules on the arduino to control the stepper motor. I noted that the magnets are all always on in my code which might explain why it gets hot but I need to maintain some form of torque for the system I'm developing.

I will attach code as that might be the problem. Is there a second device I need to attach to the adafruit motor sheild and the nema stepper motor.

```
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

int ComControlValue = -1;

/* Define pins for motor and define step motor function */
const int SlowStepPerRev = 400;                              // Define slow speed constant
const int MotorB = 2;
int rpm = 60;                                                // Rotation per minute
int acelspeed = 40;                                          // Acceleration speed
int distrot = 200;
int destinationunknown = 0;                                  // Destination of plate 1

/* Initialize the stepper library on the motor shield */
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotorB = AFMS.getStepper(SlowStepPerRev, MotorB);

/* you can change these to SINGLE or DOUBLE or INTERLEAVE or MICROSTEP! */
// wrappers for the motor!
void forwardstepB() {
   myMotorB->onestep(FORWARD, INTERLEAVE);
}
void backwardstepB() {
   myMotorB->onestep(BACKWARD, INTERLEAVE);
}

AccelStepper stepperB(forwardstepB, backwardstepB);

void setup() {
   Serial.begin(115200);                                     // Establish Serial connection to computer
   Wire.begin();                                             // join i2c bus as master
   AFMS.begin();                                             // Begin useage of conveyorbelt motor

   stepperB.setMaxSpeed(rpm);                                // Initialize max speed
   stepperB.setAcceleration(acelspeed);                      // Initialize and set speed of acceleration for spinning
}

void loop() {
   switch(ComControlValue){
        case -1: //wait
            Serial.println("Waiting for Command");
            Serial.println(stepperB.currentPosition());
            while (Serial.available()==0){}
            ComControlValue=Serial.parseInt();               // Pull value from serial port
            break;                                           // break loop & return to start
        /* 1 : Move plates into the system */
        case 1:
// Arduino using accelmotor, move to position X
        if (plateNum < platelimit){
               plateNum++;
               ComControlValue= 11;                          // After establishing plate num & location, move to case 11 to start stepmotor movement
               destinationunknown = destinationunknown + 200;
        }
        else {
               ComControlValue = -1;                         // To many plates, cancel move command
        }
        stepperB.moveTo(destinationunknown);
        break;

        /* 2 : Move plate out of system */
        case 2:
        // Arduino using accelmotor, move to position Y
        if (plateNum > 0){
               plateNum = plateNum--;
               ComControlValue= 11;                         // After establishing plate num & location, move to case 11 to start stepmotor movement
               destinationunknown = destinationunknown - 200;
        }
        else {
               ComControlValue = -1;
        }
        stepperB.moveTo(destinationunknown);
        break;

        /* 1 : Run Stepmotor to completion */
        case 11:
        // Step motor requires an uninterrupted while loop to move to completion
        // code setup will utilize while loop and allow for movement
        stepperB.run();                                     // run stepmotor
        if (stepperB.distanceToGo() == 0 ){
                ComControlValue = -1;                       // Completed movement, go back to case -1
        }
        break;
   }
}

```

# Answer
> 1 votes
Stepper motors get hot. It's a fact of life. More so when they are held stationary.

A typical 12V Nema 17 stepper motor has a coil resistance of 30Ω per phase. With 12V across a single phase it will consume 0.4A. That is the equivalent of about 4.8W of power. That comes out in the form of heat.

Reducing the current capacity of your power supply will not "fix" the problem. All that will happen is that as you go to lower and lower current supplies the supply will get hotter and eventually break.

You can test the coil resistance of your motors with a DMM set to the Ohms range, then calculate the power dissipation using:

```
Current = V ÷ R = 12 ÷ <measured resistance>

```

and:

```
Power = V² ÷ R = 144 ÷ <measured resistance>

```

# Answer
> 1 votes
I think you will have a better chance reducing the heat by lowering the supply voltage (which will reduce the current as a consequence). You won't get the nominal torque if you go below 12V, but this is a compromise and there's no free cheese there.

Limiting the available current only works in a predictable manner with power supplies which can work as current sources. If your power supply is only a voltage source, then trying to draw more current than it can provide will eventually result in the power supply going into self-protection (not delivering any voltage) or breaking down. With voltage sources, maximum current is a limit **you have to respect**, not a limit the power supply will impose.

---
Tags: adafruit, stepper
---


title: HC-05 and p-channel mosfet

text:
# Question
Title: HC-05 and p-channel mosfet
I'm trying to use a MOSFET (BS250P datasheet) to switch a circuit on and off while the MCU is asleep. It's a P-channel MOSFET that closes the circuit when the gate is pulled low. The most power hungry module in my circuit is a HC-05 bluetooth module. The specs on the website I bought it at rates it at 3.3V - 6V and a max current draw of 50mA when pairing and around 9mA when connected. Hooking it up to an Arduino 3.3V source confirms that it works at that voltage and pairs it up with another identical module just fine.

Now when I put that same 3.3V source through the MOSFET with a 10k pull up resistor and connects the HC-05 to the drain, the module does not power up. I measured the voltage on the drain and when nothing is connected it's the same as the source. After connecting the HC-05 it's about 2.4V (maybe this is a clue). Even if I run the power through a step up converter to 4.10V it does not power up through the MOSFET. If I increase the voltage to 5V it all works fine. I would ideally run the circuit at 3.6V in order to preserve current for the rest of the modules, and not having to use a voltage regulator for the RX of the HC-05.

I assume the issue is with the MOSFET properties, but as far as I can read from the datasheet it can sustain 230mA current. It has a VGS(th) of 3.6V, but since I'm always pulling the MOSFET low in this scenario that shouldn't be an issue? Measuring the resistance when the gate is pulled low indeed gives just a few ohms as the datasheet suggests.

So basically, what am I missing here? :-) Thank you for any help with this!

# Answer
> 2 votes
That's not a good choice of MOSFET I'm afraid.

The on resistance is quoted as 14Ω when the gate is at -10V - however, you are only able to get -5V, so it will be considerably worse.

That massive on resistance will be causing a massive voltage drop, which is what you are experiencing.

You should find a MOSFET with an on resistance that is in the milli-ohm range when the gate is between 0V and -5V.

---
Tags: hc-05, mosfet
---


title: Casting custom shared_ptr object

text:
# Question
Title: Casting custom shared_ptr object
I am using custom shared\_ptr class for some program on Arduino, and I need to do something like this:

```
shared_ptr<Base_class> b_ptr;
shared_ptr<Child_class> ptr((shared_ptr<Child_class>) b_ptr);

```

In my shared\_ptr class I have three constructors:

```
shared_ptr() : pData(0), reference(0){...}
shared_ptr(T* pValue) : pData(pValue), reference(0){...}
shared_ptr(const shared_ptr<T>& sp) : pData(sp.pData), reference(sp.reference){...}

```

and some other stuff... For casting I tried to write the following:

```
    template< typename T2 >
operator T2 * () const
{
   return (T2 *)pData;
}

```

and:

```
    template< typename T2 >
operator shared_ptr<T2> () const
{
    shared_ptr<T2> temp((T2 *)pData);
    return temp;
}

```

but can't get it to work.

# Answer
For doing:

```
shared_ptr<Base_class> b_ptr;
shared_ptr<Child_class> ptr(b_ptr);

```

you have to use another constructor. If you take a look on this Example of shared\_ptr implementation, you can see:

```
template<class U> shared_ptr(const shared_ptr<U>& s) ...

```

That's exactly the constructor, that takes shared\_ptr of different type .

And similarly for assigment operator.
> 1 votes

---
Tags: data-type
---


# Question
Title: Problem with nodemcu esp-01 can't connect to wifi
i've been working on a project that im using an esp8266 nodemcu-01 as described in the title, and i've been having some headache with this module, first because after searching i figured out that the commands LOW and HIGH are inversed as in LOW outputs 3.3v e HIGH outputs low tension, so i began to grow worried about the possibility that other programming resources may follow the same situation. But with that problem a part, i've been trying a few different codes including the one found in the sketchbook examples and still couldn't connect.

Also another weird problem, is that i was working working with the baudrate set on the arduino IDE settings on 115200, and so is the Serial.begin, that is also set to 115200, however i can only read properly the continuous dot that is contained in the while loop "........." when i set it to 74880, which another thing that i was trying to understand. I also forgot to mention that it keeps spamming dots but does not connect at all.

And to conclude, my problem resumes in not being able to connect to any wifi i've tried, i tried my friend's home and also 4g, both did not work, here's the code, which we tried first:

```
#include <ESP8266WiFi.h>

char* ssid = "Net Wi-fi";
char* password = "testingtest";
//
void setup() {
  WiFi.begin(ssid, password);
  Serial.begin(115200);
  while(WiFi.status()!=WL_CONNECTED)
  {
    Serial.print("Conecting");
    delay(500);
  }
  Serial.println("");
  Serial.print("IP:");
  Serial.print(WiFi.localIP());
}

void loop(){

```

This was the original try, using the arduino sketch example:

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

const char* ssid = "Net6271";
const char* password = "megaman";

ESP8266WebServer server(80);

const int led = 13;

void handleRoot() {
  digitalWrite(led, 1);
  server.send(200, "text/plain", "hello from esp8266!");
  digitalWrite(led, 0);
}

void handleNotFound(){
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void setup(void){
  pinMode(led, OUTPUT);
  digitalWrite(led, 0);
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);

  server.on("/inline", [](){
    server.send(200, "text/plain", "this works as well");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

```

Board setting: Generic ESP8266 Module. Crystal Frequency: 40MHz. Flash Frequency: 80Mhz. Upload Speed: 115200. Flash Mode: DIO. Flash Size: 512k no SPIFFS.

pls help.

# Answer
ESP-01 modules use 26 MHz crystal. Set the Crystal frequency in IDE to 26 MHz.

Both io pins (0 and 2) on esp-01 have pull-up circuit. That is why you think you measured 'inverted' logic.
> 0 votes

---
Tags: arduino-uno, esp8266, wifi, nodemcu, web-server
---


title: Using modulo for negative values

text:
# Question
Title: Using modulo for negative values
I want to wrap a random number using modulo, so that values exceeding 11 starts over from 0 and greater. However, i would also like numbers less than 0 to dividend 11 or less.

Please correct me if i'm wrong, but as far as i can tell the modulo operator only dividends values *exceeding* the divisor. If so, how can i write code that also dividends values less than 0?

# Answer
> 1 votes
One crude way:

```
while (x > 11) x -= 11;
while (x < 0) x += 11;

```

The first could be replaced with a modulo operation.

# Answer
> 2 votes
Simply use modulo

```
#include <stdio.h>

int main(){
   for (int i = -23;i<23;i++) printf("%d    %d\n",i,i%11);
   return 0;
}

```

all modern C variants should work the same way https://en.wikipedia.org/wiki/Modulo\_operation (result have same sign as divident):

```
-23 -1
-22 0
-21 -10
-20 -9
-19 -8
-18 -7
-17 -6
-16 -5
-15 -4
-14 -3
-13 -2
-12 -1
-11 0
-10 -10
-9  -9
-8  -8
-7  -7
-6  -6
-5  -5
-4  -4
-3  -3
-2  -2
-1  -1
0   0
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10  10
11  0
12  1
13  2
14  3
15  4
16  5
17  6
18  7
19  8
20  9
21  10
22  0

```

---

for new formulation of request fixed by @Gerben suggestion

if you want monotonic 0..10 sequencies, add 11, if result is negative :

```
#include <stdio.h>

int main(){
for (int i = -23;i<23;i++)
    {
    int x= i%11 ;
    x += x<0?11:0;
    printf("    %d  %d\n",i,x);
    };
return 0;
}

```

results in

```
-23 10
-22 0
-21 1
-20 2
-19 3
-18 4
-17 5
-16 6
-15 7
-14 8
-13 9
-12 10
-11 0
-10 1
-9  2
-8  3
-7  4
-6  5
-5  6
-4  7
-3  8
-2  9
-1  10
0   0
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10  10
11  0
12  1
13  2
14  3
15  4
16  5
17  6
18  7
19  8
20  9
21  10
22  0

```

---
Tags: calculation
---


# Question
Title: Is I2C a good option for transmitting data over 200 meters by cable?
Is I2C a good option for such application or are there other protocols? I know that modules like these exists to extend I2C range, and I'm planning to use this one (P82B96).

I'd like to use a frequency of 100kHz for I2C and use DMX cables of 20m connected in series.

So, is there any alternative that is more adapted for Arduino to Arduino data transmission over a cable?

EDIT : The solution here is CAN because it allows to have multiple devices on the bus. But if it is a simple communication between two arduinos, then go for the RS-232. Solution mentionned by @Dmitry Grigoryev and @Joe S

Thanks in advance.

# Answer
> 3 votes
With I2C, you're unlikely to get reliable communication on a cable longer than 1m. For your reference, here's a table showing what you can achieve with regular RS-232:

```
Length (m)  Maximum Baud Rate
1600        600
800         1200
400         2400
200         4800
100         9600
50          19,200
25          38,400
16          57,600
8           115,200

```

So, if you don't really need 100 kHz data rate, you could use regular RS-232 (which is cheap). If RS-232 is not fast enough for you, consider more complex solutions. RS-485 is one possiblility. Another one is CAN, which supports topologies up to 500m at 100kHz. The key difference of CAN is that it's a bus, meaning that all devices will share the same pair of wires.

# Answer
> 1 votes
I2C is perhaps the worst possible choice for this type of communication. Instead you should be using something like RS-485 (which is incidentally what DMX uses) with differential signalling.

---
Tags: i2c
---