message:
LCD write a line at bottom without lcd.setCursor and without deleting any char above already there?

lcd.cursor and lcd.noCursor won't work for what I want to use it for since it seemed to be "global" sort of speak and follow lcd.setCursor which I don't want it to but it is otherwise exactly what I want to be done; just to put a line at the very bottom and also remove the line whenever I want to but without removing the entire char above.

Just like lcd.cursor do but as said it won't work in the code since the line has to reside where it is even if lcd.setCursor is used elsewhere but then the cursor line follow to that other point which I don't want and such a controllable cursor that sits at the place even if lcd.setCursor is used elsewhere. But the char there first and then the line of vice versa doesn't matter just as long as there it a line. And I cant create custom chars with a line under them since its numbers from 0 - 9 and so many custom chars can't be made.

It's fully possible to write to the bottom row though and I thought it would be possible to do something with lcd.createChar by not no write anything at all at the bytes rows but the lowest one, but that surprisingly failed. This is what I tested:

    byte line[8] = {

      B,
      B,
      B,
      B,
      B,
      B,
      B,
      B11111,
    };

And that writes on the lowest row as expected, but strangely enough STILL deletes any char that is written above even if nothing should have been written there as I see it.

The test here put out pretty much garbage and pretty much delete the char written but something still remain but the line is written at top instead of bottom and I guess it all goes out of the normal bounds in the registry or something:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(40, 42, 28, 26, 24, 22);

    byte line[1] = {

      B00000,
    };

    byte noline[1] = {

      B11111,
    };

    byte sure[8] = {   //It didn't like to use "square" as name by whatever the reason

      B00000,
      B00000,
      B01110,
      B01110,
      B01110,
      B01110,
      B00000,
      B00000,
    };

    void setup() {

      lcd.createChar(0, line);
      lcd.createChar(1, noline);
      lcd.createChar(2, sure);

      lcd.begin(20, 4);
      lcd:clear:
    }

    void loop() {

      delay(500);
      lcd.setCursor(0, 0);
      lcd.write(byte(2));
      delay(500);
      lcd.setCursor(0, 0);
      lcd.write(byte(1));
      delay(500);
      lcd.setCursor(0, 0);
      lcd.write(byte(0));

    }

Any tips on how to do the same with create.Char or any other simple way? I mean the lcd.cursor and lcd.noCursor can do it, how do that do it then? It's an ordinary 20X4 LCD if that would matter.

body:
I do not really understand what you mean by your first sentence. Did you succeed in getting a "hardware" cursor to display together with a character or not? And if you do, why doesn't this fulfill your requirements?

You have to realize that your LCD cannot display partial characters, like a line at the bottom, leaving the rest of the character that was already there intact. An exception is a hardware generated cursor.

You also have to realize that createChar always expects a full character with 8 rows.

**Your code examples**

In your first example, starting with `byte line[8] = {`, the first 7 "empty" `B,` lines actually produce a value of (binary) zero. So here you create an empty character with a line at the bottom, exactly like you said you see on the display.

In your second piece of code, you define characters `byte line[1] =` and `byte noline[1] =` consisting of just 1 byte. createChar expects 8 bytes. createChar will fill the characters with the single byte defined in your character definition, plus whatever it finds in the 7 memory locations following your actual definition (which will probably contain some random data). This explains the "garbage" you see on the screen.

**Possible solution**

One solution would be to re-create each character you want your cursor to display under, on the fly. I.e. if you want your cursor to be displayed under the letter "A", you create a complete custom character which contains "A", plus a cursor underneath and you display it in place of the real "A" at this location. When you move the cursor, you replace the "custom" A with the real "A" again.

