# Question
Title: Fluctuating readings of LM35 temperature sensor (+- 5°C) with Arduino UNO
I am trying to read a LM35 temperature sensor with Arduino UNO which I got as a gift. The issue is the fact, that my readings of sensor are, well, suspicious at least - they jump with each reading some 5 °C up or down.

I had used several posts how to wire the thing to Arduino board and for and program the reading (, , ) and produced the code posted below. The sensor reading fluctuates really a lot - it jumps by some 3 to 7 °C after each reading regardless of reading frequency (tested with reading each 0.5 s, 1.0 s or 2.5 s). (Unfortunately I do not own a multi-meter to check actual values.) To mitigate the issue I implemented an averager, but underlying problem stays. Expected values are something like 23 or 24 °C as measured by digital weather station and bimetallic thermometer respectively.

Have you met this before ? Do you have any ideas what might be source of this ? I am beginner to electronics as well as to Arduino, trying to learn and mainly understand it.

The complete code:

```
#include <WString.h>

//Stores read analog values
int readLM35;
const int sensorAnalogPin = 0;
const float voltsToTemperature = 1.1 / 1023 * 100; // (1.1V supply / 10bit resolution) * (10 mV/°C = 1 V / 100 °C)
//Stores the temperature in °C
float temp;
//Averager
float temps[8];
byte position = 0;
float averageTemp;

void setup() {
    Serial.begin(9600);
    pinMode(LED_BUILTIN, OUTPUT);

    //For setting internal analog reference voltage to 1.1V
    analogReference(INTERNAL);
}

void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(50);
    digitalWrite(LED_BUILTIN, LOW);

    //Measure temperature
    readLM35 = analogRead(sensorAnalogPin);
    temp = readLM35  * voltsToTemperature;

    //Save it
    temps[position] = temp;
    if (position == 7) {
        position = 0;
    } else {
        position++;
    }

    //Get average
    averageTemp = 0;
    for (byte i = 0; i < 8; i++) {
        averageTemp += temps[i] / 8;
    }

    //Write
    Serial.println(String(readLM35) + " => " + String(temp, 1) + " deg. C, avg. " + String(averageTemp, 1));
    delay(2500);
}

```

Example of output (note the first numbers - actual reading):

```
211 => 22.7 deg. C, avg. 22.5
186 => 20.0 deg. C, avg. 21.9
234 => 25.2 deg. C, avg. 22.7
173 => 18.6 deg. C, avg. 21.9
237 => 25.5 deg. C, avg. 22.6
185 => 19.9 deg. C, avg. 21.9
231 => 24.8 deg. C, avg. 22.4
193 => 20.8 deg. C, avg. 22.2
223 => 24.0 deg. C, avg. 22.3
206 => 22.2 deg. C, avg. 22.6
197 => 21.2 deg. C, avg. 22.1
225 => 24.2 deg. C, avg. 22.8
183 => 19.7 deg. C, avg. 22.1
240 => 25.8 deg. C, avg. 22.8

```

# Answer
> 1 votes
The cause is the low sinking capabilities of LM35 output. This makes the output sensitive to EMI. Yes, the output output impedance is stated as 0.5 ohms but only for sourcing current. The sinking current is limited to 1uA which is easily achieved by the environment noise.

You need to add a low impedance load between LM35 output and ground, can be 200 ohm as the data sheet recommends for heavy capacitive loads but I wouldn't go that far, might be 1k or 2k to avoid self heating errors.

No software only solution can solve this error.

# Answer
> 0 votes
Try :-

```
const int temperaturePin = A0;

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

        Serial.begin(9600);
    }

double getVoltage(int pin)
{

  return (analogRead(pin) * 0.004882814);

    }

void loop() {

      double degree,voltage;
      degree = analogRead(temperaturePin)*0.48875855;
      voltage = getVoltage(temperaturePin);
      Serial.print(voltage);
      Serial.print(degree);
      delay(1000);

    }

```

# Answer
> 0 votes
I guess when 0 = 0 and 5V = 1023, then you should divide by 1023. Looking at the question, I notice that you use AnalogPin = 0. Myself, I would stick to AnalogPin = A0. A0 is defined as:

## define PIN\_A0 (14)

so it is not equivalent to 0. Are you sure you're reading the right pin? Also try another pin like A3.

# Answer
> 0 votes
this is a known issue for all Arduino sensors (fluctuations and drift), I also had this problem with humidity sensor and water level sensor with LM393 comparator, what I tried to do to make the fluctuations less was trying to calculate average readings instead of single reading:

```
for (int i = 0; i < 100; i++)
{
levelSensorValue = levelSensorValue + analogRead(levelSensorPin);
moistureSensorValue = moistureSensorValue + analogRead(moistureSensorPin);
}
levelSensorValue = levelSensorValue / 100;
moistureSensorValue = moistureSensorValue / 100;

```

generally speaking, all sensors have a linear range witch cannot be reliable beyond it, and also calibration for them is necessary.

# Answer
> 0 votes
Why have you done 1.1/1023. Your saying that the supply is 1.1v but your supplying it 5v. I use (readLM35/1024)\*500 to get temperature value in °C and it is on par with a thermometer I have bought. If this doesn't work try with another lm35. You might just have a faulty one.

Also the LM35 is factory calibrated for voltage. So you have to calibrate it according to the Arduino you use. I would recommend the ds18b20 as it's calibrated for temperature. Using the Dallas temperature library makes it easier to use as well

# Answer
> 0 votes
many answers, stick to the code or the LM35 itself rather than the main part, the ADC. when you are reading a \[approximately\] right temperature, well, then the code, vRef and pin config is right. I had problem with ADCs as I had to measure many voice signals for my thesis. here are some problems which may occur :

* double check if the board itself, has proper AVCC/AREF decoupling caps. many clone boards doesn't pay attention to production failures. decoupling caps usually connect between ground (GND) and a positive supply line(like VCC) to filter out noise.
* if you have access to the AVCC/AREF pin, connect 2 or 3 paralleled 100nf caps between them and ground. the values are not critical. anything in the 10nF up to 10uF range is fine. you can use different values for each cap.
* check your input power supply noise. computer USB port is the most trusted power supply. other power supplies (wall adapters, cheap power banks etc.) have some unimaginable noise.
* use caps (decoupling caps. the caps which are connected between + and - pins) on every single component or sensor. like LCDs, LM35 sensor... .
* try to use the exact code and sensor on other analog pins and if you got any, another Arduino. if the problem insists, then you can check for another LM35, or the code like the others said. but if the problem didn't exist, then the board has a problem. any faulty component in supply line can cause this. from regulators to a bad joint or PCB via.

# Answer
> 0 votes
If issue with readings persist, put an RC circuit for measuring the voltage as it is similar to averaging done in software. Another thing that you can try is replacing the LM35 with a new one as sometimes it could be faulty or you might have damaged it(has happened with me). However u can easily check this by measuring the voltage at the sensing pin whether it corresponds to what you are getting. If you are working with electronics please invest in a multi-meter as it will help you in all your projects

---
Tags: arduino-uno, analogread, temperature-sensor, temperature, lm35
---


title: arduino uno freezes

text:
# Question
Title: arduino uno freezes
Is there a reason why my Arduino Uno freezes after a few minutes of running with power coming from a usb cable connected to my pc?

```
#include <GY6050.h>
#include <Wire.h>
#include <VarSpeedServo.h>

#define angle1 20
#define angle2 90

#define Sensor_BL A0
#define Sensor_BR A1

VarSpeedServo servo;

GY6050 gyro1(0x68);
GY6050 gyro2(0x69);

int X = 0;
int Y = 0;

int y1_axis = 0;
int y2_axis = 0;

int sensorBL;
int sensorBR;

int speed = 0;
int angle = 0;

int prev_y1_axis = 0;
int y1_hold = 0;
unsigned long timer;
int start = 1;
byte step = 0;
String steps , laststep;
int freq;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  gyro1.initialisation();
  gyro2.initialisation();
  delay(100);
  servo.attach(8);
  servo.write(90);
}

void loop() {
  y1_axis = gyro1.refresh('A', 'Y');
  y2_axis = gyro2.refresh('A', 'Y');
  sensorBL = analogRead(Sensor_BL);
  sensorBR = analogRead(Sensor_BR);

  //0 right - 90 centr - 180 left

  if (sensorBL > 250) {
    speed = map( sensorBL , 0 , 1023 , 0 , 255);
    if (sensorBL < 700) { //less pressure 90+20=110
      servo.write(95 , speed);
      angle = 95;
    }
    else if (sensorBL > 700) { //more pressre 90+90 = 180
      servo.write(105 , speed);
      angle = 105;
    }
  }
  else if (sensorBR > 250) {
    speed = map( sensorBR , 0 , 1023 , 0 , 255);
    if (sensorBR < 700) {
      servo.write(95 , speed);
      angle = 95;
    }
    else if (sensorBR > 700) {
      servo.write(105 , speed);
      angle = 105;
    }
  }
  else if ((start == 0 || millis() - timer > 800) && y1_axis > -90 && y1_axis < 20 && y2_axis > -90 && y2_axis < 20 && sensorBL < 10 && sensorBR < 20) //flat dead end no servo movement - center position - can we separate on different lines the pressure sensor and accell so that I can set the dead end value separately for the press sens and acc ?
  {
    servo.write( 85 , 15);
    //Serial.println("Servo goes to zero");
    start = 1;
    step = 0;
    angle = 0;
    steps = "0";
  }
  else if ((y1_axis < 60 & y1_axis >40) && (step == 0 || step == 2))
  {
    step = 1;
    steps = "1";
  }
  else if ((y2_axis < 55 & y2_axis > 40) && (step == 0 || step == 1))
  {
    step = 2;
    steps = "2";
  }

  if (!steps.equals(laststep)) {

    if ((step == 1 || step == 2) && millis() - timer <= 700) {
      if (freq > 1) {
        servo.write(70 , 20);
        angle = 70;
      }
      else {
        servo.write(78 , 20);
        angle = 78;
      }
      freq++;
    }
    else if ((step == 1 || step == 2 && millis() - timer > 750)) {
      servo.write(78 , 20);
      angle = 78;
      freq = 0;
    }

    timer = millis();
  }
  //Serial.println("Y1: " + String(y1_axis) + " Y2: " + String(y2_axis) + " S1: " + String(sensorBL) + " S2: " + String(sensorBR) + " Millis: " + String(millis() - timer) + " Step: " + String(steps) + " Last: " + String(laststep) + " Angle: " + String(angle));
  Serial.println("Millis: " + String(millis() - timer) + " Angle: " + String(angle));

  laststep = steps;

}

```

---

I am using the pc usb power cable to power on the arduino and 2 accelerometers and one SG90 hobby servomotor. Would the best way power on the 1 servo with its own power supply ?

What power supply would you suggest for 1 servomotor?

When not connected to the pc, I use 9v battery to power on together the arduino and the one servomotor

thanks!

---

It is the part of the code for moving forward and backward in this locomotion system I came up with

