body:
    //Numbers 0-9.
    int numberArray[10][7] = {
      { 0, 0, 0, 0, 0, 0, 1 }, //0
      { 1, 0, 0, 1, 1, 1, 1 }, //1
      { 0, 0, 1, 0, 0, 1, 0 }, //2
      { 0, 0, 0, 0, 1, 1, 0 }, //3
      { 1, 0, 0, 1, 1, 0, 0 }, //4
      { 0, 1, 0, 0, 1, 0, 0 }, //5
      { 0, 1, 0, 0, 0, 0, 0 }, //6
      { 0, 0, 0, 1, 1, 1, 1 }, //7
      { 0, 0, 0, 0, 0, 0, 0 }, //8
      { 0, 0, 0, 0, 1, 0, 0 }, //9
    };

    //Turn off all segments (common anode --> high = off)
    void reset() {
      for (int i = 12; i >= 6; i--) {
        digitalWrite(i, 1);
      }
    }

    //turn on both segments (don't write anything to them)
    void on(){
      digitalWrite(4,1);
      digitalWrite(5,1);
    }

    void setup() {
      pinMode(12, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(5, OUTPUT);
      reset();
      on();
    }
    void loop() {
      for (int i=0;i<99;i++){
        twoDigitNumber(i);
      }
    }

    void twoDigitNumber(int number){
        digitalWrite(4,1);                   //turn on left display
        digitalWrite(5,0);                   //turn on right display
        digit(int(floor(number/10)));        //display the tens digit
        delay(10);
        digitalWrite(4,0);                   //turn off left display
        digitalWrite(5,1);                   //turn on right display
        digit(int(number-floor(number/10))); //display the ones digit
        delay(10);
    }

    //make the displays show a single digit number
    void digit(int number) {
      for (int i = 12; i >= 6; i--) {
        digitalWrite(i, numberArray[number][12 - i]);
      }
    }

This is my first time doing anything at all with Arduino, and I'm also brand new to the language.

I have a bit of circuitry attached to the display. I'm using 2n5551 NPN transistors to act as a switch. Collectors connected to 5v, bases are connected to pin 4/5 with a 200 ohm resistor. Emitters are connected to the common anode of the displays. pin 4 is for the left display, pin 5 for the right display. These are to display different numbers in each display. Something's probably wrong with this but I'm having a hard time learning about transistors.

When I use the function twoDigitNumber(), it only displays the number on the left display, but I can see a very dim copy of that same number on the right display. int() is there because i thought floor() would make it into a double and cause issues, but that didn't fix it.

I know every segment works. When I use digit(), it shows the same digit on both displays (as expected).

Any help is appreciated.

title: I'm trying to display the numbers 0-99 by multiplexing to two 7 segment displays. One number does not display

Answers: 1

body:
Missing `pinmode(4,OUTPUT)` in your `setup` routine.

As a general comment, using variable names instead of 'magic numbers' makes your code easier to read - and thus usually easier to debug. for example:

    const int leftDisplay = 4;
    const int rightDisplay = 5;
    const int seg1 = 12;
    const int seg2 = 11;
    [...]

You can also use `HIGH` and `LOW` instead of `1` and `0` for the `digitalwrite` elements


body:
I have two PCBs with ATmega328 that will communicate through I2C protocol. The master will also provide power for the slave, which is located at a relatively short distance (30-40cm or 12-16 inches).

Is it feasible to use the same cable for power (3.3V) and communication?

Thank you.

title: 4-wire shielded cable for I2C and power

Answers: 1

body:
Sure. Why wouldn't it be? Power is (pretty) static and noiseless.

Just be warned that having the clock and data in the same twisted pair (if your cable has twisted pairs) could cause issues over longer distances. I2C isn't designed for running over cables like that - it's designed for routing round short traces on a PCB.


body:
I made a project with an **Arduino Uno**, a 16x2 LCD **display** and a DS18B20 **temperature sensor**. It shows the temperature in the display:

[![Arduino Uno with 16x2 LCD and temperature sensor][1]][1]

I want to connect it to Internet so I got a Wemos D1 Mini. It works great: it send data through my router.

But I need to connect my project with the Wemos D1 Mini:
[![Wemos D1 Mini pins][2]][2]
I think that I just need to send the data (temperatures grades) from my project to Wemos so then Wemos resolve it.

How can I do it?

  [1]: https://i.stack.imgur.com/69IcP.jpg
  [2]: https://i.stack.imgur.com/t0iJR.png

title: How to connnect Arduino to Wemos D1 (send data)?

Answers: 2

body:
- A) Throw out the Arduino, and just connect your display and sensor to the WeMos directly.
- B) Connect the Arduino to the WeMos using UART, SPI or I²C and send the temperature value to the WeMos. Keep in mind that the Arduino UNO is a 5V device, and the maximum voltage for the ESP8266 is 3.3V, so you'll need a level shifter.
You can send the temperature as a binary value (beware of framing errors), but the easiest way is to use a text-based protocol. Since you just have to send a single value, you can just use a single delimiter (e.g. new line). That makes it very easy to parse.

body:
If you want to use the Wemos D1 only as a 'network adapter', put a firmware into esp8266. 'Classic' is Espressif AT firmware in esp with WiFiEsp library in your sketch. New option is WiFi Link firmmware in the esp with [WiFi Link library][1] used in your sketch.

Both libraries recommended by me (WiFiEsp and WiFiLink) have standard Arduino networking API like the Ethernet and WiFi library.

[WiFi Link firmware][2] is an Arduino sketch for the esp8266.

  [1]: https://github.com/jandrassy/arduino-library-wifilink
  [2]: https://github.com/jandrassy/arduino-firmware-wifilink