This will be cumbersome in code complexity as well as code size (you'd have to create a complete character map for every character you wish to display), but should be a feasible solution.


sender: user

message:
DC Motor doesn't turn and a beep sound is made, also there is a burning smell

I was trying to drive a single dc motor with L293D Shield and Arduino Uno

~~~c
#include <AFMotor.h>
#include <SoftwareSerial.h>

AF_DCMotor motorLeft(3);
AF_DCMotor motorRight(2);

unsigned char opMode = 0;

void setup()
{

}

void loop()
{
motorLeft.setSpeed(30);
motorLeft.run(FORWARD);
delay(5000);
motorLeft.setSpeed(0);
motorLeft.run(RELEASE);
delay(5000);
}
~~~

When I turned the power on, a beep sound was made continously. As I was trying to figure out where the sound comes from, I smelled something burning and turned the power off.

I am giving 6V (Four 1.5V  batteries in series) as external power. Burning smell doesn't come from batteries, that's for sure.

The smell comes from arduino or shield or both. But I think it is the the left LM293D driver.

What did I do wrong? Any idea?

sender: assistant

body: Alright, I finally realized that RPM value was too low. It has to be at least 150 for my case.


message:
Hooking Up 8 ohm Speaker to Arduino

Is this a correct way to connect an 8 ohm beaker to an Arduino?

https://www.c-sharpcorner.com/article/audio-play-using-sd-card-module-and-arduino/

body:
To effectively drive a speaker from an Arduino you need an amplifier. The good ol' LM386 is a common choice for this (readily available and cheap, though not recommended for battery based projects).

While it is *possible* to drive a speaker directly it's not recommended. Not only is it very quiet, but also it can damage the IO pin. Not only from excess current draw (peak current at 5V through 8Ω [nominal] is 626mA,  more than 15x the maximum the pin can supply, which not only stresses the pin but also distorts the output waveform) but a speaker is also an inductive load which has all the associated issues of back-EMF and such.


message:
595 Shift Register Not Working Properly

I followed the tutorial on controlling 8 LEDs using a SIPO SN74HC595N shift register on both [Adafruit][1] and [Last Minute Engineer][2]. I used a Sparkfun Pro Micro (Arduino Leonardo equivalent).

The problem is the LEDs are not lighting up in the way that I'm expecting it do it. Both guides said each LED will light up one after another. After all 8 are lit, all of them will turn off. [Here is my result][3]. Other LEDs will either dim up or down as the target LED turn on. I used the code provided from the guide and only changed the pinout number. The resistor values are the same for each color so it can't be the resistor. Anyone have any idea what's going on here?

    /*
    Test code for 74HC595N SIPO shift register. Used with Pro Micro
    */

    int latchPin = 16;
    int clockPin = 15;
    int dataPin = 14;
    int outputEnablePin = 10;

    byte leds = 0;    // Variable to hold the pattern of which LEDs are currently turned on or off

    void setup()
    {
      // Set all the pins of 74HC595 as OUTPUT
      pinMode(latchPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(outputEnablePin, OUTPUT);
      outputEnablePin = LOW;
    }

    /*
     * loop() - this function runs over and over again
     */
    void loop()
    {
      leds = 0; // Initially turns all the LEDs off, by giving the variable 'leds' the value 0
      updateShiftRegister();
      delay(500);
      for (int i = 0; i < 8; i++) // Turn all the LEDs ON one by one.
      {
        bitSet(leds, i);    // Set the bit that controls that LED in the variable 'leds'
        updateShiftRegister();
        delay(500);
      }
    }

    /*
     * updateShiftRegister() - This function sets the latchPin to low, then calls the Arduino function 'shiftOut' to shift out contents of variable 'leds' in the shift register before putting the 'latchPin' high again.
     */
    void updateShiftRegister()
    {
       digitalWrite(latchPin, LOW);
       shiftOut(dataPin, clockPin, LSBFIRST, leds);
       digitalWrite(latchPin, HIGH);
    }

**Schematics:**

[![enter image description here][5]][5]

  [1]: https://learn.adafruit.com/adafruit-arduino-lesson-4-eight-leds/overview
  [2]: https://lastminuteengineers.com/74hc595-shift-register-arduino-tutorial/
  [3]: https://gph.is/g/Z2mPdPW
  [4]: https://gph.is/g/aXJBj6R
  [5]: https://i.stack.imgur.com/Vs1Kr.jpg

body:
The dimming problem was found to be the shift register IC not connected to Ground (dumb me).

However, there is still problem with LED's on and off pattern. Sometimes two LEDs turn on at the same time and all previous LEDS turning off before the last or second last LED is turned on. It turns out Pin 10 (SRCLR Bar) needs to be pulled to high to solve that pattern discrepancy.


message:
Making Cases for Projects

I've been messing around with arduinos and other microcontrollers for around a year now and I've always struggled to find ways to encase my projects. I've seen some people use custom PCBs and then 3D print a case for that.  How would one go about that? I am only a computer science student so I know nothing about electrical circuitry.
For example, lets say I have a UltraSonic Sensor that uses a Arduino nano to light an LED. How would I transfer that to a single PCB? And are there websites where I can order custom 3D printed cases for my projects?
Please let me know if you need me to make my question clearer. Thank you!

body:
Your question has multiple layers:

1. **The custom PCB:** Breadboards are good for experimenting, but not for a finalized circuit. Depending on some factors you can decide between multiple options. One, that I myself often use, is soldering the parts onto a perfboard. That are cheap PCBs, where - depending on the type - you have a grid of single through-hole solder pads or connected groups of through-hole solder pads. I like to use these:

    [![perfboard with conveniently connected pads][1]][1]

    The pads are connected nearly like a breadboard, so it is easy to use with Arduinos and such. You can build your circuit on there by soldering the parts to it, and make the PCB the right size by cutting it into the needed size.

    A more professional option is to buy real custom PCBs. You need to create the PCB layout on your PC (common programs are Eagle or Kicad, though there are many others). Then you can choose the PCB manufacturer of your trust and give them your layout files. They will manufacture the PCBs and send them to you. This options costs a bit money (though not a lot) and you will have to wait for the PCBs to arrive.

2. **The casing:** There are many options to choose from:
    - You can buy a generic case somewhere (hardware store, or the internet shop of your trust). Then you can work on it to fit your purpose (drilling holes for the LEDs, using screws or glue to fix your PCB, ...)
    - There are some standard cases to buy, though most of them most likely don't fit you good, since they are made for special industrial purposes.
    - You can create a custom 3D printed case. For this you first need to design the case on your PC (a common program is Fusion360, though I'm using FreeCAD). For the actual printing you can either use your own 3D printer, or you can again find a good 3D printing service, that you can give your design file (commonly in the `stl` format). They will print it for you for a bit of money. You will have to choose between different manufacturing methods, mainly FDM (putting lines of molten plastic onto each other layer after layer) or Resin printing (curing layers of fluid resin one after another). FDM is still cheaper. And you need to decide on the material (PLA is common, others are ABS or even metal (though the last is expensive). Also you need to design your case in a way, that it is good printable with the chosen method. You need to read more about 3D printing elsewhere (there are tons of material about it on the web).

One rule of this site is to not give product recommendations. That's not, what the site is for, and they are pretty fast outdated. Instead you need to do the research yourself.

  [1]: https://i.stack.imgur.com/zoXc2.jpg


message:
TX, RX, ON, L LEDs were red at all time

Before seeing this error I did a project with my Uno board using a Bluetooth module.

After that, when I powered the board to upload another program, 4 LEDs (L, TX, RX, ON) went red without blinking.

So now, every time when I power up my Uno board, without any connection with any of the pins previously mentioned, the 4 LEDs are red coloured all the time.

body: If you can upload sketches, I don't think it is that big of a deal but if you can't, check the TX and RX pin tracks since if those tracks are shorted, they can keep the indicator lights on for ever due to the Serial code on the Arduino. To get further help, please tell me what happens if you try uploading code.


message:
How to change wifi credentials of multiple ESP8266 together

I need to change WiFi credentials of multiple ESP8266 in one go, without needing to change passwords for each of them individually. I know there is a WiFiManager library, which makes your ESP8266 access point when not connected to any network, but that will require me configure each of them individually.

How can I save the fatigue of changing their wifi credentials individually? All of them needs to connect to the same network, whose password is recently changed.

body: Have your devices always try to download a config file from a webserver you control.  If the config file exists and has new wifi credentials then it can update itself and reset.  When you actually change the password for the AP all the devices will already have the new password.


body:
you can reconfigure your router, or whatever network mode you are using, with auto-login to the MAC addresses of your ESPs.

And then if you provide the MACs of the corresponding ESPs, and change your WiFi credentials, then you don't need to configure the ESPs individually. It will auto-connect itself.


message:
Check if the board is in sleep mode

I'm using seep sleep mode with UNO with a simple sketch that turning on an LED and then goes to sleep. as far as the ATmega328p datasheet in sleep mode part showing the wake up sources and deactivated clock sources in deep sleep mode and the I/O clock becomes deactivate so we expect when the board goes to sleep the LED should become off because of no clock. but it doesn't happen and LED keeps ON in sleep mode. what is the problem?7 and how can we even find out that the board is on sleep mode or not?[![enter image description here][1]][1]

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/6GTrK.png
  [2]: https://i.stack.imgur.com/KLhEv.png

body:
The IO doesn't require the clock to keep its current state. It only requires it to change state.

There is no real external signal provided by the chip to indicate if its in sleep mode or not. However you could monitor the current consumption of the chip and when it drops below a certain threshold you can assume that it is in sleep mode.


body:
You could easily set the LED output LOW just before you call going_to_sleep(), and set it HIGH when going_to_sleep() returns. There would be two short periods where the LED signal would indicate sleeping but the processor is running:

 1. between the LED going LOW and the processor actually entering sleep; and
 2. between the processor waking and the LED going HIGH.

But at these times the processor could not respond to your external system anyway.


message:
L293D to change the direction current and amplify it - Temperature-Stabilizer

I have a question about my project. I'm going to make a temperature-stabilizer. To make this, I think I should use a TEC with a H-bridge and a LM35. First of all, I tried to make a H-bridge by myself, I have only used four NPN transistors and It didn't go well. Then I bought L293D motor driver - not the module one, tried it and it works well. But as datasheet says, it's output current is max 600mA. But this current doesn't make TEC work efficiently. So that, I need to amplify the current. But I don't want to buy high amp motor drivers, hardwares are to expensive in my city. Of course I'll if there's no another way.

Arduino will be used to get temperature values from LM35 and give the H-bridge voltage, control the current direction when necessary. I learned how to use transistors to amplify but if I'll change the direction, it won't work. But I don't know how to make this circuit.

**The algorithm that I thought using is this:**

[![Algorithm of Temperature Stabilizer for +-3*C degree][1]][1]

**The scheme that I thought using in this:**

[![The scheme that I thought using in this.][2]][2]

What should I do to solve my problem? Thank you for all.

**Resources:**

 1. My Tec1-12706 Datasheet:
    http://www.thermonamic.com/TEC1-12706-English.pdf
 2. LM35 Datasheet - (I have LP package):
    https://www.ti.com/lit/ds/symlink/lm35.pdf
 3. L293D Datasheet: https://www.ti.com/lit/ds/symlink/l293.pdf
 4. The transistor method to amplify:
    https://www.youtube.com/watch?v=WZD9RZoMhVE

  [1]: https://i.stack.imgur.com/fqb7c.png
  [2]: https://i.stack.imgur.com/aNoDu.png

body: I am interested on this as I have the same issue. What about using a FET or MOSFET to amplify the current that the LM293D provides?


message:
Digital to Analog converter with DAC5311, Any suggestion?

I made my DAC code with DAC5311 and Arduino Uno.
I think it has no problem, but it doesn't work well. Just print 0.(I use an oscilloscope.)
I don't know where has the problem. Please give me any suggestion.

    #include <SPI.h>
    #include <math.h>
    #define pin_CS 10
    #define pin_MOSI 11
    #define pin_SCLK 13
    #define max_VOLT 5

    void setVoltage(float voltage){
      if (voltage < 0) voltage = 0;
      if (voltage > max_VOLT) voltage = max_VOLT;
      uint16_t temp = int(voltage * pow(2, 8) / max_VOLT);
      temp = temp << 6;
      uint8_t upper = temp >> 8;
      uint8_t lower = (temp & 0xff);
      digitalWrite(pin_CS, LOW);
      SPI.transfer(upper);
      SPI.transfer(lower);
      digitalWrite(pin_CS, HIGH);
    }

    void setup() {
      Serial.begin(9600);
      pinMode(pin_CS, OUTPUT);
      pinMode(pin_MOSI, OUTPUT);
      pinMode(pin_SCLK, OUTPUT);
      SPI.begin();
      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE0);
      digitalWrite(pin_CS, HIGH);
    }

    void loop() {
      setVoltage(5);
      delay(10);
    }

body:
Classical +/- 1 problem

If you do this calculation by hand `uint16_t temp = int(voltage * pow(2, 8) / max_VOLT);`
you will get `temp=256` and this is a value you can not convert with a 8 bit DAC.

Try `uint16_t temp = int(voltage * (pow(2, 8)-1) / max_VOLT);` instead.

(or event better for a µC `uint16_t temp = (uint16_t) (voltage * (255 / max_VOLT));`)


message:
How to use attachInterrupt() in ATtiny85 with Arduino IDE?

It's possible use external interrupts/attachInterrupt() with the ATtiny85 when I program with Arduino IDE?

If is possible, how many inputs (for external interrupts) the ATtiny85 have and which are they?
Someone have an example code?

body:
Pin PB2 is the only pin that has a real external interrupt.  This is `INT0`.

Whether you can use `attachInterrupt(0, ...)` or not is entirely down to whether it is implemented in the core that you are using.


message:
Http request in interrupt esp8266 not working

So i have this code that whenever i click a button a interrupt starts.
In this interrupt i want to do a get request to a webserver.

The thing is seperate the code, the interrupt code works and without an interrupt the http request also works.
But when i put this together it doesn't.

Does anybody have an idea why this doesn't work?

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

char ssid[] = "";
char pass[] = "";

int ledpin = 5; // D1(gpio5)
int button = 4; //D2(gpio4)
int buttonState=0;

ICACHE_RAM_ATTR void ISR() {
  static unsigned long last_interrupt_time = 0;
  unsigned long interrupt_time = millis();

  if (interrupt_time - last_interrupt_time > 200)
  {
      Serial.println("Drukknop ingedruk");
      Serial.println("Sending message to server");
       if (WiFi.status()==WL_CONNECTED)
      {
        HTTPClient http;
        String url="<httpurl>";
        http.begin(url);
        http.addHeader("Content-Type","text/plain");
        int httpCode=http.GET();
        Serial.println(httpCode);
        String payload=http.getString();
        Serial.println("While sending I received this from server : "+payload);
        http.end();
      }
      else
      {
        Serial.println("Internet Problem!");
      }
  }
  last_interrupt_time = interrupt_time;
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid,pass);

  while(WiFi.status() !=WL_CONNECTED)
  {
    delay(500);
    Serial.println("Waiting for connection");
  }

  Serial.println("Connected...");
  delay(1000);
  if (WiFi.status() ==WL_CONNECTED)
  {
    Serial.println("Wi-Fi Connected!");
  }
  delay(5000);
  Serial.println("ok");
  pinMode(button, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), ISR, RISING);

}
void loop() {

}
```

body: Doing something as complex as a HTTP request in an interrupt is a very very silly idea. Instead set a flag in the interrupt routine and examine that in the main `loop()` function to perform your HTTP request.


message:
How to connect naked camera from mobile phone to Arduino Uno

Okay, guys. I have this 3 cameras(middle from the iPhone 6s, 2 at the side I found, and I think there are from modern phone). **I need some information how to connect Arduino Uno to them.** I know c/c++, assembler, but noob in microcontrollers, if this knowledge can come useful.[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/Dkf1O.jpg

body:
You need either a memory extension for your UNO - projects like Arducam did this way back 2016 and then used an OV2640 module. If you want to develop something yourself these are the steps (hurdles) to take:

 - Get a datasheet of the camera
 - Design a circuit including
   - plug for Camera and a
   - memory module (min 512Kb)
 - Attach it to the UNO
 - Write a library/function module (see datasheet for details) and
 - bring it to life

My tip save ca. two years of your life and get for 6-8$ an ESP32cam<br>
This will cost you enough of your time, but be much more rewarding


message:
Calculating SpO2 using pulse sensor

I was wondering is there a way to calculate SpO2 using a pulse sensor?
I calculated BPM and stress before with pulse sensor and now I want to calculate SpO2.

Link to Pulse sensor [manual][1]

  [1]: https://www.generationrobots.com/media/DetecteurDePoulsAmplifie/PulseSensorAmpedGettingStartedGuide.pdf

body:
For measuring oxygen saturation (SpO2) with a pulse sensor, you need to use the fact, that hemoglobin, that carries oxygen, will reflect in different light wave lengths, as hemoglobin, which doesn't carry oxygen. But that also means, that you need to use light in at least 2 different wavelengths. Common are one red (about 660nm)(though green may also work) and infrared (about 940nm). When lighted sequentially with both LEDs, you can measure the refection of both parts and calculate the ratio between them (SpO2).

But your sensor only has 1 LED, which is green. So you cannot measure SpO2 with this sensor. You need one fitting the above description.


message:
char to String conversion in Arduino program

I have started learning about Arduino and am well versed in Java and Python. In an Arduino program, I need a character input via Serial to be stored in a String variable. From my previous programming experience, I knew that a code like the one below would give an error as char can't be converted into String like this.

```
void loop() {
  if(Serial.available()) {
     String s=(char)Serial.read();
  }
}
```

As expected, the above code gives an error on compiling. But when I first defined `s` and then assigned its value in a separate step in `void loop()`, I got no error.

```
void loop() {
  if(Serial.available()) {
     String s;
     s=(char)Serial.read();
  }
}
```

The above code yields no error despite the fact that it is almost similar to the first code. What I suspect is that it has something to do with String being a class. Can one tell what is going on?

body:
I don't have much experience with Arduino's `String` type, however, most people (including myself) don't advise to use it. Because the Arduino only has 1 KB of SRAM and the `String` type has its own hidden memory allocation, you might run out of memory without you know it, resulting in crashing/frozen programs without a clue what is happening.

Instead use character arrays (like `char str[10]`) where you know exactly what is reserved.

However, to answer your question, what I expect since `String` is a class, there is a (copy) constructor in that class that takes a `char` and converts it into a `String`.


body:
this isn't an arduino specific error what you're trying to do is declare and initialize the variable in one statement which is causing the problem. As you've figured it out already. Declaring the variable first
```
String s;