https://github.com/marcob2178/Arduino-Based-Game-Locomotion

https://www.youtube.com/watch?v=OYTlF2GhXpQ

Sensors are mounted on shoes

# Answer
You haven't said or shown how your servo is powered but both the Arduino power supply is limited and your computer's USB power has a protective limit. You can power an SG90 hobby servo from the Arduino, but any larger servo needs its own supply, with only the PWM signal being taken from the Arduino. If the servo (or any other device or collection of devices) exceeds the capabilities of the Arduino's power supply, its output voltage will fall. One of the consequences of that is that the MCU stops. Or if your computer's USB supply is exceeded, it will shut down protectively.

My guess is you're powering your motor from the Arduino and it's starving the MCU.
> 1 votes

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


# Question
Title: How to burn bootloader and upload sketches on custom arduino?
Ive turned a project I breadboarded with arduino and other modules into one pcb on EAGLE. The pcb includes the ATMEGA328p smt version that doesn't have the bootloader installed. My question is then what module or components can I use to burn the bootloader onto the atmega and upload programs to it together?

# Answer
> 1 votes
You can use a second Arduino as a standalone programmer for it, either to upload your sketch directly, or to upload a bootloader (after which you'd upload your sketch in the normal way). The example program, ArduinoISP, uploaded into the second Arduino is what can do this. Here is a link to a how-to article for doing just that.

If you haven't already populated your PCB, good - sometimes your external (to the MCU) circuitry can interfere - but it's worth a try, even if you have.

---
Tags: programming, bootloader
---


# Question
Title: Receive multiple data from arduino using String builder
I am working on a small project where I have to read data from different hardware and display it on android app. I am using arduino Uno to get the values from a sensor and a motor and I use a bluetooth module to send the data to the android device. I know how to read data from motor only but not from motor AND sensor. The data displayed on the arduino can be assumed as follows:

Motor: 132

Sensor: 258

Motor: 259

Sensor: 992

So first, we will read the value of the motor then the sensor then the motor and so on. Here is part of the code where I used handler and string builder to read data from the motor. How to modify the code in order to read from BOTH the motor and sensor and keep the updating the values?

Code:

```
Handler mHandler = new Handler()
    {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    byte[] readBuf = (byte[]) msg.obj;
                    String strIncom = new String(readBuf, 0, msg.arg1);
                    sb.append(strIncom);
                    int endOfLineIndex = sb.indexOf("\r\n");
                    if (endOfLineIndex > 0) {
                        String sbprint = sb.substring(0, endOfLineIndex);
                        sb.delete(0, sb.length());
                        motor.setText(sbprint);             // update TextView
                    }

                    break;
            }
        };
    };

```

# Answer
You can convert each value to string before sending to bluetooth using `string.contain("string")`, like this:

```
if (sbprint.contains("C"){
    temptv.setText(sbprint);}
if (sbprint.contains("H")){
    humidtytv.setText(sbprint);}

```
> 1 votes

---
Tags: arduino-uno, android
---


title: LCD connection problem

text:
# Question
Title: LCD connection problem
First of all, i have some problems with an lcd . For a better understanding, the lcd datasheet could be found here: https://www.mikrocontroller.net/attachment/53098/DGF-12232-S1FBLY-325-17231-1006.pdf

i want to connect it to arduino mega but it has 20 pins and i can't figure it out how it should be connected. Could someone help me ?

# Answer
For those reading this answer prior to acquiring an LCD for an Arduino project, consider using a more common alpha / numeric LCD rather than a graphic LCD or GLCD. Likely there will be more examples to follow as well as more software with more community support.

The linked to Graphical LCD (or GLCD) uses a SED1520 controller. Searching the Arduino community resulted in finding this openGLCD project. There may be others. Looking here (near the end of 2019) we see the comment "added custom sed1520 init routine to fully initialize sed1520 chips" next to the sed1520\_Device.h file. Likely this project supports GLCD modules which use the SED1520 chip.

With regards to wiring GLCD module, on page 19 of the specifications linked to in the question, the table in section 5.1 lists the description of the 20 GLCD pins.
> 1 votes

---
Tags: lcd
---


# Question
Title: Serial doesn't initialise on Arduino Mega 2560 when not powered via the USB port
I am working on a project with a Mega 2560 and a Sim800L module.

Everything works fine, however if i don't connect the USB port (at least once) and power only externally (either by Vin unregulated 7-12V or 5V regulated pin) the program will seem not to initialize serial in setup().

I found this which is related to the issue but not a proper workaround: https://forum.arduino.cc/index.php?topic=24642.0

edit: I can confirm using a resistor to short pins 0+1 together (serial) works but it is not a proper solution. This means you have to disassemble your project to access the resistor or add a switch if you want to use USB to debug later or upload new code. Another workaround which i need to test is to remove all Serial code (because i can in my specific project), but again this is not a proper solution. Any ideas please?

edit2: for comments

```
if(SIM900.available()>0){
// AT command to set SIM900 to SMS mode
SIM900.print("AT+CMGF=1\r");
delay(100);
// Set module to send SMS data to serial out upon receipt
SIM900.print("AT+CNMI=2,2,0,0,0\r");
delay(100);
textMessage = SIM900.readString();
textMessage.toUpperCase();
Serial.print(textMessage);
delay(10);
}

if(textMessage.indexOf("SET PHONE")>=0){
// Set phone number to receive notifications
phoneNumber = textMessage.substring(9,21);
Serial.println("Phone number set to: " + phoneNumber);
String message = "Notification number set to: " + phoneNumber + "\nSend 'Help' for additional commands.\nNote in case of reset number returns to hardcoded default";
sendSMS(message);
Serial.println("Confirmication of phone number change sent");
textMessage = "";
}

```

# Answer
Ok i found the issue and the solution.

For some reason it seems that while the MCU is running Setup(); hardware or software serial don't work properly.

In my case i have code that set the SIM module to SMS mode and to send those messages to the serial port.

For some reason it doesn't send them (or probably the module is not ready to accept them).

Connecting the USB cable reset the arduino and run setup() when opening the serial monitor setting the module in the correct mode.

Adding this code in the main loop solves this issue even though i have them powered both by the same step down converter.

edit: That turns out 1 hour later after debugging more is not exactly a proper solution to the issue. That command to set into SMS mode only works when you are connected to the network.

I have a check for that and a reset function.

So now at Setup() i wait 10s for the module to boot up so it is ready to open a serial port, then i check if it is connected to the network before i send the commands to set into SMS mode.

Example:

```
// Initializing serial commmunication
Serial.begin(57600);
delay(10000);

while (ini){
    Serial3.begin(57600);
    delay(1000);
    Serial3.print("AT+CGREG?\r");
    delay(100);
    netStatus = Serial3.readString();
    if (netStatus.charAt(22) == '5' || netStatus.charAt(22) == '1') {
         digitalWrite(LED_NET, HIGH);
         ini=false;
         }
    else {
        digitalWrite(LED_NET, LOW);
        digitalWrite(resetPin, LOW);
        delay(2000);
        digitalWrite(resetPin, HIGH);
        delay(30000);
        }
}
  Serial.print("SIM800 ready...");

  // AT command to set SIM800 to SMS mode
  Serial3.print("AT+CMGF=1\r");
  delay(100);
  // Set module to send SMS data to serial out upon receipt
  Serial3.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);

```
> 1 votes

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


title: ESP8266 Deep Sleep Wake Up

text:
# Question
Title: ESP8266 Deep Sleep Wake Up
I am testing esp8266's deep sleep mode. And i have some questions about that.

1- I want to wakeup esp via timer. I did it. I implemented GPIO16-RST connection and this version done.

2- I want to ake up esp with external button too. It means, I will use timer and button to wake up esp8266 same time.

Is it possible and how can i connect button to RST pin that while GPIO16 has already connected to RST?

# Answer
The reset pin of the ESP8266 has internal pull-up. Connecting the pin to ground activates the reset of the ESP.

To create a reset button, wire a momentary push button between reset pin and ground. Pushing the button will connect reset to ground, causing a reset of the esp8266.

The io 16 pin is connected internally to RTC, which in deep sleep counts down the time and then sets the pin LOW. If io 16 is wired to reset pin, this resets the ESP8266 to end the deep sleep.

The only way to end the deep sleep of the esp8266 is a reset. There is no conflict between RTC io 16 and a reset button, both wired to reset pin. Both can activate the reset to end the deep sleep.
> 1 votes

---
Tags: esp8266, sleep
---


# Question
Title: Problem with power supply ws2812b Arduino 5v vs 12v
I have an Arduino wired to ws2812b with 10 100uF capacitors and 2 1000ohm resistors(picture). When I'm plugging 5v power supply everything is working when I plug 9v battery everything is fine but when I'm plugging 12v power supply in one moment leds stops.(NeoPixel standardtest example. How I can power the ws2812b by 12v

# Answer
> 1 votes
The regulator on an Arduino is likely analog. On this Arduino Uno the regulator is an analog NCP1117ST50T3G as seen in this schematic. On page 2 of the NCP1117ST50T3G spcification it is stated:

> Internal thermal shutdown protection limits the die temperature to approximately 175°C. Proper heatsinking is required to prevent activation.

Being an analog power regulator, the difference between the input voltage and the regulated output voltage eventually turns into heat. This may explain why a 9 volt source may work (drop is only 9V - 5V = 4V) while a 12 volt source may not work (drop is 12V - 5V = 7V).

Consider using a 5 volt power source avoiding the Arduino analog power regulator. Or, if the only source is 12 volts (for example an automobile), consider using an external switching or buck power supply to convert the 12 volt down to 5 volts and again avoiding the Arduino analog power regulator. Lastly, it should be possible to still power the Arduino with 12 volts and use its internal power regulator to only power the Arduino. Then independently power the LED strip using an external power regulator. This last option will likely have the benefit of eliminating the capacitor bank seen in the question and associated components.

# Answer
> 0 votes
See if arduino works with strips disconnected Assuming that you are connecting your 12V to the breadboard Do not try to use Arduinos voltage regulator to supply something this massive as LED strip (if you did, then arduinos voltage regulator would be burned by now)

If arduino works with strips disconnected If it does: check the voltage of the strip if its not written check if each LED has its own resistor. If it doesn't you may see Two or three LED per resistor in series That usually means 12V This would mean that LEDS would have been dim when on 5V Then you need to drop the voltage(difficult, I am not sure if even LM350A is strong enough)you can try putting 100 ohm resistor before and across the LED strip this will not be sustainable, but might light the LEDS bit for a bit.

if it works with strips disconnected: If it doesn't: Does arduino start? If it does. see first half of this message If it doesn't: Does arduino start when connected via USB? (Disconnect from breadboard for this test) if it doesn't board is damaged if it does you have burned your voltage regulator. I am not sure what are those capacitors there for. LED's arent very picky about the supply and standard CE marked (legaly) 12DC supply would be suitable for both arduino and the strip supply out of the box

---
Tags: ws2812
---


title: LCD displaying weird text

text:
# Question
Title: LCD displaying weird text
I am doing a project that requires input from a keypad to be displayed on the LCD display.

`lcd.print()` displays in proper form, but when the I press characters on the keypad, they are overwritten as weird symbols.

Any help would be appreciated.

Here's the code:

```
void setup()
{
  Serial.begin(9600);
  Serial.println("LCD test with PWM contrast adjustment");
  pinMode(13,OUTPUT);
  analogWrite(6,Contrast);

  lcd.begin(16,2);

  pinMode(buzzer, OUTPUT);
  lcd.print(" Electronic ");
  Serial.print(" Electronic ");
  lcd.setCursor(0,1);
  lcd.print(" Keypad Lock ");
  Serial.print(" Keypad Lock ");
  delay(2000);
  lcd.clear();
  lcd.print("Enter Ur Passkey:");
  Serial.println("Enter Ur Passkey:");
  lcd.setCursor(1,0);
  for(int j=0;j<4;j++)
    EEPROM.write(j, j+49);
  for(int j=0;j<4;j++)
    pass[j]=EEPROM.read(j);
}

```

# Answer
> 1 votes
stick to one type of variable, to prevent mix-up

So if you stick to a byte (uint8\_t) type for keypad:

```
uint8_t keys[4][3] = {
  {1,2,3},
  {4,5,6},
  {7,8,9},
  {0xF,0xA,0xB}                 // F-*  B-#
}

```

then you can save it to your EEPROM as a byte and read it as a byte.it will prevent mix-up. your code which you are not displaying (everybody here can write one of those faster then to download it from here)already translate numbers to numbers and then you are growing them to symbols with higher value

# Answer
> 0 votes
I think you should use 48 instead of 49.

48 is the ASCII symbol of 0. If you add a number from 0-9 to it, than you get the ASCII symbols of '0' to '9'.

(and a small sidenote: `Enter Ur Passkey:` is more than 16 characters; also it is more 'professional not to make slang texts to try to fit it, why not using `Enter Passkey:` instead?

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


# Question
Title: Can I put a resistor in the ground connection of my DHT22 sensor?
I'm building a project that uses a couple of Adafruit DTH22 temp/humidity sensors. (https://www.adafruit.com/product/385)

I have them wired into my project box through 3.5mm mini plugs (The kind that are commonly used by stereo earbud headphones for MP3 players.)

More than half the time, when I plug/unplug one of my sensors, my Arduino restarts.

My guess is that as I plug in the plug, it sometimes momentarily shorts +5V and ground, causing the +5 source to my Arduino to lose voltage.

These sensors apparently draw single-digit mA of current at peak (like 1.5mA, according to the spec.)

Could I wire a 120Ω or 150Ω resistor in line with the ground connection to the DHT22? This would limit the max current it could carry to around 40mA, which would not be a problem for my power supply (which is fed through the USB port on the Arduino, and thus is limited to 500mA.) Putting a resistor on the ground would limit the current to ground from either the VCC connection to the sensor or the data connection. It would also cause a small loss of voltage to both the data line and the VCC connection.

Would the serial connection between the DHT22 and my Arduino tolerate a 120Ω resistor, even if I connect it via ≈15M of 28-gauge wire?

I could also put the resistor into the VCC wire, but that would only current-limit a VCC-to-ground short, not data-to-ground.

# Answer
Your case : Check wire (shors ?) and pin configuration (out ??)

General : No resistor in a ground path.

Decoupling supply : one can insert a 100 Ohms resistor between the arduino +5V and the +5V sensor : but ALWAYS use a decoupling capacitor : connect a 100µF betwen +5V sensor and groud. One can add a 100nF ceramic in paraller for digital devices.

Safety in case of bad I/O config : Using a 1kOhms restisor between Arduino and Device is good, if next to the Arduino (not at the other end of sensor cable, or use 330 Ohms at eatch end of cable).
> 1 votes

---
Tags: hardware, temperature-sensor, current
---


# Question
Title: Having trouble with motor shield running off external power source
I apologize if I don't immediately give important info, I'm very new to arduino's/circuity of any kind. I'll try to include as much info as possible.

Some preface: I'm currently working on a project that generates electricity using TEG's (Thermoelectric generator). The setup I currently have is able to output upwards of 9V. The motor I'm using is able to run when directly connected to the TEG wires, sp they produce enough electricity to work. Due to the nature of the project, a stopping mechanism is being used via a photoresistor and an LED. Essentially when the light signal picked up by the photoresistor is low enough, power is cut to the motor.

So up until recently, the motor and the Arduino board/motor shield (Arduino UNO, Arduino Motor Shield Rev3) were being run using a 9V battery. Everything worked correctly, the motor would start when needed and stop when needed. Once I switched to the TEG's the set up stopped working (motor stopped running). What is weird is that if I connect a voltmeter to channel 1 of the motor shield, I read 6V-7V (some voltage drop but not drastic) when the LED was on and 0 when the led was off. So everything seemed to still be working, but the motor itself just won't actually run. In fact, when the LED is on, it makes a very faint noise for a second but doesn't run.

The only thing I can think of is that the current being produced by the TEG's is only enough to power the motor when directly connected, but when wired indirectly through the board thus powering the board, it no longer has enough amperage.

I included the code I wrote for it, which worked fine with a 9V battery powering the motor/board.

```
const int sensorPin = A5;
const int ledPin = 5;
int lightLevel;

void setup(){
  Serial.begin(9600);
  pinMode(12,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  lightLevel = analogRead(sensorPin);
  lightLevel = constrain(lightLevel, 0, 800);
  Serial.println(lightLevel);

  if(lightLevel < 200){
    digitalWrite(9,LOW);
    digitalWrite(12,HIGH);
    analogWrite(3,255);
  }
  if(lightLevel > 200){
    digitalWrite(9,HIGH);
    analogWrite(3,0);}
}

```

# Answer
Try a decoupling capacitor acorss your TEG : 100µF/35v (+ at the +). This will avoid micro power drops... Verify that y hardware driving motor works below 9V.
> 1 votes

---
Tags: arduino-uno, power, motor, arduino-motor-shield
---


# Question
Title: Why am I receiving this error: “expected unqualified-id before numeric constant”?
```
#include <LiquidCrystal.h>
LiquidCrystal 1cd(12, 11, 5, 4, 3, 2);
const int switchPin = 6;
int switchState = 0;
int prevSwitchState = 0;
int reply;
void setup() {
 1cd.begin(16, 2);
 pinMode(switchPin, INPUT);
 1cd.print("Interroga");
 1cd.setCursor(0, 1);
 1cd.print("la sfera!");
 // put your setup code here, to run once:

}

void loop() {
  switchState = digitalRead(switchPin);
  if (switchState != prevSwitchState){
    if (switchState == LOW){
      reply = random(8);
      1cd.clear();
      1cd.setCursor(0, 0);
      1cd.print("La sfera dice");
      1cd.setCursor(0, 1);
      switch(reply){
        case 0:
        1cd.print("si");
        break;
        case 1:
        1cd.print("probabilmente");
        break;
        case 2:
        1cd.print("certo");
        break;
        case 3:
        1cd.print("bene");
        break;
        case 4:
        1cd.print("forse");
        break;
        case 5:
        1cd.print("chiedi ancora");
        break;
        case 6:
        1cd.print("improbabile");
        break;
        case 7:
        1cd.print("no");
        break;// put your main code here, to run repeatedly:
      }
    }
  }
 prevSwitchState = switchState;
}

```

# Answer
> 1 votes
You're using an invalid variable name (1cd starts with the number 1).

* Variables can consist of both uppercase (A-Z) and lowercase(a-z) letters.
* Variables can contain numbers 0 to 9, but **cannot start with a number**.
* Variables may not have the same names as Arduino language keywords, e.g. you cannot have a variable named float.
* If you try and save a sketch with a space in the file name, the IDE will change the space to an underscore.

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


title: Coding issue with for loop

text:
# Question
Title: Coding issue with for loop
I have an issue with this piece of code concerning the use of 3 capcitance sensors each outputting a midi note chosen from one of three scales selected with a pot. Regarding the sensors triggering notes and the pot selecting scales, everything is perfect. However, each sensor will play each of the scale's notes by itself with each finger press. This of course is not what I am intending as each sensor should only trigger its corresponding note. Thanks for any clues and tips!!

```
    #include <SPI.h>
#include <CapacitiveSensor.h>
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();
// midi notes
int c3 = 36;
int d3 = 38;
int e3 = 40;
int g3 = 43;
int a3 = 45;
int c4 = 48;
int d4 = 50;
int e4 = 52;
int g4 = 55;
int a4 = 57;
int c5 = 60;
int d5 = 62;
int e5 = 64;
int g5 = 67;
int a5 = 69;
int c6 = 72;

/////// code & 2d array for scale selection
const int columns = 3;
const int scales = 3;
int potVal = 0;
const int  notes[scales][columns] = {
  {c3, d3, e3},
  {c4, d4, e4},
  {c5, d5, e5}
};

const int numberOfSensors = 3;
int sensorPin[numberOfSensors] = {38, 39, 40};
/////////

static const unsigned ledPin1 = 22;      // LED pin on Arduino Mega
static const unsigned ledPin2 = 23;
static const unsigned ledPin3 = 24;

int val = 10; // this value is best around "10". works with "multiply"
// and "Threshold" to enable Polyphony!
int Threshold = (0); //Threshold of triggered mp3
int Multiply = (0);  //increases or decreases the overal sensitivity

CapacitiveSensor   cs_2_38 = CapacitiveSensor(2, 38); //Mega sensor pins
CapacitiveSensor   cs_2_39 = CapacitiveSensor(2, 39);
CapacitiveSensor   cs_2_40 = CapacitiveSensor(2, 40);

void setup()
{
  for (int i = 0; i < numberOfSensors; i++) {
    pinMode(sensorPin[i], INPUT);
    Serial.begin(9600); //midi(31250)

    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);

  }
}
void loop()
{
  int potVal = map(analogRead(A2), 0, 1024, 0, 3);
  for (int i = 0; i < numberOfSensors; i++) {
    checkSensor(potVal, i);
  }
}
void checkSensor(int scaleIndex, int columnIndex)
{
  static boolean lastSensorHit1 = false;
  static boolean lastSensorHit2 = false;
  static boolean lastSensorHit3 = false;

  bool sensorHit3 = cs_2_40.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit2 = cs_2_39.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit1 = cs_2_38.capacitiveSensor(Multiply) / val > (Threshold);

  Multiply = map(analogRead(A0), 0, 1023, 150, 5);
  Threshold = map(analogRead(A1), 0, 1023, 150, 5);

  long total1 =  cs_2_38.capacitiveSensor(Multiply);
  long total2 =  cs_2_39.capacitiveSensor(Multiply);
  long total3 =  cs_2_40.capacitiveSensor(Multiply);

  int Art1 = total1 / val;
  int Art2 = total2 / val;
  int Art3 = total3 / val;

  if (sensorHit1 != lastSensorHit1)

    if (sensorHit1 && !lastSensorHit1)
    {
      digitalWrite(ledPin1, HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 80, velo 127 on channel 1)
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin1, LOW);
      MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
      MIDI.sendControlChange(64, 0, 1);
    }

  if (sensorHit2 != lastSensorHit2)

    if (sensorHit2 && !lastSensorHit2)
    {
      digitalWrite(ledPin2, HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 79, velo 127 on channel 1)
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin2, LOW);
      MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
      MIDI.sendControlChange(64, 0, 1);
    }

  if (sensorHit3 != lastSensorHit3)

    if (sensorHit3 && !lastSensorHit3)
    {
      digitalWrite(ledPin3, HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 78, velo 127 on channel 1)
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin3, LOW);
      MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
      MIDI.sendControlChange(64, 0, 1);
    }

  lastSensorHit1 = sensorHit1;
  lastSensorHit2 = sensorHit2;
  lastSensorHit3 = sensorHit3;

}

```

# Answer
Well after more tinkering I found that the one change that fixed everything was simply this (in the if/else statements).....changing `MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);` to `MIDI.sendNoteOn(notes[scaleIndex][0], 127, 1);` \[columnIndex\] needs to be a \[0\], \[1\] or \[2\] representing one of three scales in the assigned array. This is fine as I'm writing out the code for a few sensors. However, for 16 sensors I'm going to have to use a for loop ....Thanks for all your help! Here's the full code for anyone who needs it...including some alterations to the leds...

#include <CapacitiveSensor.h>
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();

 int c3 = 36;
 int d3 = 38;
 int e3 = 40;
 int g3 = 43;
 int a3 = 45;
 int c4 = 48;
 int d4 = 50;
 int e4 = 52;
 int g4 = 55;
 int a4 = 57;
 int c5 = 60;
 int d5 = 62;
 int e5 = 64;
 int g5 = 67;
 int a5 = 69;
 int c6 = 72;

const int columns = 3;
const int scales = 3;
int potVal = 0;
const int  notes[scales][columns] = {
  {c3, d3, e3},
  {c4, d4, e4},
  {c5, d5, e5}
};
const int numberOfSensors = 3;
const int sensorPin[numberOfSensors] = {38, 39, 40};

const int ledPin[numberOfSensors] = {22, 23, 24};

const int val = 10; // this value is best around "10". works with "multiply"
// and "Threshold" to enable Polyphony!
int Threshold = (0); //Threshold of triggered mp3
int Multiply = (0);  //increases or decreases the overal sensitivity

CapacitiveSensor   cs_2_38 = CapacitiveSensor(2, 38);
CapacitiveSensor   cs_2_39 = CapacitiveSensor(2, 39);
CapacitiveSensor   cs_2_40 = CapacitiveSensor(2, 40);

void setup()
{
  Serial.begin(9600);//midi(31250)
  for (int i = 0; i < numberOfSensors; i++) {
    pinMode(ledPin[i], OUTPUT);
}
}
void loop()
{
    int potVal = map(analogRead(A2), 0, 1024, 0, 3);
for (int i = 0; i < numberOfSensors; i++) {
    checkSensor(potVal,i);
  }
}
void checkSensor(int scaleIndex, int columnIndex)
{
  static boolean lastSensorHit1 = false;
  static boolean lastSensorHit2 = false;
  static boolean lastSensorHit3 = false;

  bool sensorHit1 = cs_2_38.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit2 = cs_2_39.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit3 = cs_2_40.capacitiveSensor(Multiply) / val > (Threshold);

  Multiply = map(analogRead(A0), 0, 1023, 150, 5);
  Threshold = map(analogRead(A1), 0, 1023, 150, 5);

  if (sensorHit1 != lastSensorHit1)

    if (sensorHit1 && !lastSensorHit1)
    {
      digitalWrite(ledPin[0], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][0], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[0], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][0], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }
    if (sensorHit2 != lastSensorHit2)

    if (sensorHit2 && !lastSensorHit2)
    {
      digitalWrite(ledPin[1], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][1], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[1], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][1], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }
    if (sensorHit3 != lastSensorHit3)

    if (sensorHit3 && !lastSensorHit3)
    {
      digitalWrite(ledPin[2], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][2], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[2], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][2], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }

  lastSensorHit1 = sensorHit1;
  lastSensorHit2 = sensorHit2;
  lastSensorHit3 = sensorHit3;

}````````