body:
for programming my ESP-01 chip I bought an "USB Uart", but it looks different to all the ones in all tutorials. I don't know how to connect the uart to the esp.
The uart i bought has following pins: 3V3, DTR, RXI, TX0, GND, +5V. The ESP01 has the known layout (http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family#esp-01).

Once connected: Do I need an external power source, or do i just connect the usb uart to my computer?

Many thanks

title: Connect ESP-01 to USB Uart

Answers: 2

body:
Just to give an anwser for users struggling with the same problem I will sum up what helped me.

To connect the UART to the ESP the `Beginner's Guide to the ESP8266` from @tttapa was very helpful. Another helpful link was this one:
https://www.allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now/

So in my case I just needed the GND, 3V3, RXI and TX0 pins from my UART.

I needed no external powersupply for the flashing process and some simple examples.

body:
You can program the ESP-01 whith described method in this page:

[https://zinventor.wordpress.com/primeros-pasos-con-esp8266/][1]

  [1]: https://zinventor.wordpress.com/primeros-pasos-con-esp8266/

Its works fine!


body:
I got this lcd with touchscreen from a store but i have no idea on how to connect it to the arduino uno.
Any help is appreciated.

[This][1] is where i bought it from.

[The display][2]

[My Arduino][3]

  [1]: https://www.optimusdigital.ro/ro/optoelectronice-lcd-uri/3544-modul-lcd-spi-de-28-cu-touchscreen-controller-ili9341-i-xpt2046-240x320-px.html?search_query=Modul LCD SPI de 2.8'' cu Touchscreen - Controller ILI9341 și XPT2046 (240x320 px)&results=1
  [2]: https://i.stack.imgur.com/KDTRI.jpg
  [3]: https://i.stack.imgur.com/M3bmD.jpg

title: Help connecting ILI9341 LCD SPI Display to arduino uno

Answers: 2

body:
1. Download and install a suitable library
2. Wire the display to the Arduino as per the markings on the display
3. Try some of the examples for the library you are using.

body:
You can get it working by two methods

1. using a voltage divider e.g to shift from 5V to 3.3V you could use two resistors, 100k and 200k respecfully and between both resistors there is voltage of 3.3. One for each pin that needs it.

2. Using 10K resistors in series between the LCD and the arduino. I really don't know how is working but it works fine that way.

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


body:
I'm trying to make a computer-controlled painter/drawer/CNC, something like [this][1], from an old junk printer that didn't work... I have got as far as a working motor shield that can move the sliding trolley back and forth by running the DC for a short amount of time, and running the stepper that would be "paper feed". But it is currently just some gears and roller.

1: Assuming I can attach the paper-feed gear to a platform to move it in both X and Y directions, is there still no way I can multithread Arduino code? Searching for this, I found results in some really old howtos/forums that say you cannot, but you can fake it by doing one thing then another. I would want a serial command to send the Arduino to say, "start 3mm right" and while doing so, run "3mm forward" for example for a diagonal line. I've only run this on commands that are run intermittently and can block while the command is running [like so][2].

2: There is a clear "tape" with lines on it that goes through the sliding trolley and has a ribbon coming out of the sliding trolley that I assume is reference indicating that it is x mm away from the end, that lets the printer see how long to move. Would it be feasible to reverse-engineer this type of device to use in this custom application? Could this be done with an oscilloscope output connected to pins on the ribbon?

  [1]: https://www.instructables.com/id/DIY-3axis-CNC-plotter-out-of-old-printers/
  [2]: https://github.com/programmin1/HowToTrainYourRobot/blob/master/StepperShieldTest/StepperShieldTest.ino

title: DIY printer + Arduino. Can I use the position sensor? Multithreading?

Answers: 2

body:
You can multi*task* on arduino by doing stuff for one task for a bit and then do stuff for another task for a bit and switch back and forth like that.

However many arduino libs tend to rely on blocking calls and don't support giving control back to calling code so time spent in `delay()` calls can be used by other code.

body:
I recommend using the [AccelStepper library](http://www.airspayce.com/mikem/arduino/AccelStepper/) (installable via the Library Manager) which will allow you to drive multiple stepper motors at once without blocking commands.

1. It's possible to multithread on an Arduino but it's a sophisticated operation that you don't actually need to do for this application. Better instead to call one motor move, then the next, in rapid succession in your main loop. The AccelStepper library sort of builds this in when you're using it for position-based control; you tell one motor where to move and then run `motor.run()` as often as possible in the loop to actually send the commands to your driver to move it. (You *also* tell the other other motor to move, and also run `motortwo.run()` just as often as `motor.run()` in the loop; neither command takes much time at all to run.) For precisely coordinated multi-motor moves, look at the `MultiStepper` example included in the library, but note that the sort of thing I'm describing, implemented in the similarly-named `MultipleSteppers` example, will do the trick for you.

2. Regarding that "clear tape," my suspicion is if you look close, you'll find it's got lots of very narrowly spaced black and clear bands. It is used to report position data back to the motor driver. It more than likely has a photointerruptor that reads its movement. You can read the speed (but not absolute position) of that tape by monitoring the clear and black sections moving through the photointerruptor. For higher precision of data, likely necessary because the tape will be moving relatively fast, you'll likely want to use an [interrupt](https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/) feature of the chip to watch the ticks as they go by, which is designed to take precedence over other would-be simultaneous operations the chip is doing.

Good luck with the project!


body:
I am using an Arduino Uno. `analogRead(A0)` (or whichever channel I use) returns 0 when it is grounded with Arduino Gnd, and 1023 when connected to Arduino 5v. But when I connect it to a current sensor (ACS712) it is always fluctuating like this:

>0, 0, 0, 0, 0, 0, 1023, 1023, 1023, 1023, 1023, 441, 446, 0, 0, 0, 0, 1023, 1023...

I also tried it with a potentiometer (10K) and analog joystick: the results are the same. I tried changing different power supplies (both Arduino's and the sensor's (ACS712, potentiometer, joystick)). I even tested it on an Arduino Mega, but no luck. Such extreme fluctuation are making no sense to me. Kindly help me what could be the issue.

My wiring diagram is attached to this post. And I use an external supply to the ACS712. Is it possible that Static electricity is causing this issue?

Code:

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

    void loop() {
      float value = analogRead(A0);
      Serial.print("Raw:");
      Serial.println(value);
      delay(500);
    }

Thanks.

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

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

title: Arduino Analog Input: why the weird fluctuation?

Answers: 2

body:
You need to connect together the grounds from your external power supply and the Arduino.

At the moment the two devices are floating - there's no commonly-agreed 0v point.

body:
I had a similar issue with fluctuating values. Make sure you are setting in your code the analog PIN as `INPUT` pin. On some boards you have to specify it explicitly, like this:

    pinMode(A1, INPUT);


body:
I am trying to use an ESP32s controller connected to an RC car DC motor. I found that when using my Arduino this is easily accomplished, and I can see that my output pin produces 5v for the motor to spin. My ESP32, however, only produces 3.3v, so of course the motor does not spin. Do I need to use a motor driver board, transistors, or will the ESP32 simply not work in this scenario?

Thanks in advance.

title: Is it possible to increase the voltage on 3.3v output to 5v on an ESP board to power a DC motor?

Answers: 2

body:
You should not power a motor from a micro-controller, period, regardless if that is an ATmega or an ESP32.

Instead, you need to use a motor driver circuit - this isn't really so much about *voltage* amplification, as it is about *current* amplification. The actual I/O output voltage of your ESP32 is likely very close to 3.3v. If you are measuring 1.8v, that is only because you motor is loading the pin so heavily (and improperly) that the voltage sags.

Without the specs of your motor, it's not really possible to provide any specific advice. But you should seek an FET-based solution, not one based on bipolar transistors.  The old bipolar L293D, L298, etc parts are horribly lossy and extremely unsuited to low voltages motors. In some low-voltage, low-current cases, the FET-based TB6612FNG can be a good solution - **but again, this depends entirely on the unstated requirements of your motor**. Typically only very lightweight or weak "RC cars" could use such drive, for more serious ones you should look at hobby-grade Electronic Speed Controller (ESC) modules, or their equivalent circuitry.

These motor driver chips will have two supply inputs. One supplies the logic and would typically share the microcontroller's supply voltage. The other supplies the motors - it might in light duty cases be whatever is supply the microcontroller's regulator, but in more power-hungry cases would often be a unique supply. Both grounds should be connected together and connected to the microcontroller's ground, but in such a way that the ground current for the motors flows directly from the power supply, and never *through* the microcontroller board.

body: I figured out my issue. I was only getting 1.8v output because I was testing my lead after a led light I had plugged in. Once I removed the led, my voltage went to 3.3v, which was expected.


body:
I am trying to read a value between 1000 and 2000 from my Serial Monitor and use it to drive some motors through ESC.

The code works when I use a potentiometer mapped for 1000-2000. I am now trying to use a Serial Monitor, but the "val" keeps going from the value I enter (between 1000 and 2000) and quickly returns to 0.

Why is this?

Here is the code for reference:
<!-- language-all: lang-cpp -->

    #include <Servo.h>//Using servo library to control ESC
    Servo esc1; //Creating a servo class with name as esc1
    Servo esc2; //Creating a servo class with name as esc2
    Servo esc3; //Creating a servo class with name as esc3
    Servo esc4; //Creating a servo class with name as esc4
    void setup()
    {
      esc1.attach(7); //Specify the esc signal pin,Here as D10
      esc2.attach(6); //Specify the esc signal pin,Here as D9
      esc3.attach(5); //Specify the esc signal pin,Here as D8
      esc4.attach(4); //Specify the esc signal pin,Here as D7
      esc1.writeMicroseconds(1000); //initialize the signal to 1000
      esc2.writeMicroseconds(1000); //initialize the signal to 1000
      esc3.writeMicroseconds(1000); //initialize the signal to 1000
      esc4.writeMicroseconds(1000); //initialize the signal to 1000
      Serial.begin(9600);
    }
    void loop()
    {
      int val; //Creating a variable val
      Serial.println("Input ESC Speed between 1000 and 2000:");
      while (Serial.available() > 0) {
        val = Serial.parseInt();
        Serial.println(val);
      }//Checks for a character in the serial monitor
      Serial.println(val);
      esc1.writeMicroseconds(val); //using val as the signal to esc
      esc2.writeMicroseconds(val); //using val as the signal to esc
      esc3.writeMicroseconds(val); //using val as the signal to esc
      esc4.writeMicroseconds(val); //using val as the signal to esc
    }

title: Serial.parseInt value always goes back to 0

Answers: 1

body:
This code will work IF you set the Serial Monitor to "No Line Ending" (OSX 10.6.8. IDE Version 1.0.6.2). parseInt() doesn't like the NL + CR chars.

    unsigned int val;

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

    void loop(){
      Serial.println("Input ESC Speed between 1000 and 2000:");
      while(Serial.available() > 0){
        val = Serial.parseInt();
      }
      if(val > 0){Serial.println(val);}
      delay(1000);
    }

There is another way to get the integer value using this code:

    char inputBuffer[16];
    unsigned int val;

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

    void loop(){
      Serial.println("Input ESC Speed between 1000 and 2000:");
      while(Serial.available() > 0){

        // A function that reads characters from the serial port into a buffer.
        Serial.readBytes(inputBuffer, sizeof(inputBuffer));

        // Convert string to integer
        // cplusplus.com/reference/cstdlib/atoi/
        val = atoi(inputBuffer);

        // memset clears buffer and updates string length so strlen(inputBuffer) is accurate.
        memset(inputBuffer, 0, sizeof(inputBuffer));
      }
      if(val > 0){Serial.println(val);}
      delay(1000);
    }

The Binary sketch size is 94 bytes less than the first example using parseInt. The second sketch will work with ANY Serial Monitor Line Ending settings.


body:
I am trying to build an Arduino Uno based robot. My questions are the following:

1) The motor driver also has an on-board 78M05 voltage regulator from ST electronics. I used a 9V battery to power the robot, and the 9V was connected to the input of the voltage regulator, and the +5V output I used to power the Arduino. I did so by connecting the 5V from the regulator to the 5V pin on the Arduino and the GND's together. I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?

2) I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?

title: Powering Arduino from 7805 voltage regulator

Answers: 1

body:
> I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?

Nothing wrong with that as long as it is regulated 5V (which yours is). You can use either the 5V pin on the header, or the 5V pin on the ICSP connector. They are both the same.  It is good practice to connect a diode between 5V and VIN to prevent current flowing backwards through the onboard regulator should something connected to VIN want to draw current.

> I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?

A regulator has a "drop-out" voltage. That is often in the order of 1.2V for these kind of regulators (it's certainly right for the Arduino's on-board one.

You are providing less than the regulation voltage plus the drop-out voltage, so the output of the regulator will be the input voltage minus the drop-out voltage.

As long as that is above the lowest voltage the Arduino can run from at 16MHz then it will still work fine. You should be fine down to about 4V output from the regulator, and even lower if you're lucky (you may start getting stability problems though since the ATMega328P isn't rated to run at 16MHz at lower voltages).

It also means that the GPIOs on the Arduino will be running at a lower voltage as well.


body:
I'm trying to create an Arduino project with a light sensor and a buzzer. The idea is that when the sensor detects that the lights have gone off, the buzzer will sound for 5 seconds. At some point, the lights will come back on, but when they go back off, I need the buzzer to sound again.

At the moment the buzzer does sound the first time the lights are turned off but after the lights have come back on and then off again, it won't sound and I can't figure out why.

    int lightSensor = 2;
    int buzzer = 3;
    long startTime,stopTime;
    long myDesiredTime = 5000;

    void setup()
    {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(lightSensor, INPUT);
      pinMode(buzzer, OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      int sensorState = digitalRead(lightSensor);

      switch(sensorState)
      {
      case 1:
        while (sensorState == 1)
        {
          if(stopTime-startTime<=myDesiredTime && sensorState == 1)
          {
            runBuzzer();
            stopTime=millis();
          }
        }
      }
    }

    void runBuzzer()
    {
      tone(buzzer, 1000); // Send 1KHz sound signal...
      delay(1000);        // ...for 1 sec
      noTone(buzzer);     // Stop sound...
      delay(1000);
    }

title: How can I loop for a set amount of time when a condition is met?

Answers: 3

body: Understand that your `while (sensorState == 1)` in your `switch()` is an infinite loop, with no way out (even if internally it gives the desired 5 seconds of sound).

body:
Think of it like this. Any time you use a while loop your code has the rains until its done its job.

It's important to remember that the loop() function in Arduino should not be blocked. This line:

`while (sensorState == 1)`

will block forever. The condition is never changed from within the while loop. Theres a simple way you could fix this which would be to set `sensorState` and update it inside the while loop. But lets not do that. Because thats inefficient and you'll likely run into this problem again in more complex programs and that solution here won't still be a solution.

What you're trying to do is called concurrency. Your program should have obvious units of execution. Your two units are: "run a buzzer for 5 seconds" and "set off an event when a sensor reads true." where the first is depended on the second. So its conditional. That sounds like a job for `if`

When you code in `{` and `}` it is a block. It's not quite a context but is a distinct mode of execution.

So technically this:

    void loop() {
        if( ... ) {
          ...
        }
        if ( ... ) {
          ...
        }
    }

Is two modes of execution. Since loop() is executed repeatedly. With that in mind when you program you can then use a variable to control the what gets executed as needed. So:

    void loop() {
        int sensorState = digitalRead(lightSensor);
        if( sensorState == 1 && buzzer_enabled == 0) { // set off an event when a sensor reads true.
            buzzer_enabled = 1;
            startTime = millis();
        }
        if ( buzzer_enabled == 1 ) { // run a buzzer for 5 seconds
            endTime = millis();
            if(stopTime - startTime <= myDesiredTime) {
                runBuzzer();
            } else {
                buzzer_enabled = 0;
            }
        }
    }

We could stop here. But the use of delay is also blocking in the loop function and it is only for perception. So here's the whole thing without delays using a check against the modulus of diffTime.

    int lightSensor = 2;
    int buzzer = 3;

    long startTime,stopTime;
    long myDesiredTime = 5000;

    bool buzzer_enabled = false;
    bool buzzer_active = false;

    int sensorState;
    int prevSensorState = 0;

    void setup()
    {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(lightSensor, INPUT);
      pinMode(buzzer, OUTPUT);
    }

    void loop() {
        sensorState = digitalRead(lightSensor);
        if( sensorState == 1 && prevSensorState == 0 ) { // set off an event when a sensor reads true.
            buzzer_enabled = true;
            startTime = millis();
        }
        prevSensorState = sensorState;
        if ( buzzer_enabled == true ) { // run a buzzer for 5 seconds
            stopTime = millis();
            long diffTime = stopTime - startTime;
            if( (diffTime % 2000) < 1000 ) {
                if(buzzer_active == false) {
                    buzzer_active = true;
                    //tone(buzzer, 1000);
                }
            } else {
                if(buzzer_active == true) {
                    buzzer_active = false;
                    //noTone(buzzer);
                }
            }
            if(diffTime > myDesiredTime) {
                buzzer_enabled = false;
            }
        }
    }

No need for delay >:3 And all for free you got a new feature which is that if you set off the event again (the light goes off) the buzzer is extended another 5 seconds. If you don't want that all you have to do is add ` && buzzer_enabled == false` to the first if.

body:
You have two major issues here:

    void loop() {
      // put your main code here, to run repeatedly:
      int sensorState = digitalRead(lightSensor);

      switch(sensorState)
      {
      case 1:
        while (sensorState == 1)
        {
          if(stopTime-startTime<=myDesiredTime && sensorState == 1)
          {
            runBuzzer();
            stopTime=millis();
          }
        }
      }
    }

The first is that you never re-read sensorState. The second is that you are comparing stopTime before setting a value to it. Try re-arranging like this:

    void loop() {
      // put your main code here, to run repeatedly:
      int sensorState = digitalRead(lightSensor);

      switch(sensorState)
      {
      case 1:
        while (sensorState == 1)
        {
          stopTime=millis();
          if(stopTime - startTime <= myDesiredTime)
          {
            runBuzzer();
          }
        sensorState = digitalRead(lightSensor);  // read sensorState again
        }
      }
    }

---

> In your example, the buzzer does not sound when the light has been switch on and then back off again.

Good point. Well, we can simplify somewhat:

    void loop() {

      if (digitalRead(lightSensor) == HIGH)
        {
        startTime = millis ();  // remember when we started
        while (digitalRead(lightSensor) == HIGH &&
               millis () - startTime <= myDesiredTime)
          {
          runBuzzer();
          }  // end of while switch still closed and time not up
        while (digitalRead(lightSensor) == HIGH) { } // wait for sensor go to LOW
        delay (200);  // debounce
        }    // end of switch being closed
    }      // end of loop


body:
I'm attempting to use an Arduino Nano with the RDM8800 to read data from NFC tags. After soldering wires between the Nano and the RDM8800, I attempted to test these devices using code similar to what has been used successfully on other serial devices similar to the RDM8800. Below is the code I used to test.

Wiring:

    Nano - RDM8800
    --------------
     5V  -  5V
    GND  -  GND
     D3  -  TX
     D2  -  RX

Tags Tested:

 - NTAG 216 (ISO14443A)
 - MiFare Classic 1k (ISO14443A)

Code:

    #include <SoftwareSerial.h>

    SoftwareSerial soft(2,3);

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

    void loop() {
      if(soft.available() > 0) {
        String serialData = soft.readString();
        Serial.println(serialData);
        writeAck();
      }

    }

    void writeAck() {
      uint8_t payload[] = "ACK|0|\n";
      soft.write(payload, sizeof(payload));
    }

I watched the serial monitor and attempted to scan two different NFC tags that matched the ISO14443A compatibility that should ship with the RDM8800, according to [this][1] article. I got no information returned on the serial monitor.

After, assuming the issue is with the firmware, I attempted to upload the firmware to the RDM8800, with no success. I installed the needed board support to the Arduino IDE, as outlined in [the intro article][1]. Not having a USB to serial tool, I used another Nano and simply bridged the connection between the GND and RST pins. I was unable to upload the firmware to the RDM8800, getting the error below each time I tried.

Error:

    avrdude: stk500_recv(): programmer is not responding

I believe that it's possible that I can't upload the firmware to the RDM8800 because the setup I used with the Nano as the USB to serial tool lacked a reset button. The image in [the intro article][1], says to connect the TX RX GND 5V and RST pins, but the image that it says shows this only shows the TX RX GND and 5V pins connected(See below).

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

The information that I've found on the RDM8800 and its use is very limited and so is my knowledge on this topic. I'm unsure how I should proceed right now. I believe that I'm taking the right approach to setup code to scan NFC tags, but I could be wrong there. I'm very unsure on what I'm doing in relation to the potential firmware issue. Overall, I'm simply unsure on how to proceed and I'm looking for more knowledgeable people to give me some advice on how to proceed.

Relevant Resources:
[RDM8800 Itead Wiki Page][3]
[RDM8800 Data Sheet][4]
[RDM8800 Schematic][5]
[RDM8800 Introduction Article][1]

  [1]: https://www.itead.cc/blog/introduction-to-rdm8800-a-13-56mhz-configurable-rfid-module
  [2]: https://i.stack.imgur.com/KrQVu.jpg
  [3]: https://www.itead.cc/wiki/RDM8800
  [4]: ftp://imall.iteadstudio.com/Modules/IM131218001/DS_IM131218001.pdf
  [5]: ftp://imall.iteadstudio.com/Modules/IM131218001/SCH_IM131218001.pdf

title: Interfacing Aduino Nano and RDM8800

Answers: 1

body:
SoftwareSerial constructor is rx pin first then tx pin.

You have `SoftwareSerial soft(2,3);` But you said that

    D3 - TX
    D2 - RX

Which means soft rx is going to its rx and soft tx is going to its tx. These need to be swapped. Either swap the wires or change it to:

    SoftwareSerial soft(3,2);


body:
I have an Arduino UNO and HUZZAH ESP8266  module.  I need to send data between Arduino UNO and ESP module via Software Serial.  Right now I have the ESP module write data and Arduino UNO display data, but not working. When I run the Arduino UNO  and open its Serial Monitor, nothing is printed using below source code.

1. ESP8266 RX PIN connected to Arduino UNO PIN 2.
2. ESP8266 TX PIN connected to Arduino UNO PIN 3.
3. Using the FTDI cable that came with HUZZAH ESP8266 to power this module.  I just individually connected the RX and TX pins to the ARDUINO PIN 2 and 3 as mentioned above.

Any ideas what why not working? Below is code for both modules. Thanks,

Arduino UNO

    #include <SoftwareSerial.h>

    SoftwareSerial ESPserial(2, 3); // RX | TX

    void setup(void){
      //Start hardware Serial communication
      Serial.begin(115200);

      //Start the software serial for communication with the ESP8266 component
      ESPserial.begin(57600);

    }

    void loop(void){

    if (ESPserial.available()){
      Serial.println("ESP available!!!");
      Serial.println(ESPserial.read());
    }

    }

HUZZAH ESP8266

    #include <ESP8266WiFi.h>

    #include <SoftwareSerial.h>

    SoftwareSerial ESPserial(2, 3); // RX | TX

    void setup(void){
      //Start the software serial for communication with the Arduino UNO component
      ESPserial.begin(57600);

      //TODO: setup Wifi
    }

    void loop(void){
       ESPserial.write("This message generated by ESP module.");
       delay(500);
    }

title: softwareserial between arduino uno and esp8266

Answers: 3

body:
Make sure that:

 1. RX pin on the Arduino UNO is connected to the TX pin on the ESP8266.
 2. TX pin on the Arduino UNO is connected to the RX pin on the ESP8266.
 3. Baud rate should be set to the same value from both the Arduino and ESP8266.

I don't know about your arduino but looking at this schematic, your RX and TX should be swapped.

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

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

body: Adding to the above answer. UNO's TX is at 5V , while ESP8266 's RX is at 3.3V, as it is a 3.3V module. So its better to use a resistive divider to bring UNO' TX to 3.3V and then feed to ESP's RX, instead of directly connecting them eachother.

body:
//ESP

    #include "SoftwareSerial.h"

    SoftwareSerial ArduinoUno(D2,D3); //Rx, Tx

    void setup() {

    Serial.begin(9600);

    ArduinoUno.begin(4800);

    pinMode(D2, INPUT);

    pinMode(D3, OUTPUT);

    }

    void loop() {

    }

    /******************************************************************************/

//UNO

    #include "SoftwareSerial.h"

    SoftwareSerial ArduinoUno(3,2); //Rx, Tx

    void setup() {

    Serial.begin(9600);

    ArduinoUno.begin(4800);

    }

    void loop() {

      if(ArduinoUno.available() > 0){

        //float val = ArduinoUno.parseFloat();

        Serial.println(ArduinoUno.read());

      }

      delay(30);

    }


body: If I'm going to measure an AA battery (about 1.5 v) with a USB-powered Arduino, I will connect the battery's +ve terminal to the A0 pin. Shall I connect the -ve terminal to the gnd pin too?

title: Measure an AA battery?

Answers: 1

body: Yes you could although this means you're measuring in relation to the Arduino's logic voltage, which is slightly below 5v (due to a diode's voltage drop) or the voltage of vref.


body:
Im trying to understand how the Arduino ISR keeps track of timing between pulses stored in a variable, if that variable is latter used.

Say, for example, you have a magnet mounted on a circular object, that passes a reed switch. Using this to trigger the ISR that calls a function that would have something like counts++ in it, then storing that value in a variable.

If that varible is used latter to turn on a motor, for example, according to the count capture, how does the arduino MCU know the freq or timing to output the count or pulses of the magnet passing the reed switch, at the same frequency that the counts were received? For example, a magnet mounted on a 2 inch dia shaft would turn slower past a reed switch than one mounted on a .5 inch shaft, or one could vary the speed of the magnet past the reed as they wish. So how does counter++ keep track of this freq? is it reading the attachinterupt pin (or is the function that is being called, keeping track) or does the ISR time stamp each pulse it receives and store that interval in the declared variable? so when the variable is used again, it has this interval stored in it?

To be more clear, if it takes one second for the magnet to complete one revolution, how does the MCU know it took one second and store this, along with the counts of the revolutions?

Thanks for any help

title: Arduino ISR timing question

Answers: 1

body:
All the interrupt does is count. It has no concept of time.  For instance:

    volatile uint32_t revolutions = 0;
    void count() {
        revolutions++;
    }
    ....
    attachInterrupt(0, count, FALLING);

will just count up 1 every time the interrupt triggers.

To be able to convert that count into something meaningful you have to manually introduce the concept of time - that is, the count of "revolutions" (for example) between two points in time.  And it's up to your sketch to implement that.

The simplest way may be:

    // For anything more than an 8 bit value on an 8 bit machine
    // make a critical section to save and reset the count
    cli();
    uint32_t savedResolutions = revolutions;
    revolutions = 0;
    sei();

    Serial.print(savedRevolutions);
    Serial.println(F(" revolutions per second"));

    // Introduce the concept of time - this will
    // make it get the count once a second.
    delay(1000);

Of course, instead of `delay()` you can use `millis()` in much the same way as the `BlinkWithoutDelay` example in the IDE.

It is possible (as long as you're not counting too fast) to incorporate the time element into the interrupt routine by keeping track of the time in a variable:

    volatile uint32_t rps = 0;

    void count() {
        static uint32_t revolutions = 0;
        static uint32_t timestamp = millis();

        revolutions++;

        if (millis() - timestamp >= 1000) {
            timestamp = millis();
            rps = revolutions;
            revolutions = 0;
        }
    }
    ....
    attachInterrupt(0, count, FALLING);

Then you can just reference the `rps` variable at any time to get the revolutions per second. Again it should really be queried inside a *critical section* to prevent the value being changed while you're actively reading it...

    cli();
    uint32_t myRPS = rps;
    sei();

    Serial.print(myRPS);
    Serial.println(F(" revolutions per second"));


body:
I've noticed that when using the USI interface on the ATTiny to send I2C via the methods from "Wire.h" with the ATTiny Arduino implementation included from the library manager ([ATTinyCore][1]), while `analogWrite` PWM on PB4 (Arduino pin 4, physical pin 3) works OK, it seems attempting to use it on PB1 (Arduino pin 1, physical pin 6) behaves erratically or hangs the processor.

Is this expected behavior, and is there a workaround? With the `SDA` line on PWM pin 0, physical pin 5 if that's the case it means when using the hardware USI to do I2C communications, I'm down to a single hardware PWM output, which is kind of a bummer.

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

  [1]: https://github.com/SpenceKonde/ATTinyCore
  [2]: https://i.stack.imgur.com/9LFZx.jpg

title: PWM output while using I2C with the ATTiny library

Answers: 1

body:
This is normal.

Timer0 is used as the clock source for the USI. It's the only internal clock source that can be used. The only other option is to use "software polled" mode where it's up to the sketch (or support library) to manually create the clock signal (less than desirable) by setting a bit in a register at the right time.

So you can only use Timer1 for your own (PWM) purposes while using the USI.


body:
I'm trying to read compare data from EEPROM (Arduino UNO). Reading is working fine but comparing it using the '==' operator is not working as expected.

    //string 'True' is already stored in EEPROM

    int addr = 0;
    char value = EEPROM.read(addr);

    Serial.println(value);// this line successfully prints the letter 'T'

    // but this function is not working
    if (value == "T") {
      Serial.println("foo");
    }

title: Reading and comparing data from Arduino Uno EEPROM

Answers: 1

body:
There is a HUGE difference between `"string"` and `'c' 'h' 'a' 'r'`.

You are comparing address of string `"T"` with the numerical value of character `'T'`.

The expression: `if (value == 'T')` will be much better.


body:
I have an infinite loop issue that keeps persisting in this code on my Teensy 3.1. This program is intended to take an input on Pin 0 and press the Enter key on the computer it is hooked into.

It is connected to a wire with no current but once a switch is flipped it should send a 5v Digital Signal blip to the Teensy and trigger it to run. It does function but it keeps getting caught in an infinite loop for some reason. Any help would be greatly appreciated!

    // Global Variable
    int signal_receiving_pin = 0;

    void setup() {
      // Outputting for error checking
      Serial.begin(38400);

      // Readying the pin for input
      pinMode(signal_receiving_pin, INPUT);
    }

    void loop()
    {
    // If statement to check whether an input has been received
    if (digitalRead(signal_receiving_pin) == HIGH)
    {
      // If the signal has been detected..
      Serial.println("The signal has been received \n");
      Serial.println("Now sending the ENTER signal \n");

      // .. The ENTER key is sent to the computer
      //Keyboard.press(KEY_ENTER);
      //Keyboard.release(KEY_ENTER);

      // Waiting 1 minute before allowing more input
      //delay(60000); // Pause
    }
    else
    {
      // If the signal is not detected..
      // it will let you know it isn't there
      Serial.println("Input not detected \n");
    }
    }

title: Infinite Loop on Pin Input (Teensy 3.1)?

Answers: 1

body:
Try using the internal Pullup/Pulldown resistor to control the input when the pin is not connected to anything.  If you do not have a pullup/pulldown, then the input capacitance on the input pin circuitry can sample and hold the 5V unreliably.

    ...
    void setup() {
      // Outputting for error checking
      Serial.begin(38400);

      // Readying the pin for input
      pinMode(signal_receiving_pin, INPUT_PULLDOWN);
    }
    ...

You may want to uncomment the delay() or add some state logic trigger only one activation per each cycle of `signal_receiving_pin`


body:
I'm new to these addressable LED things – I just received a 149-LED WS2812B strip today, and I'm experimenting with various approaches. Adafruit's own tutorial says the FastLED library is faster than their Adafruit_NeoPixel library, so I wanted to test their performance.

I'm running this code on a Nano clone:

    // Adafruit
    #include <Adafruit_NeoPixel.h>
    // FastLED
    #include <FastLED.h>
    // Common
    #define NUM_LEDS 149
    #define DATA_PIN 6

    // Adafruit initialization
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, DATA_PIN, NEO_GRB + NEO_KHZ800);
    const uint32_t adaBlack = strip.Color(0, 0, 0);
    const uint32_t adaWhite = strip.Color(255, 255, 255);

    // FastLED initialization
    CRGB leds[NUM_LEDS];

    void setup() {
      // Common
      delay(2000);

      // Adafruit setup
      strip.begin();

      // FastLED setup
      FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);

      // Common
      Serial.begin(57600);
    }

    void loop() {
      unsigned int adafruitMillis = adafruitLoop();
      unsigned int fastLedMillis = fastLedLoop();
      // Yes, this is ugly -- but it works every time
      Serial.print(adafruitMillis);
      Serial.print(",");
      Serial.println(fastLedMillis);
    }

    unsigned int adafruitLoop()
    {
      long unsigned startMillis = millis();
      for (int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed++) {
        strip.setPixelColor(whiteLed, adaWhite);
        strip.show();
        strip.setPixelColor(whiteLed, adaBlack);
      }
      return (unsigned int) millis() - startMillis;
    }

    unsigned int fastLedLoop()
    {
      long unsigned startMillis = millis();
      for(int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed++) {
        leds[whiteLed] = CRGB::White;
        FastLED.show();
        leds[whiteLed] = CRGB::Black;
      }
      return (unsigned int) millis() - startMillis;
    }

The results are totally disastrous for FastLED (shown in red):
[![FastLED is red, Adafruit's library in blue][1]][1]

Am I doing something wrong, or is FastLED winning on features, rather than on speed?

For the record, I did check whether the performance hit comes from setting the pixel values or from sending the data – FastLED is faster at setting the pixel values than Adafruit's library, but that doesn't matter because setting *two* pixel values takes 3 ms or less for the entire strip, regardless of the library. Sending the data to the strip takes most of the time, and that's where FastLED lags behind big time (900 ms compared to Adafruit's 200 ms).

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

title: NeoPixel library performance: Adafruit vs. FastLED

Answers: 2

body:
As I understand it, the *Fast* in *FastLED* isn't for sending the data, but for manipulating the array/data that holds the colors. The FastLED library contains many functions optimized for dealing with 8-bit unsigned integers for holding color values, including color addition, 8-bit scaling, partially-defined color palettes (for example, you define 8 waypoints in the palette, but can grab a color from the full 8-bit range and it interpolates on the fly using the fast 8-bit math.

Not just math, but also conversion to/from RGB and HSV realms, etc.

It supports pushing multiple strips at the same time (parallel) by writing to the whole `PORT` instead of just one pin of the 8-pin port, so if you split your strip into multiples, you can really make speed gains in writing to the LEDs.

body:
You can't rely on the timing reported by millis when comparing FastLED and Adafruit's neopixel library.  Writing out Neopixel data involves disabling interrupts, which is what the clock uses to advance.  FastLED accounts for this and attempts to update the system clock time after writing out led data to account for the amount of time that interrupts were disabled, but the adafruit NeoPixel library doesn't.  You need to use something else to compare timing.

(WS2812 data has a pretty strict data rate - 800khz, or about 30µs per rgb led)

(I should know, I wrote FastLED :)


body:
I'm trying to use a Nano v3 as ISP to program an atmega328p on a board with ISP headers:

I followed the instructions under
https://www.arduino.cc/en/Tutorial/ArduinoISP which I think have been recently updated. I'm simply connecting ISP headers together except for D10 from programmer to reset on the target AVR.

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

The ISP sketch seems to be working fine as far as I can see the heartbeat pulsing a led. But when trying to burn bootloader with settings:

    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x15
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x15

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x01
    avrdude: stk500_initialize(): (a) protocol error, expect=0x14, resp=0x10
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude: stk500_disable(): unknown response=0x12
    Error while burning bootloader.

<s>I noticed something weird though, the 5V and GND on the ISP header on the programmer nano only has around 0.4V. This even without anything external but the usb connected. Is my nano broken or is the usb connection not able to deliver enough power?</s>

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

title: Can't burn bootloader through Arduino Nano clone ISP to atmega328p

Answers: 2

body:
Your slave micro isnt resetting when your master wants it to reset.

Ie: master sends a reset signal before initiating further communication, and it seems that your slave not being reset.

So its not responding.

Once cross check your isp signal lines.

body:
Try adding the 10µF capacitor connected to `RESET` and `GND` on the board you are using as programmer (in this case, your Nano). This is required according to the [Documentation][1].

> The 10µF electrolytic capacitor connected to RESET and GND of the programming board is needed only for the boards that have an interface between the microcontroller and the computer's USB, like Mega, Uno, Mini, Nano.

I just encountered the exact same error output, and the capacitor solved it.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP#toc3


body:
I bought the BNO055 "smart" IMU from [Adafruit][1], thinking it would be a simple way to get orientation data for a small mobile robot project, but I've found the thing to be very difficult to use and nearly worthless.

It's advertised as being able to auto-calibrate, and although it does attempt to do this, I've found that the calibration doesn't hold. It continuously re-calibrates itself, and either gets stuck in an error state or find a successful calibration...but then loses it after a few seconds.

Is there anything I can do to improve its stability? Does it need to be mounted inside a special grounded housing? Is there a special incantation I should utter before powering it on?

I'm reading it from an Arduino Uno via I2C, and though the wiring and programming is relatively simple, getting it calibrated and staying calibrated I've found to be nearly impossible.

Even after the "system" flag says its fully calibrated, and I have the IMU just sitting on a table, not moving, after a minute, it loses its "system" calibration. The accelerometer, gryoscope, and magnetometer usually remain calibrated, but how can I trust them if the on-board fusion algorithm is reporting it's not ready?

If the BNO055 is a lost cause, is there anything better? I've tried several MPU-**** chips from InvenSense, but they're even worse.

  [1]: https://learn.adafruit.com/adafruit-bno055-absolute-orientation-sensor/overview

title: Getting stable measurements with the BNO055 IMU

Answers: 1

body:
Try a permanent calibration. From the [Adafruit forums][1]:

> You'd basically need to read and write data registers 55-6A. In both cases, you have to set the sensor in CONFIG_MODE. There's more information on page 48 of the [datasheet][2].

The magnetometer is influenced by surrounding magnetic sources like motors. You might be able to tell the extent of the effect using the [following method][1]:

> The System Calibration Status will start out at 0 and will go to 3
> when the sensor is calibrated. For example, the mag calibration status
> will go to 3 if you do some figure 8s. If you put a piece of metal
> near the sensor, the calibration status will drop to 0. But when the
> metal is moved away, it will go back to 3. You may be able to use this
> value as an indicator that calibration is lost. I have found that once
> it's calibrated, it seems to hold calibration well.

For getting solid readings out of the gyroscope, [this][3] might be helpful advice:

> I don't worry about scaling the gyro output on a per-sample basis. I simply sum the output into a 32 bit (or larger) integer register. I do subtract-out a null value at each sample, which I will talk about later. But essentially, if you sample your gyro at 1kHz, and sum the output into an accumulator, you will see that the value of that accum at any time will be directly proportional the angle of rotation. If your rate is set for 250 deg/sec, then a rotation of 180 deg will result in approximately 23330000 in the accumulator. I call that the GYRO_CAL number. So, at any given time the angle, in degrees, is deg = accum / GYRO_CAL * 180.
>
> Since the gyro output is linear, the accumulator is insensitive to
> whether the rotation is fast or slow (as long as the max deg/sec isn't
> exceeded).
>
> Here is my basic routine for each gyro reading:

`void read_FIFO(){
       sample = read_value_from_FIFO();   //read the latest z-axis sample. I use the fifo, but that isn't necessary
       accum += sample - null;           //add the sample to the sum and subtract the null
       if((accum > GYRO_CAL) -= GYRO_CAL*2;  //roll the accumulator at +180 deg.
       if((accum < -GYRO_CAL) += GYRO_CAL*2; // roll the accumulator at -180 deg.
       angle = accum/GYRO_CAL * 180;   // convert to degrees
}`

> I calculate the null at the beginning of each run. I sum 1000 readings
> and take the average. The gyro has to sit still for 3 or 4 seconds for
> this. The GYRO_CAL value can be calculated by summing the output while
> you rotate the gyro by 180 deg. Or you can sum over many turns, and
> divide by the number of 180 deg turns for a more accurate value.
>
> You could probably use a 64-bit FP for the accumulator, but since
> arduino only supports 32 bit FP, I found it absolutely necessary to
> use a 32 bit integer to avoid roundoff and other errors.
>
> If you follow that general outline, I promise you will get rock solid
> performance out of the gyro. There are a few other small optimizations
> that I make, which I can discuss later.

  [1]: https://forums.adafruit.com/viewtopic.php?f=19&t=73014
  [2]: https://cdn-shop.adafruit.com/datasheets/BST_BNO055_DS000_12.pdf
  [3]: https://groups.google.com/forum/#!topic/diyrovers/5CAeROsWLZ4


body:
I'm trying to write two strings to an Arduino Uno's EEPROM. Here, the first code block works fine: it writes string(True/False) at 'address 0'. But the second block, which writes data at 'address 5', is not working as expected.Reading data at address 5 prints a blank line. What am I missing here? Is this the correct way to write two different strings to EEPROM?

First code block:

    int state = LOW;
    char first_eeprom_value;
    if (state == LOW) {
      state = HIGH;
      char example_string[4] = "True";
      first_eeprom_value = EEPROM.read(0);
      Serial.println(first_eeprom_value);
      for (int i = 0 ; i < 5 ; i++) {
        EEPROM.update(i, example_string[i]);
      }
    } else {
      state = LOW;
      char example_string[5] = "False";
      first_eeprom_value = EEPROM.read(0);
      Serial.println(first_eeprom_value);
      for (int i = 0 ; i < 5; i++) {
        EEPROM.update(i, example_string[i]);
      }
    }
    Time = millis();

Second code block:

    char first_eeprom_value1;
    if (state1 == LOW) {
      state1 = HIGH;
      char example_string1[4] = "True";
      first_eeprom_value1 = EEPROM.read(5);
      Serial.println(first_eeprom_value1);
      for (int i = 5 ; i < 11 ; i++) {
        EEPROM.update(i, example_string1[i]);
      }
    } else {
      state1 = LOW;
      char example_string1[5] = "False";
      first_eeprom_value1 = EEPROM.read(5);
      Serial.println(first_eeprom_value1);
      for (int i = 5 ; i < 11 ; i++) {
        EEPROM.update(i, example_string1[i]);
      }
    }

    Time = millis();

    //reading data at address 5
    int addr = 5;
    char value = EEPROM.read(addr);
    Serial.println(value);// this prints blank line

title: Writing data to a specific address in EEPROM

Answers: 1

body:
You are cycling outside the string, thus creating undefined behavior.

Try replacing the second block with this:

    char first_eeprom_value1;
    if (state1 == LOW) {
      state1 = HIGH;
      char example_string1[4] = "True";
      first_eeprom_value1 = EEPROM.read(5);
      Serial.println(first_eeprom_value1);
      for (int i = 0; i < sizeof(example_string1); i++) {
        EEPROM.update(i + 5, example_string1[i]);
      }
    } else {
      state1 = LOW;
      char example_string1[5] = "False";
      first_eeprom_value1 = EEPROM.read(5);
      Serial.println(first_eeprom_value1);
      for (int i = 0; i < sizeof(example_string1); i++) {
        EEPROM.update(i + 5, example_string1[i]);
      }
    }

Please note that this is not optimal; I suggest you to use fixed-length strings, and fill the unused spaces with blanks or 0s, so you can read back all the bytes you wrote in a safe way


body:
I'm using a Mega 2560 and Uno and want to input text to the serial monitor which can be stored in character array char in[];
I want array specifically as I'll be breaking each character to trigger different code for making a morse code.

        #include<Arduino.h>
    //#include<Softwareserial.h>

    int Speaker1 = 4;
    int Speaker2 = 6;
    int LED = 2;
    int Relay = 12;
    char n = '0';
    char in[];
    //int outPins[] = { 2, 4, 6, 8 };

    void high() {

      digitalWrite(Speaker1, HIGH);
      tone(Speaker2, 800);
      digitalWrite(LED, HIGH);
      digitalWrite(Relay, HIGH);

    }

    void low() {

      digitalWrite(Speaker1, LOW);
      tone(Speaker2, 800);
      digitalWrite(LED, LOW);
      digitalWrite(Relay, LOW);

    }

    void setup() {

      Serial.begin(9600);

      pinMode(Speaker1, OUTPUT);
      pinMode(Speaker2, OUTPUT);
      pinMode(LED, OUTPUT);
      pinMode(Relay, OUTPUT);

      Serial.print("Enter your desired text: ");
      //in = Serial.readString();  /*<-------------HELP NEEDED HERE */

      for (int i = 0; i < strlen(in); i++) {

        n = in[i];

        switch (n) {

          case 'A':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'B':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'C':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'D':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'E':
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'F':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'G':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'H':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'I':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'J':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'K':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'L':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'M':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'N':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'O':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'P':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'Q':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'R':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'S':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case 'T':
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'U':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'V':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'W':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'X':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'Y':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case 'Z':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case ' ':
            delay(700);
            break;
          case '1':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case '2':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case '3':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case '4':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;
          case '5':
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case '6':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case '7':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case '8':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case '9':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(100);
            low();
            delay(300);
            break;
          case '10':
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(100);
            high();
            delay(300);
            low();
            delay(300);
            break;

        }

      }

    }

    void loop() {

    }

title: How to input text from Serial monitor into a character array?

Answers: 2

body:
I don't understand exactly why your signals are much different from 'real' morse code, e.g. A is .-

Instead of calling each high and low separately like the 'a' for example:

      case 'A':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;

call it like this:

    case 'A':
      send2(false, true); /* means .-
      break;

Than create a function send2 which sends a . and a -
Something like:

    void send2(bool b1, bool b2)
    {
       send(b1);
       send(b2);
       delay(300); /* Extra wait in between characters */
    }

For characters needing 1, 3 or 4 characters, you can make send 1, send3 and send4 accordingly.

    void send(bool b1)
    {
       digitalWrite(Speaker1, b1 ? HIGH : LOW);
       tone(Speaker2, b1 ? 800);
       digitalWrite(LED, HIGH);
       digitalWrite(Relay, HIGH);
       delay(b1 ? 300 : 100); /* Assuming HIGH needs delay of 300 and low of 100 */
    }

    void low() {

      digitalWrite(Speaker1, LOW);
      tone(Speaker2, 800); /* I would expect two different values for HIGH and LOW */
      digitalWrite(LED  , b1 ? HIGH : LOW);
      digitalWrite(Relay, b1 ? HIGH : LOW);
    }

body:
I suggested in a comment you read the blog post [Reading Serial on the
Arduino][read serial]. In this post, Majenko shows a `readline()`
function that does almost exactly what you want. This function is
non-blocking, which, in the embedded world, is most of the time a
mandatory feature. However, in one of your comments you wrote that you
want a blocking function:

> I need the program to "wait" like [...] `scanf`

Degrading a non-blocking function into a blocking one is as easy as
wrapping the non-blocking function in a loop. Here is a code snippet for
reading a CR-terminated string, which is similar to a blocking version
of Majenko's `readline()`:

    char buffer[80];
    size_t pos = 0;
    for (;;) {
        int c = Serial.read();
        if (c == -1) continue;   // no input
        if (c == '\r') {         // end of line
            buffer[pos] = '\0';  // terminate the string
            break;
        }
        if (pos < sizeof buffer - 1) {
            buffer[pos++] = c;
        }
    }

That being said, I could not resist the temptation to brutally simplify
your program. The key to the simplification is to consider the Morse
code as a _data structure_. Then, the code for keying a string is
generic: you look up each character in the code table and key it in
turn. This saves the long `switch`/`case`:

    struct code_t {
        char c;
        const char *code;
    };

    static const code_t morse_code[] = {
        {'A', ".-"   }, {'B', "-..." }, {'C', "-.-." }, {'D', "-.."  },
        {'E', "."    }, {'F', "..-." }, {'G', "--."  }, {'H', "...." },
        {'I', ".."   }, {'J', ".---" }, {'K', "-.-"  }, {'L', ".-.." },
        {'M', "--"   }, {'N', "-."   }, {'O', "---"  }, {'P', ".--." },
        {'Q', "--.-" }, {'R', ".-."  }, {'S', "..."  }, {'T', "-"    },
        {'U', "..-"  }, {'V', "...-" }, {'W', ".--"  }, {'X', "-..-" },
        {'Y', "-.--" }, {'Z', "--.." },
        {'1', ".----"}, {'2', "..---"}, {'3', "...--"}, {'4', "....-"},
        {'5', "....."}, {'6', "-...."}, {'7', "--..."}, {'8', "---.."},
        {'9', "----."}, {'0', "-----"},
        {' ', " "    }, {'\0', NULL}  // sentinel
    };

    static inline void high() { digitalWrite(LED_BUILTIN, HIGH); }
    static inline void low()  { digitalWrite(LED_BUILTIN, LOW);  }

    // Key a string in Morse.
    void key(const char *s)
    {
        for (; *s; s++) {  // *s = current letter

            // Find this letter's code.
            const code_t *p;
            for (p = morse_code; p->c; p++) {
                if (p->c == toupper(*s)) break;  // found
            }
            if (!p->c) continue;  // not found -> ignore

            // Send this code's symbols.
            for (const char *code = p->code; *code; code++) {
                if (*code != ' ')
                    high();
                switch (*code) {
                    case ' ': delay(100); break;
                    case '.': delay(100); break;
                    case '-': delay(300); break;
                }
                low();
                delay(100);
            }
            delay(200);  // inter-letter spacing = 300 ms
        }
    }

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

    void loop()
    {
        // Read a string.
        char buffer[80];
        size_t pos = 0;
        for (;;) {
            int c = Serial.read();
            if (c == -1) continue;   // no input
            if (c == '\r') {         // end of line
                buffer[pos] = '\0';  // terminate the string
                break;
            }
            if (pos < sizeof buffer - 1) {
                buffer[pos++] = c;
            }
        }

        // Key it in Morse.
        key(buffer);
    }

Note that this program reads CR-terminated strings from the Serial port
and keys them on the builtin LED. If you want your program to work on a
single string, you can call `exit()` at the end of `loop()` or,
alternatively, merge `loop()` into `setup()` and provide an empty
`loop()`.

[read serial]: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/


body:
I checked several related posts but couldn't solve my problem.

I have Antergos Linux :

    # uname -a
    Linux biutitude 4.14.11-1-ARCH #1 SMP PREEMPT Wed Jan 3 07:02:42 UTC 2018 x86_64 GNU/Linux
The board is a Seeeduino Lorawan.

The problem is that the menu to select the port is greyed, and when I check in /dev I don't see any new tty when I plug the card. However the card blinks.

I tried :
- adding myself to lock + tty + uucp (and restarted my session)
- created a dialout group because I didn't have one, added myself to it
- loading cdc_acm module but got the following error :

    # modprobe cdc_acm
    modprobe: FATAL: Module cdc_acm not found in directory /lib/modules/4.14.11-1-ARCH
Thus I tried :

    [root@biutitude biu]# depmod -ae
    depmod: WARNING: -e needs -E or -F
    depmod: ERROR: could not open directory /lib/modules/4.14.11-1-ARCH: No such file or directory
    depmod: FATAL: could not search modules: No such file or directory
    [root@biutitude biu]# depmod
    depmod: ERROR: could not open directory /lib/modules/4.14.11-1-ARCH: No such file or directory
    depmod: FATAL: could not search modules: No such file or directory

I'm clearly out of ideas. The weirdest is that a few months ago, I was able to use a RFduino card without any trouble.

title: No ttyACM0 nor ttyUSB0

Answers: 1

body:
My solution - install linux-modules-extra kernel module on ubuntu 20.04. Solved my problem which was identical.

Get OS details:

    uname -a
    Linux seeeduino-node 5.4.0-91-generic #102-Ubuntu SMP Fri Nov 5 16:31:28 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

Install the sudo apt install linux-modules-extra:

    sudo apt install linux-modules-extra-<kernel-version>

Example:

    sudo apt install linux-modules-extra-5.4.0-91-generic

You need to reboot the machine afterwards it should work.


body:
I have just bought a [16x2 LCD display with buttons][1]. I can get the display to work and do various basic sketches included in the Arduino IDE. However, I cannot figure out how to control the buttons.

The buttons work using analog pin 0 and from what I was able to understand from what I have read online, it is something to do with the values you receive when the buttons are pressed. I can't seem to find out what values mine gives, I have found a sketch that is supposed to map the buttons, but I cannot get it to work, as I don't really understand what it is doing, I am very new to this.

The code I am using is as follows:

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

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    int lcd_key     = 0;
    int adc_key_in  = 0;

    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5

    int read_LCD_buttons() {
      adc_key_in = analogRead(0);
      if (adc_key_in > 1000) return btnNONE;
      if (adc_key_in < 50)   return btnRIGHT;
      if (adc_key_in < 250)  return btnUP;
      if (adc_key_in < 450)  return btnDOWN;
      if (adc_key_in < 600)  return btnLEFT;
      if (adc_key_in < 920)  return btnSELECT;
      return btnNONE;
    }

    void setup() {
      lcd.begin(16, 2);
      lcd.setCursor(0,0);
      lcd.print("Push the buttons");
    }

    void loop() {
      lcd.setCursor(9, 1);
      lcd.print(millis()/1000);
      lcd.setCursor(0, 1);
      lcd_key = read_LCD_buttons();
      switch (lcd_key) {
        case btnRIGHT: {
          lcd.print("RIGHT ");
          break;
        }
        case btnLEFT: {
          lcd.print("LEFT   ");
          break;
        }
        case btnUP: {
          lcd.print("UP    ");
          break;
        }
        case btnDOWN: {
          lcd.print("DOWN  ");
          break;
        }
        case btnSELECT: {
          lcd.print("SELECT");
          break;
        }
        case btnNONE: {
          lcd.print("NONE  ");
          break;
        }
      }
    }

If anyone can give me any pointers it would be greatly appreciated.

Liam

  [1]: https://www.amazon.co.uk/gp/product/B01EYW5R5M/

title: How do I control the buttons on an Arduino LCD keypad shield?

Answers: 2

body:
I have found an easy way to do this, i found a tutorial [on instructables][1] that has explained in detail what to do, i then applied this to my LCD keypad shield rather than external buttons on a breadboard.

All you have to do to see what the results are for your particular buttons is to load the sketch below onto your board then open the serial mapper on the arduino ide, simply press the buttons and you should see the results.

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

     /*
      Debounce

      Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
      press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
      a minimum delay between toggles to debounce the circuit (i.e. to ignore
      noise).

      created 28 October 2009
      by Riaan Cornelius

      */

     // constants won't change. They're used here to
     // set pin numbers:
     const int buttonPin = 0;     // the number of the pushbutton pin
     const int ledPin =  53;      // the number of the LED pin for testing

     const int BUTTON1 = 1;
     const int BUTTON2 = 2;
     const int BUTTON3 = 3;
     const int BUTTON4 = 4;
     const int BUTTON5 = 5;

     const int BUTTON1LOW = 970;
     const int BUTTON1HIGH = 1024;
     const int BUTTON2LOW = 850;
     const int BUTTON2HIGH = 950;
     const int BUTTON3LOW = 700;
     const int BUTTON3HIGH = 800;
     const int BUTTON4LOW = 400;
     const int BUTTON4HIGH = 650;
     const int BUTTON5LOW = 250;
     const int BUTTON5HIGH = 350;

     // Variables will change:
     int ledState = HIGH;         // the current state of the output pin
     int buttonState;             // the current reading from the input pin
     int lastButtonState = LOW;   // the previous reading from the input pin

     // the following variables are long's because the time, measured in miliseconds,
     // will quickly become a bigger number than can be stored in an int.
     long lastDebounceTime = 0;  // the last time the output pin was toggled
     long debounceDelay = 50;    // the debounce time; increase if the output flickers

     void setup() {
       pinMode(buttonPin, INPUT);
       pinMode(ledPin, OUTPUT);
       Serial.begin(9600);
     }

     void loop() {
       // read the state of the switch into a local variable:
       int reading = analogRead(buttonPin);
       Serial.println(reading);

       /*
       Not needed while getting the values.

       int tmpButtonState = LOW;             // the current reading from the input pin

       if(reading>BUTTON5LOW && reading<BUTTON5HIGH){
         //Read switch 5
         tmpButtonState = BUTTON5;
       }else if(reading>BUTTON4LOW && reading<BUTTON4HIGH){
         //Read switch 4
         tmpButtonState = BUTTON4;
       }else if(reading>BUTTON3LOW && reading<BUTTON3HIGH){
         //Read switch 3
         tmpButtonState = BUTTON3;
       }else if(reading>BUTTON2LOW && reading<BUTTON2HIGH){
         //Read switch 2
         tmpButtonState = BUTTON2;
       }else if(reading>BUTTON1LOW && reading<BUTTON1HIGH){
         //Read switch 1
         tmpButtonState = BUTTON1;
       }else{
         //No button is pressed;
         tmpButtonState = LOW;
       }

       // check to see if you just pressed the button
       // (i.e. the input went from LOW to a buttonState),  and you've waited
       // long enough since the last press to ignore any noise:

       // If the switch changed, due to noise or pressing:
       if (tmpButtonState != lastButtonState) {
         // reset the debouncing timer
         lastDebounceTime = millis();
       }

       if ((millis() - lastDebounceTime) > debounceDelay) {
         // whatever the reading is at, it's been there for longer
         // than the debounce delay, so take it as the actual current state:
         buttonState = tmpButtonState;
         Serial.println(buttonState);
       }

       // save the reading.  Next time through the loop,
       // it'll be the lastButtonState:
       lastButtonState = tmpButtonState;

       // set the LED using the state of the button for testing:
       switch(buttonState){
         case BUTTON1:
         digitalWrite(ledPin, buttonState>0);
         break;
         case BUTTON2:
         digitalWrite(ledPin, buttonState>0);
         break;
         case BUTTON3:
         digitalWrite(ledPin, buttonState>0);
         break;
         case BUTTON4:
         digitalWrite(ledPin, buttonState>0);
         break;
         case BUTTON5:
         digitalWrite(ledPin, buttonState>0);
         break;
       }
       */
     }

Liam
  [1]: http://www.instructables.com/id/How-to-access-5-buttons-through-1-Arduino-input/

body:
Upload this and it will read the resistance of your buttons on the lcd screen

    /*  /*
    Arduino 2x16 LCD Detect Buttons
    resistance
    */

    #include <LiquidCrystal.h>

    //LCD pin to Arduino
    const int pin_RS = 8;
    const int pin_EN = 9;
    const int pin_d4 = 4;
    const int pin_d5 = 5;
    const int pin_d6 = 6;
    const int pin_d7 = 7;

    const int pin_BL = 10;

    LiquidCrystal lcd( pin_RS,  pin_EN,  pin_d4,  pin_d5,  pin_d6,  pin_d7);

    void setup() {

      lcd.begin(16, 2);

      lcd.setCursor(0,0);

      lcd.print("  Press Any Key ");
      lcd.setCursor(0,1);
      lcd.print("Resistance:");
    }

    void loop() {
      int x;
      x = analogRead (0);
      lcd.setCursor(12,1);
      lcd.print (analogRead (0));
      lcd.print("                ");
      delay (500);
      }


body:
I'm trying to manually add board definitions in a boards.txt file in hardware subfolder of my sketches folder as per instructions here for instance: https://www.arduino.cc/en/Tutorial/ArduinoISP

They however do NOT show up in my board selection.

My sketches location where hardware subfolder should be placed:

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

Board defs:

    ~/D/Arduino ❯❯❯ cat ~/Documents/Arduino/hardware/boards.txt
    ##############################################################

    atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

    atmega328bb.upload.protocol=arduino
    atmega328bb.upload.maximum_size=30720
    atmega328bb.upload.speed=57600

    atmega328bb.bootloader.low_fuses=0xE2
    atmega328bb.bootloader.high_fuses=0xDA
    atmega328bb.bootloader.extended_fuses=0x05

    atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
    atmega328bb.bootloader.unlock_bits=0x3F
    atmega328bb.bootloader.lock_bits=0x0F

    atmega328bb.build.mcu=atmega328p
    atmega328bb.build.f_cpu=8000000L
    atmega328bb.build.core=arduino:arduino
    atmega328bb.build.variant=arduino:standard

    atmega328bb.bootloader.tool=arduino:avrdude
    atmega328bb.upload.tool=arduino:avrdude

BUT nothing show here:

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

I have restarted Arduino IDE.

  [1]: https://i.stack.imgur.com/mYV8B.png
  [2]: https://i.stack.imgur.com/Qd3Af.png

title: Manually added boards doesn't work in 1.8.5…?

Answers: 1

body:
Newer versions of the IDE (after 1.5) have a different folder structure where there is additional subfolders for maintainer and architecture.

    <Arduino sketch folder>/hardware/<custom name>/avr/boards.txt

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification


body:
I am concerned whether I need to use a voltage divider to power my ESP8266 module. My concerns stem from the warnings that I have heard in multiple tutorials. Everyone seems to regard the ESP8266 as being very sensitive to supply voltage.

Has anyone use the ESP8266 with an supply voltage greater than 3.5 V? What were the effects? Is it even necessary to make a voltage divider?

I am asking because my application has limited real estate.

title: Can I power ESP8266 with more than 3.5 V?

Answers: 4

body:
The [datasheet][1] usually is definitive on the allowable range of voltages.

Look in Section 5.1: Electrical Characteristics.

Working Voltage Value:
----------------------

 - Min: 2.5 V
 - Typical: 3.3 V
 - Max: 3.6 V

If you have to feed in signals that could go higher than 3.3 V in normal operation, you need to either clamp it with Zener diodes, or use a voltage divider.

If you are asking about powering the chip with more than 3.3 V, don't. You can get away with a 3.3 V linear regulator and 2 capacitors so that you are powering it with no more than designed supply voltage.

  [1]: http://www.espressif.com/sites/default/files/documentation/0a-esp8266ex_datasheet_en.pdf

body: The result to apply more voltage to a circuit is that the components will be burn. The same if you apply for a long time the maximum voltage. So the board works at 3.3v, your source maybe fluct between that but you will burn it if you apply 3.6 or more as a regular voltage.

body:
I have 4 pieces of ESP01-S with DHT11 that connect to the WiFi every 30 minutes and send temperature data and then go into DeepSleep.  In addition, an ESP01-S as a motion detector and one as a push button.  These two usually in DeepSleep.
 All are directly connected to a Li-Ion battery as power supply.  This has been running for over a year (except for changing the battery) and so far I haven't had any problems

body:
Usually ESP8266 **modules** have an onboard voltage regulator, USB connector and a pin labeled **5V**. This pin or the USB cable certainly tolerate resp. need a 5V power supply.

The ESP8266 controller itself will not survive 5V, neither at the Vcc nor at the signal pins.

BTW: a voltage divider (two resistors) is ok for signals, but does not help with the power supply.


body:
I connected a 16x2 LCD display to a Arduino Uno. Then I tested a "Hello, Word" code and it works perfect.
Now I want to do the same with a Wemos D1 Mini but it doesn't work.

Here the Wemos is not connected to USB:

[![16x2 LCD connected to Wemos (front)][1]][1]
[![16x2 LCD connected to Wemos (rear)][2]][2]

This os the "Hello, World" code. I needed to change the name of the pins (maybe this is the problem):

    #include <LiquidCrystal.h>

    const int rs = 8, en = 7, d4 = D5, d5 = D4, d6 = D3, d7 = D2;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

    void setup() {
      lcd.begin(16, 2);
      lcd.print("hello, world!");
    }

    void loop() {
      lcd.setCursor(0, 1);
      lcd.print(millis() / 1000);
    }

This is the result (potentiometer works perfect):

[![Display is on but empty][3]][3]

  [1]: https://i.stack.imgur.com/AKoz9.jpg
  [2]: https://i.stack.imgur.com/oReLJ.jpg
  [3]: https://i.stack.imgur.com/HvGDf.jpg

title: Wemos: 16x2 display doesn't show anything

Answers: 3

body:
Three possibilities (it's impossible to be more accurate from your description):

1. The display isn't wired to the pins you specified in your sketch
2. The display doesn't accept 3.3V signals when run from 5V
3. The display doesn't function when run from 3.3V

It's certainly not being initialized, which tells me that the instructions for setting it up aren't getting through, or aren't being executed when they do get through.

You can:

1. Use an oscilloscope or logic analyzer to confirm the right pins are in use,
2. Try powering the display from 3.3V if it's currently powered by 5V
3. Try powering the display from 5V if it's currently powered by 3.3V

If it's powered by 5V you may want to consider adding some logic level translation to boost the IO signals from the Wemos to 5V.

body:
You are doing it on wemos d1 mini isnt it ?

Then you dint include its header files,
Did you check the "LiquidCrystal.h" has definitions for wemos pinouts?

Your lcd is fine, n wemos too, its just your configuration is wrong.

Check those and update here.

body:
Although an old question, i just ran into the excat same issue.
The problem is that the pin numeration on the wemos D1 isn't the same as on the arduino.
I've followed the liquid crystal arduino tutorial but changed the numeration of the pins to
```
const int rs = 12, en = 13, d4 = 14, d5 = 4, d6 = 5, d7 = 16;
```
Now, at least for me, the display works as it should


body:
I have the following Arduino code for configuring a wifi connection through a simple webpage:

I declare `char* ssid;`. Later I read a value from a SPIFFS config file where `q_ssid` is declared as a string and successfully populated from the file:

    strncpy(ssid, q_ssid.c_str(), 10);

In the line above, I am limiting it to exactly 10 as that is the length of my wifi AP name that this connects to. If I change the initial `char*` to `char ssid[10];`, all works well, but SSIDs can have varying names, and if I do not use 10 chars, then the trailing spaces prevent connection in the statement `WiFi.begin(ssid, password);`.

On the web client handler that reads in values from the user, I use this:

    String q_ssid = server.arg("ssid");
    strncpy(ssid, q_ssid.c_str(), 10 );

How can I dynamically assign the size of `char* ssid;` so that it can be used with the correct number of characters for the AP name that the user has stored from the webpage?

Any help is greatly appreciated.

Thanks.

title: Char* and string conversion from an ESP8266 web server

Answers: 1

body:
What you need to do is creating a fixed string, this can be done in two ways:

static:

    char ssid[100];

Where 100 is the maximum length ever possible. Note that this will always use up 100 bytes, even if less are used (e.g. your string length is 5.
dynamic:

    char* p_ssid = malloc(100);

This way a pointer is created to a dynamically created string that can hold 100 characters. Disadvantage is that using malloc in a microcontroller can cause empty memory 'holes' when freeing/mallocing a lot.

With either way you can than use a normal strncpy or strcpy (in first case use &ssid to get a pointer to the ssid).
Also don't forget to add 1 to the length because of the trailing \0 to denote the string is ended.
Thus for storing 10 characters, you need an 11 char sized array.


body:
I am using GPRS GSM A6 with arduino uno to post data to web server. After sending AT commands to module I get OK response after every command,

    AT+CIPMUX=0

    OK
    AT+CGATT=1

    OK
    AT+CSTT="internet","",""

    OK
    AT+CIICR

    OK
    AT+CIFSR

    10.65.87.210

    OK
    AT+CIPSTART="TCP","xxx.xxx.xxx.xxx", 80

    CONNECT OK

    OK
    AT+CIPSEND

    > POST http://xxx.xxx.xxx.xxx/Code/ HTTP/1.1
    Host: xxx.xxx.xxx.xxx
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 18

    Data=GPS Data Sent
    AT+CIPCLOSE

    >

To terminate AT+CIPSEND you have to send CTRL-Z. I am sending CTRL-Z using this statement in code,

    Serial.write(0x1A)

But the module doesnot respond to this, and treats the next command (AT+CIPCLOSE) as data.

Please Help... Thanks in Advance!!!

title: Problem in AT+CIPSEND(CTRL-Z) GPRS GMS A6

Answers: 2

body:
RTFM: https://github.com/espressif/esp8266_at/wiki/CIPSEND

You need to close the input steam with "+++" to return to command mode.

body:
To terminate AT + CIPSEND just apply the next command:

    Serial.write(26);
or

    gsm.write(26);

where gsm is the UART channel of gsm module.