```
and initializing it another statement does the job for you
```
s=blabla
```

Hope this helps. PS, try posting the error that you get during build process next time :)

**EDIT**:
 I think this needs more explanation. Basically why you cant declare and initialize at the same time in this case is because Serial.read is a synchronous request. Declaring an object requires acquiring the space for it, running any constructors and whatsoever, and doing while Serial.read() is an IO blocking operation. You could declare and initialize a String class variable given it was a string constant but not with anything like get_input or Serial.read

**EDIT 2**:
Further here's what I've found for you.

http://www.cplusplus.com/reference/string/string/string/

Apparently the  String class has a copy constructor which means when declaring the variable you initialize at the same time it uses the copy constructor, and which requires ADDRESS to a valid string(know that you can use a constant because C++ deals with all strings as the address to their first char). In your case the constructor raised an error because you pointed it to an undefined(Serial.read() ).
```
String mystring=Serial.read(); //error, uses copy constructor
```
However this would work
```
String mystring="hey juliet!" ; //uses the copy contructor which takes address to a char

```
Doing the same thing in two different lines works for the same reasons, it uses a different constructor

```
String mystring; //uses empty string constructor - okay so far
mystring=Serial.read(); // uses the overloaded = operator  --okay

```


body:
You misunderstand `Serial.read()`: it does not return a `String` or sth. like a char array, but an integer, representing only the last byte in the input buffer that hasn't been read.

What you probably want to do is to interpret those incoming bytes as `char`s and accumulate those in a `String`.

E.g. like this:

    String s="";
    while(Serial.available()) {
      // as long as there are bytes in the buffer
      s+=(char)Serial.read(); // interpret int as char and append character to s
    }

As using `String` can easily lead to crashes you should avoid dynamic memory allocation by using a fixed-size char arrays:

    #define MAX_LEN 64
    char s[MAX_LEN];
    uint8_t i;
    while (serial.available() && i<MAX_LEN) {
      s[i]=(char) Serial.read();
      i++;
    }

Note: once you are that far you still have to handle, when you want the data to be ready to process (e.g. detecting a `\n` and setting a flag appropriately).


body:
This will fix the problem:
`void loop() {
  if(Serial.available()) {
     String s=(char*)Serial.read();
  }
}`
This is because in C: Strings are defined as an array of characters.
You cannot assign a primitive to an array...

I guess the casting into pointer can be implicit as in your second example..


message:
Arduino Nano use SPI pins as I/O pins? and still be able to do ISP?

I wonder if can use the Arduino Nano SPI-pins(MOSI,MISO & SCK) as I/O pins in a sketch? and still be able to program over ISP?

Of course I will physical disconnect the Arduino from any other hardware before programming.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/z4yAP.png

body:
Yes, you can use SPI in your sketch just as you like. The programming over ISP is triggered by resetting the microcontroller. That means, that when trying to program over ISP your sketch (which configures the SPI hardware for use) doesn't run. The programming is starting at a stage, before the sketch runs, thus the sketch cannot interfere.

By the way: The same is correct for programming over Serial, though for a different reason. Programming over Serial is done by the bootloader, which runs before your sketch.


message:
No contact between DS18B20 and WeMos D1 Mini

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

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

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

Can anyone please help me with the following sketch?

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

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

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

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

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

float celsius = 0;

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

  // Connect to sensors
  sensor.begin();

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

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

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

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

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

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

void loop() {
}
```