> 1 votes

# Answer
I am just learning this program so I could be way off on this and I apologize if I am.

Instead of the loop inside of `void setup()` initialize each pin individually. Also you are telling the system to start the MIDI and set the `pinMode` 3 times.

Inside the `Void checkSensor` function you set all the `sensorHits` every time the function runs, you might save a little bit you do `lastSensorHit(i)`.

I just noticed you have the if command running this function as `(int i = 0; i < numberOfSensors; i++)`. You don't have a sensor 0, so you might want to change that to `(int i = 1; i < numberOfSensors+1; i++)// or just change it to 4`.

Inside the function checkSensor, it doesn't look your variable val has a value.

`if (sensorHit1 != lastSensorHit1)` this is still under the same function as before and it is going to run once per channel that you specified in the controlling if function. Maybe move this into the void loop() or create its own function?
> 1 votes

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


title: Can't use uint16_t in library

text:
# Question
Title: Can't use uint16_t in library
I wonder why the following minimal example sketch doesn't compile (`unknown type name 'uint16_t'`):

`sketch_does_not_compile.ino`:

```
#include "myheader.h"

void setup() {
  char a[]="hello world";
  uint16_t l=str_len(a);
  Serial.println(l);
}

void loop() {}

```

`myheader.c`:

```
uint16_t str_len(char* input_string) {
  uint16_t i=0;
  while (input_string[i++]!='\0');
  return i;
}

```

`myheader.h`:

```
#include "myheader.h"

uint16_t str_len(char* input_string);

```

Compilation fails with:

```
myheader.c: At top level:
myheader.c:3:1: error: unknown type name 'uint16_t'
 uint16_t str_len(char* input_string);
 ^
exit status 1
unknown type name 'uint16_t'

```

Using `uint16_t` in the .ino-file directly like in the sketch below compiles fine.

`sketch_compiles.ino`:

```
uint16_t str_len(char* input_string) {
  uint16_t i=0;
  while (input_string[i++]!='\0');
  return i;
}

void setup() {
  char a[]="hello world";
  uint16_t l=str_len(a);
  Serial.println(l);
}

void loop() {}

```

What am I missing?

# Answer
Using `#include <Arduino.h>` in your myheader.h will also include `<stdint.h>` and probably solve this.

The Arduino IDE automatically includes Arduino.h in the sketch itself, but apparently not for external stuff.
> 5 votes

---
Tags: c++, c, compilation-errors, compiler
---


# Question
Title: How to detect the direction of rotation with a sensor encoder timing disk (photoelectric speed sensor)?
I am making a DIY gaming steering wheel and am stuck. For measuring the rotation of the wheel, I'm using a sensor encoder timing disk, which is usually found in printers. - https://robu.in/product/photoelectric-speed-sensor-encoder-coded-disc-code-wheel.

A lot of tutorials on youtube use this. But I just cannot seem to understand how to use this sensor.

Please help me in figuring this out: using this sensor, how to -

1. Measure how much the wheel rotated?
2. Know which direction did the wheel rotates in (clockwise, anti-clockwise).

PS: I tried using a rotatory encoder, but it is unable to sense rotation when rotated by a 1000 RPM motor. Would love to understand why.

Thanks!

# Answer
> 1 votes
It seems to be a A/B coding : if A gets high before B, it's one way (count for exemple), and if B gets high before A, it's other way (decount). So, connect power and ground. Then connect the two wires to input pins :

```
    int P_A=2; int P_B=3; //Inputs
    long int position = 0; //Position of wheel
    long int lastPosition = 0; //last position of wheel : for speed computing

```