body:
//Call this function after sensor begin in setup.. share output

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

      uint8_t address[8];
      uint8_t count = 0;

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

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

      return count;
    }


body:
And for the stability (**Read the comments**) of your solution (Change anyway!) instead of

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

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

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


message:
NodeMCU unable to connect to mobile hotspot when I include codes for reading the temperature sensor

Good day.

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

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

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

Thanks!

PS:  i attached my codes here
```
#include <ESP8266WiFi.h>
#include <WifiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

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

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

body:
Get rid of the delay - this **STOPS** processing for five seconds, not really what you want in a wifi scenario - some routers might disconnect you in this time if no pingbackis are coming
If you need a 5 second- non blocking break for your routines look at this example
ArduinoIDE -> examples -> 2 Digital -> blinkwithoutdelay.

For further assistance copy and paste your code in code tags and not as a picture.


message:
How to set a timer for a function and be able to reset it in the middle of the process?

Hello me and my friend have to do an assignment for school but we need some help. We have to make a LED turn on and of with a button and a relay. But when I press the button the LED should be on for 10 minutes and then go off unless we press the button inside those 10 minutes then the LED should turn off. Then repeat this process when we press the button again.

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

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

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

    }

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

Read the comments in the code:

    #define btn 5
    #define rly 6

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

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

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

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

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

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

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


message:
Soil moisture sensor, weird readings

I'm  having a small problem with my soil moisture sensor

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

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

(the output voltage is read on an ESP32, almost visible in the bottom of the image)
[![enter image description here][1]][1]

[![][2]][2]

  [1]: https://i.stack.imgur.com/qH0BH.png
  [2]: https://i.stack.imgur.com/TFdYG.jpg

body:
It looks like you're trying to measure the resistance of soil by connecting an ADC input through the soil to VCC.  That is not the way to to it.

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

![schematic](https://i.stack.imgur.com/GxgKl.png)

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

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

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

![schematic](https://i.stack.imgur.com/Dpdjl.png)

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

----

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


message:
I have a question,an error occured in my code saying TIMSK was not declared in the scope(There are no errors)

#include <SmartInventor.h>

    void setup() {
      SmartInventor.DCMotorUse();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    }

body:
The SmartInventor library is to be used with the Rokit Smart board. That board is based around the ATMega32.

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


message:
Boolean variable with if statement

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

Here is the code:

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

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

    void loop() {

      x++;

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

    }

body:
I asked this question to be moved to Stackoverflow as it is not Arduino related.

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

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

    int x = 0;
    boolean state1;
    boolean state2;

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

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

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

    int x = 0;
    boolean state;

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

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

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

    int x = 0;

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

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

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


message:
CIPSEND to ESP8266 returning bytes but no content

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

    #include <SoftwareSerial.h>

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

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

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

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

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

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

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

    AT+CIPSEND=61

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

    busy s...
    Recv 61 bytes
    SEND OK

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

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

-----edit-----

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

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

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

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

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


message:
AVR & PIC 8-bit Microcontrollers - Can you add: external flash memory, external RAM, video & audio output, more address busses?

so I was planning on creating a mini PC out of basic ICs and 8-bit microcontrollers such as ATTinys and/or PICs and I have several questions regarding those:

 1. Can you add external RAM, say with SRAM, DRAM chips, so the microcontroller can handle larger programs? (ones requiring more memory to be executed). I've seen an excellent discussion here: https://arduino.stackexchange.com/questions/45870/external-flash-memory-for-attiny85, which exclaims that **I can't** do that with AVRs (but why exactly is that? What about PICs, or any 8-bit uCs for that matter).
 2. Can you add external memory, like flash or EEPROM, so that the microcontroller can store some files (sort of a hard drive (but more like an SSD I guess).
 3. Also, how would you go around connecting memory chips together to get more memory out of them? Would there be a difference with memory chips like serial flash and parallel flash?
 4. Can you use them to output and create basic audio & output HDMI? (or communicate with external ICs to do that task)
 5. Can you somehow connect say 2 8-bit ATTinys to get a pseudo 16-bit microcontroller? Would that mean they could process more data at the same time?

Thanks,
some guy on the internet.

body:
1. Yes, you can connect external RAM chips through the typical interfaces (mainly SPI or I2C). But you cannot execute code from it. The microcontroller is an IC, meaning Integrated Circuit. It is hard wired internally to execute from internal flash. You cannot change that. That is valid for most microcontrollers, that executes from internal flash (which is somewhat a definition of a microcontroller). A processor - in contrast- like in a computer, is build to execute code from elsewhere. Note: Some microcontrollers have the ability to execute from external flash. The ESP boards are a good example for this, because they already use an external flash chip, which is soldered onto the board. You can extent the available flash over the SPI flash pins (the SPI bus, where the flash is connected); though this is not really a topic for beginners. You might wanna look into that.

    If your code, that you want to store externally, isn't that complex, you could save the code there as an own (most likely binary) data format and write code for the microcontroller, that takes that data and executes corresponding functions. So basically an interpreter. Though on the small microcontrollers only code for rather small functionality will fit.

2. Yes, you can add external storage. Which storage depends on many factors. You can by external flash or EEPROM chips, just like external RAM chips. Common storage devices for microcontrollers are SD cards, because they can easily interfaces via SPI. You can even have a file system there (though the size is somewhat limited by the available RAM of your microcontroller, because it needs to load the file table). Maybe you can even connect an SSD, but you will have to look, if you can set up the corresponding interface for it. A microcontroller does not have SATA interfaces or similar. And adding extra chips for these leaves you fastly with interfacing chips, that are way more capable as the main chip itself (see Wifi and the ESPs: You could add Wifi to an Arduino Uno project with it, but the ESP is way more capable, than the Uno). Then you would need to ask yourself: Is this really a good idea?

3. I think most memory chips (whichever kind) are not daisy chainable. Mostly they use a Single-Master-Multiple-Slaves interface like SPI. You could connect multiple memory chips to the SPI bus and communicate sequentially with them. The difference between parallel and serial flash chips is their communication interface. Serial can be something like SPI. Parallel communication will send multiple bits at once over the corresponding amount of wires (mostly 8, means 1 byte). Here you need the corresponding number of free pins on your microcontroller. Though parallel interfacing is often not advisable. Especially the small microcontrollers are too slow, to profit from the faster interface. And instead of using at least 9 pins, you could also use 3 for SPI and get the same transmission speed in the end.

4. Yes, they can. Though it really depends on the used microcontroller and the project topology. When using something like the DFmini player, any microcontroller can play audio (from files on a micro SD card in the player). When the microcontroller should play sounds itself, you can get very different results, depending on the chip capabilities. An ESP32 for example has a dedicated I2S interface, which is build for transmitting sound to an output device.

    About video: AVR based microcontrollers (or similar PICs) cannot really handle video. For example: The most, that you can get out of an Arduino Uno (Atmega328p) is a very very limited VGA signal (very small resolution, only a few colors). HDMI is out of range for any of them. Surely you would want to draw on the screen, that is connected to the HDMI interface, to build up a visual interface. I think, that is just not possible with such small microcontrollers. They are not meant for this. Though you might find some very specialized chip, that you could use in such a way. If, that chip would be way more expensive as buying multiple Raspberry Pis. But if you are willig to compromise you may find a smaller sized display (like a few inches) with a connected controller, that you can control via the Arduino. But still you will have very low refresh rate, so no moving images, more like still images.

5. No, just as 2 32-bit computers do not make 1 64-bit computer. That is just not, how everything works. Each microcontroller can still only process 8 bit at a time out of it's own memory. Depending on the task, you may try to give them different tasks. That would give you more computation power in theory, but it's not the same as a 16-bit controller.

I assume, that you are doing this for fun or for the grind, so I will not say, that you should buy a Raspberry Pi. Though I think, you might look into the wrong way. You cannot make a truck out of parts for a mini, though many of the components work in a similar way. To get all the difficult functionality (audio, video, big storage, ...) out of your self build computer, you need to use computer parts, not microcontroller parts.

If you are happy with much less capabilities, many people in the past have build their own computers out of more basic parts as microcontrollers (down to the big range of logic gates). Microcontrollers live in the world between computers and basic logic components. They are too integrated for extending their capabilities much.


body:
Yes you can, and even execute code from it on PIC18 and PIC17 microcontrollers up to 2MB if external program memory can be added but most variants lac the external program memory interface.
For example the pic18f8x8x you can even implement a memory bank system to address much more than 2MB like PCs did in the early times of the x86 called XMEM extended memory.


message:
Receiving multiple Values from android via Bluetooth

my question is, how can I receive 3 integer values in Arduino, which I send from my android phone. I send all 3 values at the same time and I also need to read them in about the same time.
I hope you can help me.

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

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


message:
Using PortB as a sink, not working

Out of ideas here, i try using PB0-3 as sinks for a LED matrix and the pins just won't sink.

My test code:
```
void setup() {
  //bitClear(SPCR, 6);
  pinMode(PD5, OUTPUT);

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

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

// the loop function runs over and over again forever
void loop() {
  digitalWrite(PD5, HIGH);
  delay(1000);
  digitalWrite(PD5, LOW);
  delay(1000);
}
```
(Using bog standard Blink as a starting point for tests)

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

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

body:
`PB3` etc don't refer to Arduino pins. Instead they refer to the bits in the internal registers.

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

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


message:
Arduino HTTP Command - ESPEasy

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

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

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

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

Thanks!

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

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

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

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

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

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

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

}
```


message:
Can't get keypad to use Keyboard.write on an Arduino Uno

I've tried to use Keypad.h and Keyboard.h libraries to get my Arduino to use my Keypad for Keyboard input.

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

*Working keypad*
```
#include <Keypad.h>

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

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

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

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

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

void loop() {
char customKey = customKeypad.getKey();
  if (customKey){
    Serial.println(customKey);
  }
}
```
At this point, using Serial Monitor, I can see that all keys are being read and printed out no problem.
Then, I tried adding the Keyboard.h library to get it to act as an keyboard input
*Not Working Keyboard Input*
```
#include <Keypad.h>
//#include <Keyboard.h>
const byte Rows = 4;
const byte Cols = 4;

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

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

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

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

void loop() {
char customKey = customKeypad.getKey();
  if (customKey){
    Serial.write(customKey);
    //Keyboard.write(customKey);
  }
}
```
The commented out sections are where I've added changes.
The problems I've encountered:
 - Can't include Keyboard.h on regular Arduino Uno. I've read that changing board type to Arduino Leonardo helps, and it does, but then the Serial Monitor is greyed out and doesn't read keypad input.
 Using following code I get following error message ( I'm still 'using' Leonardo board since Keyboard.h doesn't want to work with Uno)
```
#include <Keypad.h>
#include <Keyboard.h>
const byte Rows = 4;
const byte Cols = 4;

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

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

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

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

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

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

body:
The UNO can't be a Keyboard. It doesn't have a real USB connection. It has a serial connection that passes through a UART to USB converter.

You cannot use the UNO as a keyboard.

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


message:
Weird behavior of variables when replacing for loops with if statement

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

```

int analogInPin = A0;
int analogOutPin3 = 3;

int sensorValue;

int i = 0;
int a;
int y;

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

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

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

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

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

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/zEAe2.jpg

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

define instead of

    int y;

change to

    long y;

and change

     void inOut(int &i){

to

    void inOut(){
and remove

       return i;// Its a global var

change the line

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

to

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

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


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

```

int analogInPin = A0;
int analogOutPin3 = 3;

long sensorValue;

int i = 0;
int a;
long y;

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

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

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

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

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


message:
Arduino bluetooth HC-05 servo control

I am using HC-05 Bluetooth module to control two servos. I use Bluetooth terminal in my android phone to control them.

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

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

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

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

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

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

    }
    }
    }

Where is the problem?

body:
When using

    if(BT.available())

that's doing the same as

    if(BT.available() > 0)

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

Try to use

    if(BT.available() >= 2)

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


message:
Sending MIDI CC to multiple midi Channel

Hi so i would like to send CC messages to different MIDI Channel (volume control). The CC messages are coming from one knob.

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

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

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

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

MIDI.sendControlChange(controlNumber, controlValue, channel);

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

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

or

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

or

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

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

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

Hope you can help, in advance, thanks

        /* USB MIDI AnalogControlChange Example

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

       This example code is in the public domain.
    */

    #include <Bounce.h>

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

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

    void setup() {

    }

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

    elapsedMillis msec = 0;

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

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

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

      }

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

body:
A single CC message applies to a single channel. If you want to affect multiple channels, you have to send multiple messages:

<!-- language-all: lang-cpp -->

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

And this should of course be done in a loop:

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


message:
ESP8266, I am trying to establish a SoftAP and I cant seem to get the WiFilocalIP function to give me my IP

I am just trying to establish a server and it seems that I can't get the serial monitor to read the local IP of my device and my Client can't establish a connection to update the sensor value. when I run the monitor I get this:

IP Address: (IP unset)

here is my code:

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

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

        //Setup Server Object
        ESP8266WebServer server;

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

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

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

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

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

body: The WiFi.localIP() is a function of the STA. To print the IP address of the SoftAP, use WiFi.softAPIP().


message:
ESP-01 Programming

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

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

**What I am trying to do**

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

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

ESP01:
[![https://components101.com/sites/default/files/component_pin/ESP8266-Pinout.png][1]][1]

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

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

**Circuit**

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

*ESP*:
VCC   -> 3.3v EXPWS

GND   -> GND  EXPWS

CH_PD -> 3.3v EXPWS

RX -> RX AN*

TX -> TX AN*

GPIO0 -> 3.3v EXPWS*

RESET -> 3.3v EXPWS*

*Arduino*

GND -> GND EXPWS

GND -> Reset AN*

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

**Where I am**

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

**Things I cannot do**

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

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

    }

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

    }

But I can access AT commands with the following two:

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

    }

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

    }

and

    void setup() {
      int i = 0;

    }

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

    }

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

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

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

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

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

**Conclusion**

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

  [1]: https://i.stack.imgur.com/AO3Mn.png

body:
Wow this was complicated to figure out.  I am able to upload code to the esp, though it doesn't run yet.

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

**Wiring**

Format: ESP -> Raspberry Pi

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

CH_EN -> 3.3v

GND -> GND

GPIO0 -> GND

TX -> RXD (GPIO 15)

RX -> TXD (GPIO 14)

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

**Uploading**

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

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

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

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

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

    esptool.py --port /dev/ttyS0 write_flash 0x1000 SketchFolder/Sketch.ino.generic.bin

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

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

and

    Invalid head of packet

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

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

**Conclusion**

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


message:
How to split a *char and pass to a function needing uint8_t?

I have a requirement where an event has `char *newvalue`.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


message:
Serial.println() not working in ISR

Please refer my below code,

    const int led_pin = PB5;
    const uint16_t t1_load = 0;
    const uint16_t t1_comp = 43750;
    int blinkcount;

    void setup() {
      // put your setup code here, to run once:
      DDRB |= (1<< led_pin);
      TCCR1A = 0;
      //TCCR1B = 0X03;
     TCCR1B |= (1 << CS12);
     TCCR1B &= ~(1 << CS11);
     TCCR1B &= ~(1 << CS10);

      TCNT1 = t1_load;
      OCR1A = t1_comp;

      TIMSK1 = (1 << OCIE1A);
      Serial.begin(9600);
      sei();

    }

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

    }

    ISR(TIMER1_COMPA_vect) {
      TCNT1 = t1_load;
      PORTB ^= (1 << led_pin);
      blinkcount = blinkcount + 1;
      Serial.println(blinkcount);
    }

the Serial.println(blinkcount); not working or the serial window does not show up.

Apologies if it sound stupid as I'm new to programming.

body:
ISR are simply not intended for this abuse.

If you want to use Arduino level functions, you must have good reasons why you need to mix them with direct arv-gcc hardware-accessing code (or vice versa).

If you're new to programming and to Arduino, simply ignore that level (for now).

`DDRB |= BV(PB5);`
is easier understandable if you write

`pinMode(13,OUTPUT);` ( or even use LED_BUILTIN instead of 13 )


body:
```const int led_pin = PB5;
const uint16_t t1_load = 0;
const uint16_t t1_comp = 43750;
int blinkcount;
int flag, flag_1, a, i;

void setup() {
  // put your setup code here, to run once:
  DDRB |= (1<< led_pin);
  TCCR1A = 0;
  //TCCR1B = 0X03;
 TCCR1B |= (1 << CS12);  //for 256 prescalar
 TCCR1B &= ~(1 << CS11);
 TCCR1B &= ~(1 << CS10);

/* TCCR1B &= ~ (1 << CS12);
 TCCR1B |= (1 << CS11);
 TCCR1B &= ~(1 << CS10);*/

  TCNT1 = t1_load;
  OCR1A = t1_comp;

  TIMSK1 = (1 << OCIE1A);
  Serial.begin(9600);
  sei();

}

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

/*  blinkcount = blinkcount + 1;
  if(blinkcount++)
  {
    flag = 1;
  }
  if(flag == 1)
  {
    Serial.println("ok");
  }*/

}

void loop_1()
{
  i = blinkcount;
  //for(i=0; i<=blinkcount; i++);
  //{
  i = i + 1;
  //if(i++)
  // {
    flag = 1;
    flag_1 = flag;
   //}
  if(flag_1 == 1)
  {
    Serial.println(flag_1);
  }
//  }
}

ISR(TIMER1_COMPA_vect) {
  TCNT1 = t1_load;
  PORTB ^= (1 << led_pin);
  //blinkcount = blinkcount + 1;
  //Serial.println(blinkcount);
  loop_1();

}```

I've changed the code according to your suggestion, the tx led on arduino blinks but serial monitor does not pop up


message:
A problem in l led or arduino nano

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

body: The `L` LED and pin 13 are one and the same thing. That LED is connected directly to pin 13. If you blink pin 13 then that LED will blink.


message:
Arduino bluetooth HC-05 data reading problem

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

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

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

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

    SoftwareSerial BT(2,3);

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

    }

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

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

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

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

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

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

      }
    }

body:
You are mixing ASCII characters and integer values.

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

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

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

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

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

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

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

or by a convinient function

    if(isDigit(c))


message:
What are the applicable processor for the ATmega32u4? And what are higher versions of ATmega32u4?

Can arduino uno smd r3 version handle a Keyboard.h library?  it is not applicable for that arduino?

body:
The Arduino Uno cannot use the `Keyboard` library. The microcontroller needs to have a native USB interface. The Uno uses the Atmega328p, which does not have one.

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

---

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


message:
How to subtract micros()?

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

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

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

Thanks you.

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

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

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

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

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

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

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