Notice that one pin must be an hardware interrupt pin (Uno 2 an 3 are interrupt pins. Then attach interrupt in the stup :

```
    attachInterrupt(2, wheel, RISING);  //wheel is arbitray

```

Then create the interruption code :

```
    void wheel(){
        int sB = digitalRead(P_B);
        if (sA == sB)   { //Clockwise
        position++;
        }
        else   { //Counterclockwise
        position--;
        }

```

Then, in your loop, you can print position when it changes to read current position :

```
    if(lastPosition != position){
        Serial.println(position);
    }

```

i hope it will help... Notice that if you use both interruptions, you get a better resolution, but speed limit is lower.

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


title: Low power error with serial connection

text:
# Question
Title: Low power error with serial connection
So I want to create an application where I can send data with a SIM-Module, and when it's not needed it should fall into a "standby-mode" because it's battery powered. But I always get this exact output, and I have no clue why:

> ```
> wakeup condition fulfilled
> Tes
>
> ```

When it wants to print out "Testing ..." it always stops after three letters.

Here's my code:

```
/*
 *  PINOUT:
 *
 *  UNO >> SIM800L
 *  RX (8) >> TX
 *  TX (9) >> RX
 *
*/

#include <BareBoneSim800.h>

BareBoneSim800 sim800("hologram"); //APN of the carrier

void sendData(char *url)
{
  sim800.enterSleepMode(false);
  Serial.println("Testing GSM module For GPRS Connectivity");
  delay(8000); // this delay is necessary, it helps the device to be ready and connect to a network

  Serial.println("Should be ready by now");
  bool deviceAttached = sim800.isAttached();
  if (deviceAttached)
    Serial.println("Device is Attached");
  else
    Serial.println("Not Attached");

  // Connecting the the GPRS APN Network
  Serial.println(" Connecting to APN");
  bool netConnect = sim800.gprsConnect();
  if (netConnect)
    Serial.println("Connected to Network");
  else
    Serial.println("An Error Occured");

  if (netConnect)
  {
    Serial.println("Making HTTP Get Request");
    String result = sim800.sendHTTPData(url);
    Serial.println("Received Info: ");
    Serial.println(result);

    Serial.println("Current time utc+0: ");
    Serial.println(sim800.getTime());
  }

  sim800.closeHTTP(); // disconnect from server
  sim800.gprsDisconnect();
  sim800.enterSleepMode(true);
}

void wakingUp()
{
  //hardware interrupt measurement goes here
}

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

  while (!Serial)
    ;

  //Save Power by writing all Digital IO LOW - note that pins just need to be tied one way or another, do not damage devices!
  for (int i = 0; i < 20; i++)
  {
    if (i != 8 && i != 9 && i != 2)
    {
      // pin 2 is for waking the arduino up from deep sleep

      //pin 8 and 9 are used to connect with the sim module,
      //these pins must be exluded from power saving
      pinMode(i, OUTPUT);
    }
  }

  attachInterrupt(0, wakingUp, FALLING); //interrupt for waking up

  /*
      various flags for turning stuff down when not needed
based on this very good tutorial https://www.youtube.com/watch?v=urLSDi7SD8M

  */
  //SETUP WATCHDOG TIMER
  WDTCSR = (24);      //change enable and WDE - also resets
  WDTCSR = (33);      //prescalers only - get rid of the WDE and WDCE bit
  WDTCSR |= (1 << 6); //enable interrupt mode

  //Disable ADC - don't forget to flip back after waking up if using ADC in your application ADCSRA |= (1 << 7);
  //ADCSRA &= ~(1 << 7);

  //ENABLE SLEEP - this enables the sleep mode
  SMCR |= (1 << 2); //power down mode
  SMCR |= 1;        //enable sleep

  //BOD DISABLE - this must be called right before the __asm__ sleep instruction
  //MCUCR |= (3 << 5);                      //set both BODS and BODSE at the same time
  //MCUCR = (MCUCR & ~(1 << 5)) | (1 << 6); //then set the BODS bit and clear the BODSE bit at the same time
  __asm__ __volatile__("sleep"); //in line assembler to go to sleep
}

void loop()
{
  //do nothing, use ISR instead
}

char targetURL[] = "http://www.example.com/restAPI/";

ISR(WDT_vect)
{
  //DON'T FORGET THIS!  Needed for the watch dog timer.  This is called after a watch dog timer timeout - this is the interrupt function called after waking up
  //todo, turn on adc conversion again

  int halfHourCounter = 0; //30 minutes => 225 8sec intervals

  bool wakeUpCondition = (halfHourCounter % 225 == 0);

  if (wakeUpCondition)
  {
    Serial.println("wakeup condition fulfilled");
    //reset counter
    halfHourCounter = 0;

    //ADCSRA |= (1 << 7); // turn analog digital conversion back on

    //... measure data and send it away :)
    sendData(targetURL);

    //ADCSRA &= ~(1 << 7); // disable ADC again
  }
  else
  {
    Serial.println("wakeup condition not fulfilled");
  }

  halfHourCounter += 1;

} // watchdog interrupt

```

I'm using an Arduino Uno in combination with a SIM800L evaluation board. If I call the sendData()-function without any standby-flags enabled everything works fine. Vice versa if I call just a print function for debugging with all the standby flags enabled

# Answer
It seems, that the Sim800 module is drawing too much current, when you start it again. The voltage drops and the Arduino/Sim800 stops working.

This datasheet of the Sim800 states, that it can draw up to 2A when doing a sending burst. An USB port on a computer can provide up to 500mA and you can draw between 200mA to 1A from the Arduino's 5V pin (depending on the version, that you use: Older Unos can provide 200mA, Uno r3 should be able to provide 1A). If you draw too much current through the Arduino from USB, you will fry the diode for voltage source seletion. Also you can fry the electronics of the USB port, if you draw too much current from it (though normally the port should go into shutdown, if you do that, and work again, if you restart the computer).

You have to provide the Sim800 module with enough power and not through the Arduino. You should choose a fitting battery for this. If you don't want to involve a battery at this point, since you are still testing, you can use an USB phone charger to provide enough current.
> 1 votes

---
Tags: arduino-uno, power, networking, watchdog
---


# Question
Title: Attiny85 PB4 works for analog output but not PB3?
I can get PB4 to work but not PB3 on my ATtinny85. I'm just lighting up an led (with 150 ohm resistor) (using internal 16mhz)

```
void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);

}
void loop() {
  analogWrite(3, 15);//does not work
  analogWrite(4, 15);//works
  delay(500);
  analogWrite(3, 0);//does not work
  analogWrite(4, 0);//works
  delay(500);
}

```

# Answer
> 1 votes
The hardware `PWM` is only suported on pins with output compare altenate function on it. The pinout in your question shows `Attiny13` but the rest of your question is about `Attiny85`, which has different capabilities from `Attiny13`

As you can see, only pins with `PWM` capability are `PB0`, `PB1` and `PB4`

---
Tags: attiny85
---


title: Problem with HC-06 receiving data

text:
# Question
Title: Problem with HC-06 receiving data
I have paired 2 BT modules HC-05 and HC-06. When I write something through Serial Monitor and send it from HC-05 to HC-06, everything works well. But when I send continuous data through loop, HC-06 receives only specific amount and then just stops! Is it because of BT module, or there is something else? My code for HC-05:

```
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3);
void setup()
{
    Serial.begin(9600);
    BTserial.begin(38400);
}

void loop()
{
        BTserial.write('1');
}

```

Code for HC-06:

```
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(2, 3);
void setup()
{
    Serial.begin(9600);
    BTSerial.begin(9600);
}
void loop()
{
if (BTSerial.available())
    Serial.write(BTSerial.read());
}

```

Baud rates are good. Thanks!

# Answer
I think you have 2 problems:

* First about the shown sketch: I don't think, that the Baud rates are good. In your HC-05 code (the sender) you are using `BTserial.write('1');` without any delay or other code, thus this will run very fast, so the `SoftwareSerial` interface is almost completely busy. You sending almost at the maximum speed, that you can get with 38400 baud. On the receiving site you are using 9600 baud, which is significantly slower than 38400 baud. How should the HC-06 transmit all data, that it get's, to the Arduino, when you only use 9600 baud, but the data is coming with 38400 baud? That cannot work. You should configure the HC-05 and HC-06 to use the same baudrate, so that this cannot happen. Or - if you really don't want to - you can restrict the overall speed, that you are sending with, by just sending less data per time unit (sending the data slower, but on the same baudrate as before). This will prevent the HC-06 to get flooded by data. (Also there might be a limit on how fast you can send data over the HC-05, but I haven't tested this). All in all it mostly isn't a good idea, to do communication totally without any speed brake. That can get you into troubles, that you mostly don't want to think of.
* Secondly: In your comment you wrote, that you tried to change the baudrate, but that gave you garbled data. Since you didn't describe more, we cannot say much about this. But garbled data is a normal symptom for wrong baudrate. So it seems, that you haven't changed the baudrate successfully. I would suggest, that you again look into this and that you try to change the baudrate successfully. It is possible and there are many tutorials and codes on the web, that show how it is done. (When you again have problems with this, you can ask a question about this specific problem, including all the relevant information)
> 0 votes

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


title: Troubles with motors for arduino

text:
# Question
Title: Troubles with motors for arduino
**Why won't my motors work?**

My setup is as followed:

* arduino mega 2560 -\> L296N motor controller -\> Gikfun 3-6v dc motors.

To power the motors the setup is as followed:

* arduino mega 2560 5v -\> L296N motor controller.
* 9v battery -\> LM2596 buck converter(7-8v) -\> L296N motor controller.

I have 2 issues.

* Issue 1: that no matter the code, the motors seem to only want to run at maximum speed. The code can be the simple example code or my code **see bottom**.
* Issue 2: When given a code that changes the speed, it only works for one motor and the other motor will not run regardless if the first motor is hooked up or not, it will not work with the example code provided nor will it work in my code **see bottom**.

Note that this is not a simple wiring fix. Either the code is wrong, my hardware setup is wrong, or my hardware may not be functioning properly. **Thank you for taking the time to review.**

```
// ex code:
int a = 2;
int b = 3;
int c = 22;
int d = 23;
int e = 24;
int f = 25;

void setup(){
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);

void loop() {
  digitalWrite(c, HIGH);
  digitalWrite(d, LOW);
  digitalWrite(e, HIGH);
  digitalWrite(f, LOW);
  analogWrite(a, 0);
  analogWrite(b, 0);

```

```
// ex code:
for (int i = 0; i > 150; i++){
  analogWrite(a, i);
  analogWrite(b, i);
  delay(1000);
}

for (int i = 150; i <= 0; --i){
  analogWrite(a, i);
  analogWrite(b, i);
  delay(1000);
}

```

```
/* my code. Note that the timed function is not finished.
* I also x'd out 4 motors for easy debugging purposes.
*/
// Motor 1
int a = 2;
int a1 = 22;
int a2 = 23;
// Motor 2
int b = 3;
int b1 = 24;
int b2 = 25;
// Motor 3
int c = 4;
int c1 = 26;
int c2 = 27;
// Motor 4
int d = 5;
int d1 = 28;
int d2 = 29;
// Motor 5
int e = 6;
int e1 = 30;
int e2 = 31;
// Motor 6
int f = 7;
int f1 = 32;
int f2 = 33;
// Motor halt
unsigned int i;
int x;
int x1;
int x2;
void setup(){
  Serial.begin(9600);
  pinMode(a, OUTPUT);
  pinMode(a1, OUTPUT);
  pinMode(a2, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(b1, OUTPUT);
  pinMode(b2, OUTPUT);
  pinMode(x, OUTPUT);
  pinMode(x1, OUTPUT);
  pinMode(x2, OUTPUT);
  pinMode(x, OUTPUT);
  pinMode(x1, OUTPUT);
  pinMode(x2, OUTPUT);
  pinMode(x, OUTPUT);
  pinMode(x1, OUTPUT);
  pinMode(x2, OUTPUT);
  pinMode(x, OUTPUT);
  pinMode(x1, OUTPUT);
  pinMode(x2, OUTPUT);
}
void motor1(){
  digitalWrite(a1, HIGH);
  digitalWrite(a2, LOW);
  analogWrite(a, 0);
  if (a = 1){
    Serial.println(" MotorA not working");
  }
  delay(1000);
  digitalWrite(a1, LOW);
  digitalWrite(a2, LOW);
  delay(250);
  digitalWrite(a1, LOW);
  digitalWrite(a2, HIGH);
  analogWrite(a, 0);
  if (a = 1){
    Serial.println(" MotorAr not working");
  }
  delay(1000);
  digitalWrite(a1, LOW);
  digitalWrite(a2, LOW);
  delay(250);
}
void motor2(){
  digitalWrite(b1, HIGH);
  digitalWrite(b2, LOW);
  analogWrite(b, 0);
  if (b = 1){
    Serial.println(" MotorB not working");
  }
  delay(1000);
  digitalWrite(b1, LOW);
  digitalWrite(b2, LOW);
  delay(250);
  digitalWrite(b1, LOW);
  digitalWrite(b2, HIGH);
  analogWrite(b, 0);
  if (b = 1){
    Serial.println(" MotorBr not working");
  }
  delay(1000);
  digitalWrite(b1, LOW);
  digitalWrite(b2, LOW);
  delay(250);

}
void motor3(){
  digitalWrite(x1, HIGH);
  digitalWrite(x2, LOW);
  analogWrite(x, 0);
  if (c = 1){
    Serial.println(" MotorC not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);
  digitalWrite(x1, LOW);
  digitalWrite(x2, HIGH);
  analogWrite(x, 0);
  if (c = 1){
    Serial.println(" MotorCr not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);

}
void motor4(){
  digitalWrite(x1, HIGH);
  digitalWrite(x2, LOW);
  analogWrite(x, 0);
  if (d = 1){
    Serial.println(" MotorD not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);
  digitalWrite(x1, LOW);
  digitalWrite(x2, HIGH);
  analogWrite(x, 0);
  if (d = 1){
    Serial.println(" MotorDr not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);

}
void motor5(){
  digitalWrite(x1, HIGH);
  digitalWrite(x2, LOW);
  analogWrite(x, 0);
  if (e = 1){
    Serial.println(" MotorE not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);
  digitalWrite(x1, LOW);
  digitalWrite(x2, HIGH);
  analogWrite(x, 0);
  if (e = 1){
    Serial.println(" MotorEr not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);

}
void motor6(){
  digitalWrite(x1, HIGH);
  digitalWrite(x2, LOW);
  analogWrite(x, 0);
  if (f = 1){
    Serial.println(" MotorF not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);
  digitalWrite(x1, LOW);
  digitalWrite(x2, HIGH);
  analogWrite(x, 0);
  if (f = 1){
    Serial.println(" MotorFr not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);

}
void timed(){
  analogWrite(a, i);
  digitalWrite(a1, HIGH);
  digitalWrite(a2, LOW);
  analogWrite(b, i);
  digitalWrite(b1, HIGH);
  digitalWrite(b2, LOW);
  delay(2000);
  digitalWrite(a1, LOW);
  digitalWrite(a2, LOW);
  digitalWrite(b1, LOW);
  digitalWrite(b2, LOW);
  analogWrite(b, i);
  digitalWrite(b1, LOW);
  digitalWrite(b2, HIGH);
  analogWrite(a, i);
  digitalWrite(a1, LOW);
  digitalWrite(a2, HIGH);
  delay(2000);
  digitalWrite(a1, LOW);
  digitalWrite(a2, LOW);
  digitalWrite(b1, LOW);
  digitalWrite(b2, LOW);
}
void loop(){
  motor1();
  motor2();
  motor3();
  motor4();
  motor5();
  motor6();
  if (i = 0){
    i++;
  }
  if (i >=100){
    --i;
  }
  timed();

}

```

# Answer
I cannot say much about the example code, that you mentioned. The posted example code is not complete, also the second part with the for loop is plain wrong. A for loop looks like this

```
for(<Variable initialization>; <Condition for running the loop>; <Action done for every loop iteration>)

```

So the condition in the middle is the condition for the loop running. If the condition evaluates to `false`, the loop will not run anymore. You have the line

```
for (int i = 0; i > 150; i++)

```

where `i` has the value zero at the start of the first iteration. zero is not bigger than 150, so the condition will evaluate to false. Thus the for loop will never run. The situation is similar with the second for loop of the example code. Where did you get that code? I think you should not trust this source very much, if it gives you this code.

---

Your own code also has some errors:

* You are doing the if statement for equality wrong. If you want to check for equality, you need to use double equal signs. A single equal sign means an assertion (so you are actually changing the variable instead of check it's value), which will always evaluate to true. An example of a correct if statement is this:

```
if(i == 0)

```
* You are doing things like

```
analogWrite(a, 0);

```

all over your code. but nearly always you are doing a

```
if(a == 1)

```

directly after it. This does not make sense. The first parameter of `analogWrite()` is the pin number, where you want to output the PWM voltage. A pin number is constant, why should it ever change, unless you are plugging the motor into other pins. So the above if statement will not check, if the motor runs or not. It will compare the pin number to 1, which is always false, since none of the pin numbers, that you used, is 1.
* Again with the line

```
analogWrite(a, 0);

```

You are never providing a different second parameter as zero in your code (except for the `timed()` function, but I will get to this later). So the corresponding pin (here pin a aka 2) is turned off aka outputs LOW. With H-bridge controllers like the L296N, you use 2 digital pins to set the direction and then provide a PWM voltage (mostly at the enable pin) to change the speed. But as described, you never output a PWM voltage, so the motors cannot run, if you connected them corrected.
* Connected the the previous sentence. Your code will not run any motors. But since you wrote, that they actually do run, this means, that the hardware is also a problem. Please revisit tutorials on how to use the L296N with an Arduino or provide information about your wiring by editing your question.
* In your `loop()` function you have this passage:

```
if (i == 0){
     i++;
}
if (i >=100){
    --i;
}

```

(I already corrected the double equal signs as described above). If `i`is exactly zero, `i` will be incremented. If `i` is greater or equal to 100, it will decrement. It only changes in this code portion and it will be initialized implicitly with a value of zero at the startup of the program. So the first if statement will trigger exactly once. Then `i` is not equal to zero, so it will not increment or even ever change again. Also `i` is not greater or equal to 100 (it is 1), so it will never decrement. Your code sets `i` to 1 once, and then never changes it again. That cannot be, what you tried to do. If you want a sweep from 0 to 100 and then from 100 to 0, you need an extra variable for the direction. Something like this:

```
boolean direction=false; // define this at global scope
...
// the following code would replace your `i` related code in your loop function
if(direction){
    i++;
} else {
    i--;
}
if(i==0) direction = true;
if(i>=100) direction = false;

```
* Connected to the previous issue: Since `i` stays `1` forever, you also only write a PWM duty cycle of 1 out of 255 to the motors a and b inside the `timed()` function. A value this small is most likely not enough to even move the rotor of the motors (since motors also experience friction). Again, these motors should not run with your current code. If you change the `i` related code like I suggested above, the code should run the motors with changing speed. But also note, that this would still be a very slow change. A full run of the `timed()` function takes 4s (since the two 2s delays). With 100 steps, a full sweep from 0 to 100 will take 400s (aka 6.7 minutes) and the same time back to 0. (And this isn't accounting for the huge delays from the previous motor functions. With this you won't be able to see the change, until you wait really long time for it)
* You wrote, that you are using a 9V block battery as power source. If it is a 9V block battery, then you should know, that these batteries are not made for providing much current. They are made for low power applications. For driving motors for a longer time over battery or driving more motors at the same time, you should consider using a different battery (for example multiple AA batteries in series). As your motors currently run from it, you seem to get away with it, which is just fine. I just wanted to provide the information, in the case you reach this limit at some point.

---

All in all I can only agree with VE7JRO, that you should start with code for 1 single motor. Then, if it works like it should, you can move on and add the next motor. This will ensure, that you are getting things right early in the process and that you don't generate a big mountain of problems to cope with at once.
> 0 votes

---
Tags: arduino-mega, motor
---


# Question
Title: NodeMCU V3 Serial input results in Fatal exception 9 (LoadStoreAlignmentCause)
I am building a simple telnet style interface for experimental settings on my project. I am getting all the serial output sent to serial (and USB to PC). The code works fine, but if I try to read from Serial or check 'Serial.available()' I will get:

> Fatal exception 9(LoadStoreAlignmentCause)

Definition: `bool pridaj_cely(uint8_t source_from=0, uint8_t line_LCD=0);`

The code:

```
bool Vstup::pridaj_cely(uint8_t source_from, uint8_t line_LCD) {
  uint8_t i = 0;
  Serial.println(F("one piece input read"));
  switch (origin) {
    case 0: { //Serial
        int16_t znak = -1;
        while (Serial.available() < 0) {
          Serial.print(F("."));
          delay(100);
        }
        Serial.print(F("Somothing is comming"));
        while (Serial.available() > 0) {
          celok[i] = Serial.read();
          if (i < 12)  i++;
        }
      }
      break;
  }
  return 1;
}

```

Code of Priojenie:

```
bool pripojenie(bool force_it = 0) {
  Serial.println(("Beginning connection routine"));
  kolo = millis();
  while (!WiFi.isConnected()) {
    int8_t sieti = WiFi.scanComplete();
    Serial.printf("Search result %X", sieti);
    switch (sieti) {
      case -2:
        Serial.println(("\tSearch begins"));
        WiFi.scanNetworks(1);
        delay(50);
        break;
      case -1:
        Serial.print(("."));
        delay(300);
        break;
      default: //This is the relevant case
        Vstup odpoved;
        Serial.ciara;
        Serial.ciara;
        Serial.printf(("Found %X networks"), sieti);
        Serial.ciara;
        Serial.println();
        for (uint8_t i = 0; i < sieti; i++) {
          Serial.printf("%d: %s, Kanál:%d (%ddBm) %s\n", i, WiFi.SSID(i).c_str(), WiFi.channel(i), WiFi.RSSI(i), WiFi.encryptionType(i) == ENC_TYPE_NONE ? "Otvorena" : "");
        }
        Serial.ciara;
        Serial.println(("\nChose network number:"));
        odpoved.pridaj_cely(0);
        // -------------------Never gets past this one-------
        if ((odpoved.Nacislo10() >= 0) && (odpoved.Nacislo10() < sieti)) {
          Serial.printf(("Zadaj heslo pre %s\n"), WiFi.SSID(odpoved.Nacislo10()).c_str());
          String heslo = Serial.readString();
          Serial.print(F("Dostal som "));
          for (uint8_t i = 0; i > heslo.length(); i++) Serial.print(heslo[i]);
          Serial.println();
          Serial.printf(("Vybral som možnosť číslo %d a sieť: "), odpoved.Nacislo10(), WiFi.SSID(odpoved.Nacislo10()).c_str());
          //WiFi.begin(WiFi.SSID(odpoved.Nacislo10()).c_str(), heslo);
        } else Serial.printf(("Nesprávny výber %d"), odpoved.Nacislo10());
    }
  }
}

```

I have commented all the functions that use pins. The source compiles without any problem.

I am adding the result of exception decoder as it did not help me solve it.

```

Decoding stack results
0x40202a8d: __yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 105
0x40202355: Stream::timedRead() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Stream.cpp line 37
0x40202392: Stream::readString() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Stream.cpp line 240
0x402013b6: pripojenie(bool) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 315
0x40203411: malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/heap.cpp line 95
0x40204548: umm_malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1685
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x4020141c: pripojenie_samo(unsigned char) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 327
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x40204bb1: std::_Function_handler ::_M_invoke(std::_Any_data const&, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2073
0x4020197c: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2300
0x4020e5b8: sys_check_timeouts at core/timeouts.c line 368
0x40202957: loop_task(ETSEvent*) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 133
0x4020ac9a: __ssputs_r at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf.c line 233
0x40206938: _printf_i at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf_i.c line 194
0x4020ac9a: __ssputs_r at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf.c line 233
0x402034b4: malloc_loc(size_t, char const*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/heap.cpp line 126
0x40204548: umm_malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1685
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x40204738: umm_realloc(void*, size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1745
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x4020299c: esp_yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 91
0x40202f53: delay(unsigned long) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_wiring.cpp line 54
0x40201a89: ESP8266WiFiScanClass::scanNetworks(bool, bool, unsigned char, unsigned char*) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 98
0x40203942: uart_write(uart_t*, char const*, size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/uart.cpp line 498
0x4020299c: esp_yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 91
0x40202f53: delay(unsigned long) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_wiring.cpp line 54
0x402015fd: loop() at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 460
0x40201410: pripojenie_samo(unsigned char) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 325
0x40204bb8: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data&, std::_Any_data const&, std::_Manager_operation) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 1934
0x40204ba4: std::_Function_handler ::_M_invoke(std::_Any_data const&, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2069
0x40201e50: HardwareSerial::setDebugOutput(bool) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.cpp line 79
0x40202a4c: loop_wrapper() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 125

```

line 325 is a wrapper function because async scan can only call void function of specific type and calls pripojenie\_samo(uint8\_t pointless)

Serial Output: (after translation to English)

```
Beginning connection routine
Search result 3
-----------------------------------------------------
-----------------------------------------------------
Found  3 networks

-----------------------------------------------------

0: VM5070527, Kanál:11 (-55dBm)
1: Virgin Media, Kanál:11 (-74dBm)
2: VM5076233, Kanál:11 (-85dBm)
-----------------------------------------------------

Chose network number:
Instance cleared
one piece input read

Panic /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp:103 __yield

>>>stack>>>

```

```

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld

SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020

```

# Answer
I have figured it out There seem to be understandable limitations if what kind of function can be run as a result of asynchronous scanning (which doesn't seem to interrupt running of a loop function) So if I have used `delay(x)` or a while loop until there is input on serial, MCU resets after allotted time runs out. I have re-written code to start function from loop when scan is complete, and it all runs fine now. I guess Arduino isn't right language for parallel programing
> 1 votes

---
Tags: serial, esp8266, nodemcu
---


# Question
Title: Items needed to build an automatic watering system
I would like to build an automatic watering system. So my research brought me to the following items:

* Breadboard Solderless Prototype PCB Board – ALLDE BB-007 (3pcs) 400 Pin with 4 power Rails and Double Sided Tape
* Capacitive Soil Moisture Sensor (Operating voltage: 3.3 ~ 5.5 VDC, Output voltage: 0 ~ 3.0 VDC, Interface: PH2.54-3P)
* 1 Channel 5V Relay Module (VCC: Connect 5V Positive Pole Power Supply, GND: Connect 5V Negative Pole Power Supply)
* Mini Water Pump (DC Voltage: 3-5 V)
* Arduino UNO REV3 \[A000066\]

I am beginner in electronics so I have some very basic questions. Given the above specifications, and assuming I would like to power this system with battery and not to a power outlet, what battery do I need to power up the Arduino? I would like to have this system running for at most 30 days. The system will be running constantly until the moisture sensor indicates that watering is needed, in which case will run the mini water pump for some time (I don't know how long this will be running).

Could a battery power up this system? I am not sure if I can link products, but this system is based on this system if I forgot to include some critical information about the system.

So to summarize, is is possible to power up this system with a battery pack, if so which battery should I use?

# Answer
> 0 votes
I'd suggest feeding the system with a 12V lead-acid battery and a buck DC/DC converter with 5V output. (Those are more efficient than the regulators in Arduinos.) You could feed the regulated 5V directly into the USB port on your Arduino. You'll probably need a filtering capacitor on the Arduino 5V input to reduce fluctuations in power as the pump turns on and off however.

You'll need to do some back-of-the-envelope calculations on the power consumption of the Arduino, the on current of the water pump, the expected max duty cycle of the pump, and the efficiency of the DC/DC converter. That will let you estimate the power consumption of the whole system in mW/hr. You can then get a battery big enough to power it for your desired run-time. If you add a solar powered charging system you could increase your run-time or even make it run purely on solar power (with a big enough panel and enough bright sunshine.)

# Answer
> 0 votes
For start, I would be seriously supprised if 5 volt pump does much good and vould start from 12VDC (car or campa-van stuff...) I would be supprised if you do not have 12DC supply around (from old router, chinese gimic sliming devices, christmas light box, cable setup-box...)
Don't panic, You may be able to get relay capable of switching higher Voltages.
Second: Newer connect anything that has solenoid directly to arduino. (not even relay). Most IC's or MCU's are only able to handle opening mosfet or a transistor, only some can handle one LED. Although in the moment relay switches off, it (its induced current) will take Arduino with it. if instead you use some common cheap NPN transistor and a diode across(in opposite direction). I recommend soldering. relays and the things you power from them. last get an IP55 box from nearest electric shop.

simulate this circuit – Schematic created using CircuitLab

And lastly I would have replaced UNO for NANO here. Its much more compacr and fits easily into IP55 box For battery you van use car battery... I Find since Yuasa started destroying (buying ) competition, the lead-acids lifespan gone far down (on alarms often insufficient in a year)

---
Tags: arduino-uno
---


title: TimerOne Hanging

text:
# Question
Title: TimerOne Hanging
For the following program. Compiles and runs. I start the Serial Monitor (shown following code) and it asks me to input the Blink Rate. This runs in setup. Then it enters the loop and prints to the serial monitor the rate and starts the \>Serial.println("the bl And it hangs! I can exit the serial monitor and restart it and it does the same thing. So the program/sketch seems to be running fine but somehow the serial communication hangs? Others have tried it and it works for them? Using an Alien Aurora R5 running Win10 64bit Home. Added some delays after another person tried it and it hung on them before adding delay and then ran for them. They are using Win10 32bit and when tried on their 64bit laptop it hangs.

```
//Testing the Serial Port

#include <TimerOne.h>

int state = 0;
int value;
long int newtime;

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, state);
  Serial.println("Enter the Blink Rate: ");
}

void loop() {
  if (Serial.available()) {
    value = Serial.parseInt();
    delay(100);
    Serial.print("the blink rate is: ");
    Serial.println(value);
    Serial.println("Enter a new blink rate: ");
    newtime = value * 1000000;
    Timer1.initialize(newtime);
    Timer1.attachInterrupt(blinkme);
    delay(500);
  }
}

void blinkme() {
  state = !state;
  digitalWrite(13, state);
  delay(100);
}

```

# Answer
If you enter 1 in Serial Monitor and you have line ends selected, the Serial Monitor sends "1\r\n". parseInt() reads 1 and in next loop \r or \n is available and parses as 0. You then set the Timer to 0. The Serial can't finish printing because the Timer fires without a pause.
> 3 votes

# Answer
Change io 13 to (suggestion) 10 and attach led + 1k resister to io 10. 13 seems to be in use. Also No line end in Serial.
> 0 votes

---
Tags: arduino-uno, library, timers
---


title: Multiple Serial Ports Stream Switch

text:
# Question
Title: Multiple Serial Ports Stream Switch
I am trying to define multiple serial ports (multiple BMS management boards) and select via a global variable the port which one is active, this is the sketch I am trying to modify.

https://github.com/bres55/Smart-BMS-arduino-Reader/blob/master/smart\_bms\_reader\_Mega\_v11.ino

The function I want to write could be called "MySerialSwitch"

The smart\_bms\_reader\_Mega\_v11.ino has 19 calls to serial in a number of different functions. I want to be able to define the "active" MySerial in a variable that can be changed on the fly.

Something like this.

```
#include <SoftwareSerial.h>
SoftwareSerial MySoftSerial1(10, 11); // RX, TX
SoftwareSerial MySoftSerial2(12, 13); // RX, TX

#define MySerial1 MySoftSerial1
#define MySerial2 MySoftSerial2
#define MySerial3 Serial3

char MySerialPort[] = "MySerial1";

void setup()

{
MySoftSerial1.begin(9600);
MySoftSerial2.begin(9600);
Serial3.begin(9600);
}

```

This function would be modified

```
void call_get_cells_v()
{
  flush(); // flush first
  uint8_t data[7] = {221, 165, 4, 0, 255, 252, 119};
  MySerial.write(data, 7);
}

```

to read.

```
void call_get_cells_v()
{
  flush(); // flush first
  uint8_t data[7] = {221, 165, 4, 0, 255, 252, 119};
  MySerialSwitch.write(data, 7);
}

```

I have been researching this post

How to define a SoftwareSerial object inside a class?

And this post

Writing First Library - Serial Stream Object

It’s my first attempt at creating a library, I think this is kind of what I am trying to achieve, I've done the reading on stream, references and pointers. I'm not quite clear yet. I would really appreciate some assistance.

```
class MySerialSwitch {
    private:
        Stream *_dev;

    public:
        MySerialSwitch(Stream *dev) : _dev(dev) {}
        MySerialSwitch(Stream &dev) : _dev(&dev) {}
        (char MySerialPort);
};

    (int pos) {
    _dev->write(char MySerialPort);
}

```

# Answer
> 0 votes
I found this post, I don't think it will switch between hardware serial and software serial but it certainly works for just software.

```
#include <SoftwareSerial.h>
SoftwareSerial MySoftSerial1(10, 11); // RX, TX
SoftwareSerial MySoftSerial2(12, 13); // RX, TX
SoftwareSerial *MySerial;

void setup()
    {

   Serial.begin(115200);
   MySoftSerial1.begin(9600);
   MySoftSerial2.begin(9600);
    }

    void loop()
    {
      MySerial = &MySoftSerial1; //Query the 1st BMS
      //or change port
      MySerial = &MySoftSerial2; //Query the 2nd BMS

      // I had to all instances of MySerial.write to MySerial->write
    }

```

I'll keep reading to figure out what I've done but if anyone would like to explain, I'd be very appreciative.

This is the post I got the method from.

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

Thanks

---
Tags: serial, softwareserial, pointer, stream
---


# Question
Title: Issues with connecting to an Adafruit FLORA board
I just bought a new Adafruit Flora board, and I haven't been able to get it working successfully. When I plug it into a USB port, the board seems to be getting power (the green PWR LED is illuminated), but there is no other output from the board. The Arduino IDE also does not recognize the board (the "port" menu under "Tools" is grayed out), and I have tried to connect to it on both Windows and Linux (Ubuntu) systems with the appropriate drivers/packages installed (including the Windows drivers and the board manager add-on in both installations of the Arduino IDE). I've also verified that the USB cable I'm using can handle data.

Previously, I was able to at least get the board to be recognized in the IDE on my Linux machine, and the red LED did light up, but after disconnecting it doesn't light up anymore (unless I try to reset the board, which makes the red LED pulse a few times).

Anything that I can try to get it recognized in the IDE?

Edit: I'm able to see the board pop up under "ports" in the IDE immediately after I hit the reset button on the board. However, as soon as the red LED stops pulsing (I think this means that the board is finished rebooting), it disappears from the list of available ports. It's also mounting under /dev/ttyACM0, not the usual /dev/ttyUSB0.

# Answer
> 1 votes
Seems like whatever code was running on the Flora was corrupted. As soon as I hit the reset button, the board would momentarily pop up in the Arduino IDE, and after doing this a few times, I managed to upload the "Blink" sketch while the board was visible to my system. After that the board started working normally. It reports its name as "Adafruit FLORA" under "get board info", and the serial monitor/onboard LED work just fine.

---
Tags: serial, usb, adafruit
---


title: 16 bit PWM doesn't go to absolute 0V

text:
# Question
Title: 16 bit PWM doesn't go to absolute 0V
```
void setup() {
  Serial.begin(9600);
  setupPWM16();
}

uint16_t icr = 0xffff;

void loop() {
  analogWrite16(9, 0);
}
void setupPWM16() {
  DDRB  |= _BV(PB1) | _BV(PB2);       /* set pins as outputs */
  TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
        | _BV(WGM11);                 /* mode 14: fast PWM, TOP=ICR1 */
  TCCR1B = _BV(WGM13) | _BV(WGM12)
        | _BV(CS10);                  /* prescaler 1 */
  ICR1 = icr;                         /* TOP counter value (freeing OCR1A*/
}

/* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
void analogWrite16(uint8_t pin, uint16_t val)
{
  switch (pin) {
    case  9: OCR1A = val; break;
    case 10: OCR1B = val; break;
  }
}

```

Using the code above I can achieve 16 bit PWM signal, but when writing 0 in `analogWrite16` it output ~33mV. I know that I can set the PWM pin low but yet again it don't output 0V.

I'm guessing beside the ATMEGA offset the Arduino UNO board it self ground is raised either because it's being fed from USB or the board circuitry and PCB traces resistance. or both?

because ~33mV offset is a lot, is it normal?

How can I make Arduino to start at 0V or at least reduce that 33mV offset to 1-2mV?

# Answer
> 1 votes
You've got two possibilities:

1. You can't have full off in "non-inverting PWM" mode
2. You can't have full on in "inverting PWM" mode

In the Arduino core it's solved by turning off the PWM output and setting logical 0 or 1 for corner values.

And if you need full off but you don't need full on, you can use inverted PWM mode.

---
Tags: arduino-uno, pwm
---


# Question
Title: Measure current across shunt resistor (Power Analysis)
I am trying to reproduce the side-channel power analysis attack described in this paper: https://pdfs.semanticscholar.org/7946/a8ee82658e2ffb017270331f220a55f5ace6.pdf for educational purposes.

The attack (on the HCS3xx family of chips) requires measuring the power consumption (i.e. current) that the chip is using in order to reveal its cryptographic key.

In the paper, they describe their setup as attaching a shunt resistor in the ground path and using a digital oscilloscope (with a sampling rate greater than 1MHz) to measure the voltage drop across this resistor.

I have reproduced this setup to the best of my abilities (pictured in the schematic below), but the problem is I don't have an oscilloscope.

simulate this circuit – Schematic created using CircuitLab

Therefore, I've decided to use an Arduino Uno I have lying around as a poor man's oscilloscope.

Besides the fact that the Arduino ADC has a *much* lower sampling rate (~77KHz vs. the ideal 20MHz described in the paper), I have been having an issue getting a reliable voltage reading across the shunt.

While trying to use the full 10-bit ADC, and producing samples as `(ADCH << 8) | ADCL` in my ADC ISR, I do not get any samples that are greater than 0.

However, when I left-align the ADC to only use 8-bit precision (with `ADMUX |= 1 << ADLAR` and read with just `ADCH`, I get non-zero values but none with a value greater than one.

Could it be that the amount of power that the chip consumes is so small that the Arduino does not have enough precision to read it? Or could it be that my shunt has too large of a resistance and is causing a reduced current throughout the circuit?

# Answer
> 1 votes
In the graphs they've got `2.5mA` tops, so you've got about `2mV` on that `1.2R` shunt resistor.

And Uno's default ADC reference is `5V` divided into `1024` steps each of them roughly `5mV`. That's more than peak value of measured voltage.

And with such small sampling frequency you won't be even able to spot fast changes as you'll be measuring much slower that it needs to be.

ADC step precision can be better by using internal 1V1 reference, but it's still way too big step. And there is no other option on UNO. The Mega on the other side has also possibility to configure diferential ADC inputs and with 1x, 20x or 200x gain. But it's not supported by Arduino core, so you'll have to do it directly. However it won't help much if it's sampling too slow.

---
Tags: arduino-uno, power, current, adc
---


title: How to stop loop in the serial monitor?

text:
# Question
Title: How to stop loop in the serial monitor?
I want to make a serial program with input from the serial monitor and show each character with its binary and ASCII codes.

At the end of the program, I want to show the whole message sent from the serial monitor but I don't know how to stop the loop. Can someone help me please?

Here's my program:

```
String dataST;

void setup() {
  Serial.begin(9600);
  Serial.println("Message sent by serial monitor : ");
}

void loop() {
  for (int i = 0; i < 400 ; i++) {
    if (Serial.available()) {
      char dataOK = Serial.read();
      dataST += dataOK;
      Serial.print(dataOK);
      Serial.print(" = ");
      delay(200);
      for (int i = 7; i >= 0; i--) {
        byte bytes = bitRead(dataOK, i);
        Serial.print(bytes, BIN);
      }
      Serial.print(" = ");
      int dataAS = dataOK;
      Serial.print(dataAS);
      Serial.println(" ");
      Serial.println(" ");
    }
  }
  Serial.println("Message : ");
  Serial.print(dataST);
  dataST = "";
}

```

The result from the program above is:

```
Message sent by serial monitor :
Message :
Message :
Message :

```

And the result I want is:

```
Message sent by serial monitor:
H = 01001000 = 72

e = 01100101 = 101

y = 01111001 = 121

Message :
Hey

```

Please help me.

# Answer
Please take a look at the documentation of SerialEvent.

This might be exactly what you are looking for (after several small tweaks)

Code from the example:

```
/*
  Serial Event example

  When new serial data arrives, this sketch adds it to a String.
  When a newline is received, the loop prints the string and clears it.

  A good test for this is to try it with a GPS receiver that sends out
  NMEA 0183 sentences.

  NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or
  other ATmega32U4 based boards.

  created 9 May 2011
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/SerialEvent
*/

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

void loop() {
  // print the string when a newline arrives:
  if (stringComplete) {
    Serial.println(inputString);
    // clear the string:
    inputString = "";
    stringComplete = false;
  }
}

/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

```
> 1 votes

# Answer
An embedded system is never meant to stop. If/when your `loop()` function exits (returns), it will be immediately called again.

If you need a process that runs to some state of completion and than stops, you're better off to leave `loop()` empty and write your own function that does what you need it to do, and call it at the end of `setup()`.

You can either put an infinite loop at the bottom of your function:

```
for(;;);

```

is one way to do it, or just let it return to setup(). Then `setup()` will exit, your empty `loop()` function will be called (infinitely), which accomplishes the same thing.
> 0 votes

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


# Question
Title: What would cause a delay when using serial between the Arduino IDE & external clients?
I have been working on a problem for a couple of days that I can't figure out.

I am using a Teensy3.6 with Arduino IDE to build a CAN Bus monitor for a car. For those familiar, I am trying to save the data in the format of can-utils so it can be easily replayed on Linux machines. The board uses the FlexCAN library to facilitate communication.

Everything works well using the Arduino Serial Monitor. However, I want to save the output to a host computer. Unfortunately, I've not been able to get any other serial programs to work. I have tried PuTTY & Python via PySerial. The output seems to get interrupted & doesn't print on a new line correctly.

Sample Output from Arduino Serial Monitor:

```
(1302.864746) can0 1C5#2C032C032E01
(1302.864868) can0 1F4#000000000000
(1302.865356) can0 287#0000
(1302.865601) can0 F1#340000400000
(1302.865845) can0 96#BFF00A120000
(1302.866455) can0 97#35800A1518300A0A
(1302.866821) can0 98#00000A0080000A13
(1302.867065) can0 1E5#4400335000000103
(1302.867554) can0 C7#00000000
(1302.867798) can0 1E9#FF8300EFFC0000
(1302.868042) can0 232#0000000000000000
(1302.868652) can0 1E1#00000000001CC0
(1302.868896) can0 2F9#83000000000007
(1302.869019) can0 222#001607AD0C00
(1302.869629) can0 BC#A11E005C00000000
(1302.869751) can0 D3#2C02
(1302.869995) can0 186#44005D0000017C
(1302.870483) can0 224#CBC8C8
(1302.870605) can0 228#005B5F5B
(1302.870850) can0 1F3#80BC00
(1302.871460) can0 B9#000A800002000000

```

Output from PuTTY/PySerial:

```
(1443.927002) can0 C1#10026B0210037D86
(1443.927246) can0 C5#10026B0310026B02
(1443.927490) can0 D1#40007FFF00FF00
(1443.927856) can0 1EB#0241(1444.011230) can0 AA#2C032C030253FC00
(1444.011597) can0 C9#8000002000101800
(1444.012085) can0 1E7#019000000000316D
(1444.012329) can0 1ED#019000000000316D
(1444.012451) can0 34A#000000001B
(1444.012939) can0 1EF#00000000

```

My naive opinion is it seems the CAN data comes faster than the serial is writing. However, it's odd that it works fine in the Arduino IDE. It happens about 1x/second--which is well enough to cause a headache.

Outside of SD cards or writing locally--does anyone know why this might happen? Or how I could save this data to a host computer? Worst case I can copy/paste the output from the Arduino Serial Monitor, but that isn't very elegant.

Thank you!

Edit: Here is some relevant code from my Arduino IDE. I modified the object oriented can example from flexcan to print in my desired format.

```
#include <FlexCAN.h>
static CAN_message_t msg;
elapsedMicros sinceStart;

class CANHandler : public CANListener{
  void printFrame(CAN_message_t &frame);
  void gotFrame(CAN_message_t &frame, int mailbox); //overrides the parent version so we can actually do something
};

void CANHandler::printFrame(CAN_message_t &frame){
   Serial.print("("); Serial.print(sinceStart / 1000.0 / 1000.0, 6);
   Serial.print(") "); //cast to 6 decimals to make compatible with can-utils
   Serial.print("can0 "); // to identify a CAN channel for can-utils
   Serial.print(frame.id, HEX);
   Serial.print("#");
   for ( uint8_t i = 0; i < frame.len; i++ ) {
     if(frame.buf[i] < 15){
        Serial.print("0"); Serial.print(frame.buf[i], HEX);
     } else {
        Serial.print(frame.buf[i], HEX);
     }
 }
 Serial.println();
}

void CANHandler::gotFrame(CAN_message_t &frame, int mailbox){
printFrame(frame);
}

CANHandler canHandler;

void setup() {
    Serial.begin(115200);
    Can0.begin(500000);
    Can0.attachObj(&canHandler);
    CanHandler.attachGeneralHandler();
}

void loop() {
//run until exit
}

```

# Answer
> 0 votes
If your data input rate is higher than, or even close to, your serial output rate (baudRate/10 char/s), your system will be unable to keep up.

With an interrupt driven system, make sure your interrupt function executes and returns as quickly as possible, i.e., does as little as needed to not lose data. Let the background process (the main sketch code) deal with the incoming data as it appears. Make sure the both processes are short enough to deal with the worst-case input-data bursts without losing any. For the background process, use as high a baud rate as it is capable of - and as it's downstream neighbor (Storage device? Another MCU or PC?) is capable of - keeping up with.

---
Tags: serial, arduino-ide, teensy, can-bus
---