body:
I'm pulling together a project for my class where students build a solar panel structure/frame that moves with the sun to capture more power than if the panel were just flat on the roof.

I can handle controlling the motors, but I wanted some help to make sure I safely/accurately measured power.

I have an Arduino (the model isn't especially important), a 12 V deep cell battery, and 6 V solar cells. Obviously I don't want to hook the cells straight to an analog pin, but I came up with the schematic below. The wire to the battery will go through the CT (the inductor) to get current in order to calculate power.

Would the battery still charge even if the cells are only producing, say, 8 V? Am I overlooking anything  or is there any circuit protection I need to include? Maybe a computer fan as a load on the battery and to cool everything?  Any help is appreciated.

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

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

title: Measuring solar power with an Arduino

Answers: 4

body:
> Would the battery still charge even if the cells are only producing, say, 8V

Only if the battery is below 8V.

> Am I overlooking anything

Yes. Current transformers require a load resistance and bias voltage to convert a current measurement into a voltage the ADC can measure.

body:
Just a few points:

 - You can't measure DC current with a coil; you would need a Hall-effect sensor;
 - The charging current and the voltage you measure will depend on the state-of-charge of the battery, making it difficult to compare measurements;
 - You can't fully charge a nominally 12 V battery with a 12 V solar panel; a 12 V lead-acid battery with the panel you mention in the comments should work;
 - You need at least a diode between solar panels and battery, and possibly a proper charger, depending on the chemistry and capacity of the battery and the maximum charging current; maximum charging current for a 12 V, 9 Ah lead-acid battery is about 1 A if you stay on the very safe side, so the panel you mention should be OK; just don't overcharge the battery;
 - You need to be sure the battery voltage doesn't exceed 12 V by too much, or the voltage divider will put more than 5 V on the Arduino's input pin and fry it. Nominally 12 V lead-acid batteries are usually charged to about 14 V, and the solar panel you mention can get there. This would put 5.6 V on the Arduino input pin with the resistor values you use in your voltage divider.

Also have a look here: [Measure power of solar cell with an esp8266][1].

  [1]: https://electronics.stackexchange.com/questions/530562/measure-power-of-solar-cell-with-an-esp8266

body:
Use something like a 1NA169 'high side' current sensor, like this [Sparkfun module][1] instead of a resistor or inductor.  Much more accurate, and it can be placed on the 'high side' of the power circuit - very handy.

  [1]: https://learn.sparkfun.com/tutorials/ina169-breakout-board-hookup-guide/all

body: I have done something similar on my boat. This has a 12v car battery and a solar panel charger that can generate upto 20v in bright sunshine. I used a 3:1 potential divider so that the voltage supplied to the Arduino input is never more than 5v.


body:
I'm getting my first steps on Arduino and I'm trying to do an exercise where I have to draw a graph bar in a 16x2 LCD that indicates the values read from a vector of 16 integer elements amplified by the value read from a potentiometer (connected to the analog pin A0) during runtime. The graph should change in real-time as I move the cursor of the potentiometer to the left or right.

I have the following code structure:

> void loop() {
>
> // Read the 16 vector elements and map then to the screen height ...
>
> // Print out their values multiplied by the value read form the potentiometer, to the serial monitor ...
>
>// Draw a bar for each one of the vector elements (you will have 16 bars in the end)...
>
>// If the graph has reached the screen edge do not amplify it anyfurther. If it has reached the bottom, do the same
>
>//Wait a bit. Start drawing everything from scratch.

So far what I have is:

    #include<LiquidCrystal.h>

    // Create an LCD object and connect control wires

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    int vector[16] = {3, 7, 10, 15, 28, 12, 43, 1, 6, 19, 29, 23, 54, 76, 57, 66};

    int value=0;

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

      // Specify the LCD's number of columns and rows

      lcd.begin(16, 2);
    }

    void loop(){

      value = analogRead(A0);

      for(int i=0; i<16; i++){
        int vector2[i] = map(vector[i], 0, 1024, 0, 20);
        Serial.println(vector2[i]*value);
      }
    }

However I'm getting the following error so far:

     In function 'void loop()':
    28:25: error: array must be initialized with a brace-enclosed initializer
     exit status 1

Also I can't think of a way to do the last 3 steps of the code structure I have.
I know that if i would want to print a bar like a character I could do:

    #include<LiquidCrystal.h>

    // Create an LCD object and connect control wires

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    byte bar[] ={B11111, B11111, B11111, B11111, B11111, B11111, B11111, B11111};

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

      // Specify the LCD's number of columns and rows

      lcd.begin(16, 2);
      lcd.createChar(0, bar);
    }

    void loop(){
    lcd.setCursor(0,0);
    cd.write(byte(0));

    }

But even this would only print a column in the first row and column and not in both rows and first column of the LCD.

Can someone help me with the error I already have and give me some lights on how to do the last 3 steps of the code structure?

title: Drawing a bar graph in a LCD

Answers: 1

body:
First off you're going to need to define some custom characters. There's examples for how to do that.  You want characters that gradually fill up from the bottom to full, such as:

▁ ▂ ▃ ▄ ▅ ▆ ▇ █

Now, you have 8 lines per character and two lines of characters, which gives you a possible drawing range of 0-16. So you need to [`map`](https://www.arduino.cc/reference/en/language/functions/math/map/) your maximum range into that 0-16 span.

Finally you want to create a function to draw a single bar. This will take two parameters - the position of the bar (x) and the height of the bar (y). A simple little bit of mathematics later and you can work out what to print in the upper and lower characters.

* If the value is = 0:
  * Both top and bottom are spaces
* If the value is <= 8:
  * The bottom character is the one with the same number of lines as the value
  * The top character is empty.
* If the value is > 8:
  * The bottom character is the one with all 8 lines filled
  * The top character is the one with the value - 8 number of lines filled.

So you may end up with something like (note - untested):

```c++
const uint8_t bars[8][8] = {
    { 0, 0, 0, 0, 0, 0, 0, 0xff },
    { 0, 0, 0, 0, 0, 0, 0xff, 0xff },
    { 0, 0, 0, 0, 0, 0xff, 0xff, 0xff },
    { 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff },
    { 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff },
    { 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff },
    { 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff },
    { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff },
};

void setup() {
    // other stuff, like setting up the LCD...

    for (uint8_t i = 0; i < 8; i++) {
        lcd.createChar(i, bars[i]);
    }
}

void drawBar(uint8_t x, uint8_t y) {
    char top, bot;

    if (y == 0) { // Both spaces
        top = ' ';
        bot = ' ';
    } else if (y <= 8) { // Bottom has bar graph, top is empty
        top = ' ';
        bot = val - 1; // Characters start at 0, so 1-8 is 0-7
    } else if (y <= 16) { // Bottom is full, top has bar graph
        top = (y - 9); // Characters start at 0, so 9-16 is 0-7
        bot = 7;
    } else { // Overflow - both top and bottom full
        top = 7;
        bot = 7;
    }

    lcd.setCursor(x, 0);
    lcd.write(top);
    lcd.setCursor(x, 1);
    lcd.write(bot);
}

void loop() {
    // your stuff in here
}
```

Then to draw a bar you just call `drawBar` 16 times:

```c++
for (uint8_t i = 0; i < 16; i++) {
    uint8_t y = <your calculation on vector2[i] here>
    drawBar(i, y);
}
```

If you've done it right you should end up with something like:

```
▁█ ▄ ▆█▇   ▃ ▃▇
██▃█▇███▅▆▇█▆██▃
```


body:
As a novice, I would like to create a small breadboard with 5 items on it. 3 toggle buttons, and two constant spin (ie. no stop at 360 degrees) knobs.

Is then like the bottoms to send what ever key stroke (single key pee click) to the pc as if it was from a keyboard (maybe even a shift+key?)

And the knobs send keystrokes too. On each “click” as I don’t want smooth knobs. Ones that kinda of click per degree. Not sure how to explain that.

It’s for Flight Simulator. Doing it with a mouse, from distance, with small buttons is challenging. And twisting knobs with the mouse in bumpy conditions is even worse.

So planning on using my Nana, connected to a USB port for
Power and signal.

Can anyone guide me in the right direction? Would I need 3rd party software to convert signals to keystrokes on the pc?

I think there is a keyboard library - but from what I read, it takes over your keyboard. That is, once the Arduino is connected and listening - the main keyboard no longer functions. Is that a misunderstanding? I need both to be operational.

I’m guessing something like this as it has “positions”.
https://www.ebay.com.au/itm/Rotary-Encoder-Module-Arduino-Compatible/232624628710?hash=item36298223e6:g:JIIAAOSwg31aVFVW

title: Button and twist knob to send keystroke to PC

Answers: 2

body:
> As a novice, I would like to create a small breadboard with 5 items on it. 3 toggle buttons, and two constant spin (ie. no stop at 360 degrees) knobs.

Those knobs are called "Rotary Encoders".

> Is then like the bottoms to send what ever key stroke (single key pee click) to the pc as if it was from a keyboard (maybe even a shift+key?)

Then you really want an Arduino with a "native" USB connection, like the Leonardo or Micro.

> Can anyone guide me in the right direction? Would I need 3rd party software to convert signals to keystrokes on the pc?

Not with a Micro or Leonardo - you just use the `Keyboard.h` library.  If you want to use your Nano then yes, you can only talk serial, and you will have to have some third party software that interprets serial commands and injects keyboard signals into your OS.  I think there's some Python projects around that do that kind of thing. Or there is "professional" software, like [232key](https://www.232key.com/) that can do it for you.

body:
The twisty click per degree thing is called a rotary encoder.

You can already send serial commands to a computer, so to keep it simple, I'd try to find a way of turning the serial commands into a keyboard click.


body: My new Uno wifi rev2 just arrived and I have one problem.  At the beggining I connected my board via USB and tested with example blink program from WifiNiNA and It worked fine.  When program is runned and I plug in DC power suply and take off USB, my program is still working. And here is my problem. I'm wondering how I can send program/sketch to my arduino without usb just through WIFI. Is it possible? How I can do it?

title: Uno Wifi Rev2 - sending program via WIFI

Answers: 0


body: I have an Arduino Nano 33 IOT and it uses BLE. I want it to talk to my Pi 3B+ and send all of its sensor data. I cannot figure out a way to do it using Python for the Pi and ArduinoBLE library for my Nano IoT. Is it possible?

title: Raspberry Pi 3B+ BLE communication to Arduino Nano 33 IOT

Answers: 1

body:
For completeness, it appears an appropriate Python library can be installed with:

    pip3 install adafruit-circuitpython-ble

The test code, used with the Arduino code 'Echo' from the ArduinoHardwareBLE library is below.  This was updated to let you choose the name of the device (here, MY_BLE)  rather than any random device that has UART capability.  It also allows you to send a small file from a few lines, with a "#" denoting a comment (first character in the line).  ESC and a return quits the program.

    # Connect to an "eval()" service over BLE UART.

    from adafruit_ble import BLERadio
    from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
    from adafruit_ble.services.nordic import UARTService

    ble = BLERadio()

    uart_connection = None

    def send_stuff(s):
     uart_service.write(s.encode("utf-8"))
     uart_service.write(b'\n')
     readline=uart_service.readline().decode("utf-8")
     while(len(readline)>0):
      print(readline)
      readline=uart_service.readline().decode("utf-8")

    while True:

     if not uart_connection:
      print("Trying to connect...")
      print("ESC then RETURN to exit.")
      for adv in ble.start_scan(ProvideServicesAdvertisement):
       if UARTService in adv.services:
        regular_name = adv.complete_name
        if(regular_name=='MY_BLE'):
         uart_connection = ble.connect(adv)
         print("Connected")
         # for some reason, we have to read a line...
         uart_service = uart_connection[UARTService]
         print(uart_service.readline().decode("utf-8"))
         break
      ble.stop_scan()

     if uart_connection and uart_connection.connected:
      uart_service = uart_connection[UARTService]
      while uart_connection.connected:
       s = input("Prompt: ")
       if(len(s)>0):
        if(ord(s[0])==27):
         print("done.")
         exit()
        else:

         # Check if "!" character is used; if so, send contents of a file
         if(s[0]=="!"):
          print("sending commands")
          count=0
          file1=open('commands.txt','r')
          Lines=file1.readlines()
          for line in Lines:
           count=count+1
           tmp=line.strip()
           if(len(tmp)>0):
            if(tmp[0]=='#'):
             print("comment:" + tmp)
            else:
             print("Line{}: {}".format(count, tmp))
             send_stuff(tmp)

         else:
          send_stuff(s)


body:
I have exactly this model of esp8266:
[![enter image description here][1]][1]
I removed Atmega328p IC from Arduino, and powered Arduino with USB cable. After all, I made this connection combinations:
```
1)
ESP Tx > Arudino Tx
ESP Rx > Arduino Rx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd
ESP GPIO0 > GND

2)
ESP Tx > Arudino Rx
ESP Rx > Arduino Tx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd
ESP GPIO0 > GND

3)
ESP Tx > Arudino Tx
ESP Rx > Arduino Rx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd

4)
ESP Tx > Arudino Rx
ESP Rx > Arduino Tx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd
```

I checked both 9600, and 115200 baud, but on any of them I did not get a reply to the `AT` command. Have I done something wrong? I get weird characters when disconnecting ESP's `GND` wire, so some communication exists.

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

title: No response in Serial Monitor from es8266 with Arduino nano

Answers: 1

body:
   If it is not a genuine Arduino (Chinese clone probably) and it has the CH340 USB to Serial converter chip, then it will not work as the digital Signal on TX does not get pulled to ground when transmitting a digital LOW, (if that's the right way to say it). There seem to be resistors on the board that cause this effect, or something. I do not guarantee that this is your problem but it's highly likely.

Use an FTDI USB to Serial board or similar and you might have better results.


body:
**How it happened**

Recently I was working on a device with **Blynk** application in which my device will burn crackers using Blynk. I wanted to create a safe environment for burning crackers. There was a dilemma to power Nodemcu with a battery first I used a **38650 lion battery** but it didn't provide sufficient power to Nodemcu. Than I connected two 38650 battery in series than it was working fine for half a minute. But later it started became hot but than I removed the power supply immediately and powered it with **3.3v charger** than also it was heating and still.

**My research**

I researched a lot and also changed the **S4 didode** with **IN4007** but it is still heating and malfunctioning. I **checked** all the parts but they were **not shorted**. What's the problem with my Nodemcu why is it heating and not working properly.
**With regards**
**Naman**

title: My nodemcu esp8266 is heating a lot and the on board LED of gpio16 is On continuously. What's the Reason of heating?

Answers: 0


body:
I'm making a vehicle project as a way to learn Arduino. I've set up motor control for a number of DC-motors plus a servo via an Adafruit Motor Shield V1 that I picked up.

Everything works fine, but now I've started looking at adding wireless control for the setup using a second Arduino and two NRF24L01 wireless units. However, reading up on the specs for the NRF24L01 it seems it requires pin 12 on the Arduino, which is already in use by the motor shield.

So, can I combine a NRF24L01 and an Adafruit Motor Shield V1? And if so, how?

If it's not possible, what would be the pros and cons of slaving the shielded Arduino to a Nano that would carry the NRF24L01, versus replacing the Adafruit motor shield with external DC motor driver(s)?

Edit:

I now found this previous question:

https://arduino.stackexchange.com/questions/3892/motor-shield-and-wireless-transceiver-compete-for-same-pins?rq=1

A difference in my project is that I'm not using stepper motors, so perhaps that makes a difference?

title: Combining an NRF24L01 transmitter/receiver with an Adafruit Motor Shield V1?

Answers: 1

body:
One of the problems of the Uno is that the hardware SPI pins conflict with some of the PWM pins. If you want lots of motor control then you have it at the expense of no SPI. If you want SPI then you have it at the cost of reduced motor control.

The V1 shield uses a shift register for some of the motor signals, and that has to fit its signals in around the available PWM pins, so that as well has spilled over into the SPI pins (since you can't use SPI because of the PWM pins that really doesn't matter).

So no SPI means no nRF24L01.  Or does it?

You *could* (though I don't know of any libraries that handle this) use "bit-banged" software SPI on other pins (such as the analog pins) to communicate with the nRF24L01. Your mileage may vary with that, but it is technically possible - as long as you can find (or write) the right software support for it.

Would it be better to throw more hardware at it and have the wireless connection on a dedicated MCU? I would say, yes. Not only does it mean you can use existing libraries to communicate with the nRF24L01 without any worries of conflicting pins, but you get to compartmentalise your software into discrete units that don't interfere with each other. Parallel processing :)

How to communicate between the two? Well, you have I2C available on the analog pins A4/A5, which is well documented and plenty of examples. Or you could use serial, although the 328P's lack of serial ports means that you'd probably be working with SoftwareSerial which is ropy at best.  I'd pick I2C out of those two TBH.


body:
I'm using an Arduino Nano with an Atmega 328p.

I would like to attach and use a different USB port instead of the builtin one for supplying power, serial debugging and uploading code.

Currently my board is recieving power from the USB port using vin, but I would like to know how I can get the Arduino to use serial communication with the TX/RX pins and the data+ and data- pins on the USB. I'm especially interested in knowing if I can upload new code to the board through TX/RX.

The official page for the Nano says that the serial communication is handled by an FTDI FT232RL chip, which as I understand, translates the signal from the builtin USB to serial. Is there any way that I can use this chip to communicate over the TX/RX pins instead of builtin USB?

Online documentation about this subject is really lacking, and of the few opinions that I've found, many are conflicting. I would really appreciate any help with this, thanks.

title: Using TX/RX serial pins to communicate over USB

Answers: 1

body:
There is no "built-in USB" on the Nano. There is only the FT232RL chip which talks USB. That chip is connected directly to the TX/RX pins inside the board.

You are already communicating over the TX/RX pins *through* the FT232RL to the USB.

Yes, you could use your own FT232RL (or FT232-like) board to communicate between USB and the TX/RX pins, but that will be exactly the same as using the one built in to the board - but without the convenience, and with the addition of more wires and expense.  So pointless, unless the current USB connection is damaged in some way.


body:
I am using RTClib.h and TimeLib.h with an Uno.

Have been struggling for days in understanding the various RTC libraries available and how to use them with the Arduino Time Library.

**Question 1**.
If I do not want to create a new now() object each time through the loop, how do I sync the Time Library to the RTC every x seconds?  Any time I try to use the RTClib function now.hour now.minute etc it requires me to use DateTime now = RTC.now() creating the now() object.

Is there an equivalent function in RTCLib as setSyncProvider(RTC.get) in DS1307RTC library?

Is there an equivalent to setSyncInterval(5000)

**Question 2**.
Which RTCLib should I call out? There are several used in examples:

<RTClib.h>

"RTClib"   using quotes

<RTCLib.h> with capital L

and sometimes also calling out one of these:

RTC_DS1307 RTC

or
RTC_DS1307 rtc

or
RTC_DS3231 rtc

**Question 3**
a. Are tmElements_t tm part of the DS1307RTC library?
b. Are these tm.Hour tm.Minute from the RTC?
c. Is there an equivalent in the RTClib.h ?

And finally I have posted some code below just to show my usage:

    #include "RTClib.h"
    #include <Wire.h>
    #include <TimeLib.h>

    RTC_DS1307 RTC;

    void setup() {

    Serial.begin(9600);
    Wire.begin();  //sets up the I2C
    RTC.begin();   //initializes the I2C to the RTC

    if (! RTC.begin()) {
        Serial.println("Couldn't find RTC");
    }

    //  Set the RTC Time to 5:10:30 Nov 3 2020
          RTC.adjust(DateTime(2020,11,3,5,10,30));

    //Set Arduino Time Library different than RTC time to see which is which
    setTime(9, 27, 05, 14, 07, 2015);

    }

     void loop() {

    /*
    // How do I sync Time Library to RTC after x seconds?
      setSyncProvider(RTC.get); // This is in the DS1307RTC.h Library
      setSyncInterval(5000);   //  Are there such functions in RTClib ?
    */

    DateTime now = RTC.now();   // Pulls RTC time into now().  Does not sync with Time Library
                                // Do not want to do this every loop.

    //Print RTC Time
    Serial.println();
    Serial.print("RTC now.hour        ");
    Serial.println(now.hour());
    Serial.print("RTC now.minute      ");
    Serial.println(now.minute());
    Serial.print("RTC now.second:     ");
    Serial.println(now.second());
    Serial.println();
    Serial.println();

    //Print Arduino TimeLib Time
    Serial.print("Time Lib Hour:       ");
    Serial.print(hour());
    Serial.println();
    Serial.print("Time Lib Min:        ");
    Serial.print(minute());
    Serial.println();
    Serial.print("Time Lib Sec:        ");
    Serial.print(second());
    Serial.println();
    Serial.println();

    delay(1000);

     }

--------------------------------------------------------
Updated 5 Nov 2020

I think I almost  understand.
Please let me know if this code is doing what I think it is doing, specifically:

In Setup:
        Set the RTC to 5:10:30.
        Set Time Library to 9:27:05 with setTime().
        Set Time Library to RTC time with DateTime now (over writing   9:27:05)?
        Set Time Library variables to RTC using tm.Hour = now.Hour, etc.

In Loop:
        Every 5 seconds update hour(), minute() second() with RTC time.
        Every loop update tm.hour with hour(), etc.

I know it is still not right since the serial prints show tm.Hour,tm.Minute alternating each loop as shown at the bottom.

```c++
#include "RTClib.h"
#include <Wire.h>
#include <TimeLib.h>

RTC_DS1307 RTC;

time_t time_provider()
{
    return RTC.now().unixtime();
}

tmElements_t tm;  //part of Time Library

void setup() {
    //setSyncProvider(time_provider);
    Serial.begin(9600);
    Wire.begin();  //sets up the I2C
    RTC.begin();   //initializes the I2C to the RTC

    if (! RTC.begin()) {
        Serial.println("Couldn't find RTC");
    }

    //  Set the RTC Time to 5:10:30 Nov 3 2020
    RTC.adjust(DateTime(2020,11,3,5,10,30));

    //Set Arduino Time Library different than RTC time 9:27:05
    setTime(9, 27, 05, 14, 07, 2015);

    //Setting Time Library to RTC time
    DateTime now = RTC.now();
    tm.Hour = now.hour();
    tm.Minute = now.minute();
    tm.Second = now.second();
}

void loop() {
    setSyncProvider(RTC.now);
    setSyncInterval(5000);

    //Time Library time updates to RTC every 5 seconds
    tm.Hour = hour();
    tm.Minute = minute();
    tm.Second = second();

    Serial.print("tm.Hour:    ");
    Serial.print(tm.Hour);
    Serial.println();
    Serial.print("tm.Minute:  ");
    Serial.print(tm.Minute);
    Serial.println();
    Serial.print("tm.Seconds: ");
    Serial.print(tm.Second);
    Serial.println();
    Serial.println();
    delay(1000);
}
```

Serial Prints:

```text
tm.Hour:    5
tm.Minute:  34
tm.Seconds: 56

tm.Hour:    18
tm.Minute:  0
tm.Seconds: 0

tm.Hour:    5
tm.Minute:  34
tm.Seconds: 56

tm.Hour:    18
tm.Minute:  0
tm.Seconds: 0

tm.Hour:    5
tm.Minute:  34
tm.Seconds: 56

tm.Hour:    18
tm.Minute:  0
tm.Seconds: 0
```

title: Arduino Time Library and RTC Libraries

Answers: 2

body:
> Is there an equivalent function in RTCLib as setSyncProvider(RTC.get) in DS1307RTC library?
>
> Is there an equivalent to setSyncInterval(5000)

Those are TimeLib functions. There's no "equivalent to" since you *are* using TimeLib.

The first one just expects a pointer to a function that returns a `time_t`. What is in that function is up to you.

> Which RTCLib should I call out? There are several used in examples:

The capitalisation should match the name of the header file. Windows doesn't care, and OS X usually doesn't care, but can be configured to. Linux *does* care and needs it to match. If you want your code to be portable then you must keep the capitalisation the same as the file.

> and sometimes also calling out one of these:

You need to create an object that matches your physical RTC.

> a. Are tmElements_t tm part of the DS1307RTC library?

No. They are part of TimeLib.

> b. Are these tm.Hour tm.Minute from the RTC?

They are whatever gets assigned to them by a function that is called. They are just variables. They can contain anything.

> c. Is there an equivalent in the RTClib.h ?

No. But then you don't need there to be if you're using TimeLib.

So: you need to

* Create a function that gets the time from the RTC through whatever library you want to use (RTCLib for example) and calculates the number of seconds since 00:00:00 01/01/1970, which it then returns as a `time_t`.
* Pass that to TimeLib's `setSyncProvider()`
* Set a sync frequency with `setSyncInterval()`.

body:
Let me first give some background about these libraries.

The Time library uses `millis()` for timekeeping. Since this can be
subject to significant drift, it provides a means to periodically sync
to an external time provider. Hence the functions `setSyncProvider()`
and `setSyncInterval()`.

RTClib is meant to interface an RTC. It does not provide timekeeping on
its own: you get the current time by querying an RTC through it's
`now()` method.

These two libraries can nicely complement each other, as RTClib can be
used as a time provider for the Time library:

```c++
// Provide the RTC time to the Time library.
time_t time_provider() {
    return RTC.now().unixtime();
}

void setup() {
    // ...
    setSyncProvider(time_provider);
}
```

> If I do not want to create a new now() object [...]

It is actually called a `DateTime` object.

> Is there an equivalent [to `tmElements_t`] in the RTClib

Yes, the [`DateTime` class][DateTime]. Note that, unlike the
`tmElements_t` structure, the data fields of `DateTime` are not public,
and you have to use accessors to get them: `year()`, `month()`,
`day()`...

**Alternative timekeeping method**

Since you are using an Arduino Uno, there is a third method of
timekeeping you may want to consider. Instead of querying the RTC on
every loop iteration (RTClib) or interpolating the RTC readings with
`millis()` (Time library), you may route a 1 Hz output of the RTC
to an interrupt pin, and count the seconds in the ISR. The [avr-libc
timing code][avr-libc] is designed to provide timekeeping in this
fashion. It all boils down to:

```c++
// Initialize the system time from the RTC.
set_system_time(RTC.now().secondstime());

// Keep the time in sync using the 1 Hz output of the RTC.
pinMode(pin1Hz, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(pin1Hz), system_tick, FALLING);
```

For more details, see the example sketch [interrupts1Hz.ino][example]
provided with RTClib.

[DateTime]: https://adafruit.github.io/RTClib/html/class_date_time.html
[avr-libc]: https://www.nongnu.org/avr-libc/user-manual/group__avr__time.html
[example]: https://github.com/adafruit/RTClib/blob/1.12.0/examples/interrupts1Hz/interrupts1Hz.ino

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

**Edit 1**: Answering a comment

> which pin does [the Arduino interrupt pin] connect to on the RTC?

It depends on the RTC you are using. I will assume it's a DS1307, as
implied by the code in your question. Take a look at the [datasheet][]
of the RTC. On page 6, there is a table titled “Pin description”. From
this table:

> **pin**: 7
> **name**: SQW/OUT
> **function**: Square Wave/Output Driver. When enabled, the SQWE bit
> set to 1, the SQW/OUT pin outputs one of four square-wave frequencies
> (1Hz, 4kHz, 8kHz, 32kHz). The SQW/OUT pin is open drain and requires
> an external pullup resistor. SQW/OUT operates with either
> VCC or VBAT applied. The pullup voltage can be
> up to 5.5V regardless of the voltage on VCC. If not used,
> this pin can be left floating.

If you are using an RTC _module_, you will have to figure out where this
pin is exposed on the module's connector.

In any case, you will have to enable the 1 Hz square wave output with

```c++
RTC.writeSqwPinMode(DS1307_SquareWave1HZ);
```

[datasheet]: https://datasheets.maximintegrated.com/en/ds/DS1307.pdf

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

**Edit 2**: Commenting on the update to the question:

> ```c++
> // Set the RTC Time to 5:10:30 Nov 3 2020
> RTC.adjust(DateTime(2020,11,3,5,10,30));
> ```

Correct.

> ```c++
> // Set Arduino Time Library different than RTC time 9:27:05
> setTime(9, 27, 05, 14, 07, 2015);
> ```

Correct. Date is 2015-07-14.

> ```c++
> // Setting Time Library to RTC time
> DateTime now = RTC.now();
> tm.Hour = now.hour();
> tm.Minute = now.minute();
> tm.Second = now.second();
> ```

No. This is only partially initializing the `tm` variable. It has no
effect on the idea the Time library has of the current time. Note that
the date fields of `tm` have not been initialized at this point, and
could well be invalid (like month 23, day 125).

> ```c++
> setSyncProvider(RTC.now);
> ```

This is incorrect, and should have generated a compiler warning.
`setSyncProvider()` expects a function that returns the current time as
Unix time (a simple integer, of type `time_t`). You are providing a
function that returns the current time in broken down form (year,
month...), with type `DateTime`. The Time library will not understand
that and may yield garbage like, say, 18:00:00.

The time returned by `RTC.now()` can be converted to Unix time with the
`unixtime()` method. That's why I gave you the `time_provider()`
function.

Also, you are not supposed to call `setSyncProvider()` and
`setSyncInterval()` on every loop iteration. Do it once and for all in
`setup()`.

> ```c++
> // Time Library time updates to RTC every 5 seconds
> tm.Hour = hour();
> tm.Minute = minute();
> tm.Second = second();
> ```

Again, this is only updating the variable `tm`. It has no effect on what
the Time library believes is the current time.


body:
I would like to play car alarm sound through Arduino buzzer - something like this [https://youtu.be/nuPHwijMsIg][1]

  [1]: https://youtu.be/nuPHwijMsIg

Does anybody have a library for such melody?

title: Arduino piezo-buzzer melody for car alarm

Answers: 2

body:
I think what you're really asking for is a library of sounds (in the form of code), rather than a code library in the normal sense.  I'd like such a thing too (specifically a retro-gaming style laser noise), but extensive googling hasn't found anything, though someone has made a sketch of the Tetris theme.

A car alarm is probably fairly easy - a couple of for loops changing the frequency of a `tone()`; My Arduino and piezo buzzer are at home but playing that YouTube and using a [spectrum analyser app](https://play.google.com/store/apps/details?id=com.xyz.fft&hl=en&gl=US) on my phone it looks like (using the waterfall display mode):
- The first alarm is looping from 1000Hz to 2200Hz over about 250ms, then back down again.  - The next 2 are falling tones, from 1kHz down to about 500 over 250 or 500ms.
- Then we've got a rising tone 500 Hz to 1kHz  over 2s
- A beep at about 2.2kHz, 250ms on/off
- A two-tone siren at 1 and 1.5kHz, 1s of each.

Times and frequencies were indeed a little off, and many of the frequency ramps aren't linear, but here's something to play with.  The more interesting alarms are in there, along with a couple of laser zaps.  The square-wave drive of a piezo (leading to interesting harmonics), and the complete lack of a low frequency response (nothing below about a few hundred Hz on the one I have here) limit things a little, but it compares well to a Lego siren I have

    int beep_pin=10;
    int gap=1000;

    void setup() {
      // put your setup code here, to run once:
      pinMode(beep_pin, OUTPUT);
    }

    void zap1()
    {
        for (float f=3000;f>40;f=f*0.93){
        tone(beep_pin,f);
        delay(10);
      }
    }

    void zap2()
    {
        for (float f=3000;f>10;f=f*0.85){
        tone(beep_pin,2*f);
        delay(5);
        tone(beep_pin,f);
        delay(5);
      }
    }
    void risefall()
    {
      float rise_fall_time=180;
      int steps=50;
      float f_max=2600;
      float f_min=1000;
      float delay_time=rise_fall_time/steps;
      float step_size=(f_max-f_min)/steps;
      for (float f =f_min;f<f_max;f+=step_size){
        tone(beep_pin,f);
        delay(delay_time);
      }
       for (float f =f_max;f>f_min;f-=step_size){
        tone(beep_pin,f);
        delay(delay_time);
      }
    }
    void fall(float rise_fall_time)
    {
      int steps=50;
      float f_max=2000;
      float f_min=500;
      float delay_time=rise_fall_time/steps;
      float step_size=0.97;
      for (float f =f_max;f>f_min;f*=step_size){
        tone(beep_pin,f);
        delay(delay_time);
      }
    }
    void rise()
    {
      float rise_fall_time=2000;
      int steps=100;
      float f_max=1500;
      float f_min=500;
      float delay_time=rise_fall_time/steps;
      float step_size=1.012;
      for (float f =f_min;f<f_max;f*=step_size){
        tone(beep_pin,f);
        delay(delay_time);
      }
      noTone(beep_pin);
      delay(100);

    }

    void twotone()
    {
      float f_max=1500;
      float f_min=1000;
      float delay_time=800;
      tone(beep_pin,f_max);
      delay(delay_time);
      tone(beep_pin,f_min);
      delay(delay_time);

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

      for (int count=1;count<=10;count++)
      {
        risefall();
      }
      noTone(beep_pin);
      delay(gap);
      for (int count=1;count<=10;count++)
      {
        fall(300);
      }
      noTone(beep_pin);
      delay(gap);
      for (int count=1;count<=5;count++)
      {
        fall(600);
      }
      noTone(beep_pin);
      delay(gap);
      for (int count=1;count<5;count++)
      {
        rise();
      }
      noTone(beep_pin);
      delay(gap);
      for (int count=1;count<5;count++)
      {
        twotone();
      }
      noTone(beep_pin);
      delay(gap);
      for (int count=1;count<10;count++)
      {
        zap1();
      }
      noTone(beep_pin);
      delay(gap);
      for (int count=1;count<10;count++)
      {
        zap2();
      }
      noTone(beep_pin);
      delay(gap);
    }

It's also [on GitHub](https://github.com/ChrisHodgesUK/ArduinoAlarms), and released into the public domain under the [unlicense](https://unlicense.org/) so anyone can use it however they like

body: https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody See this example to get the code for each musical note. It should work very well!


body:
I have an arduino uno connected via USB to a raspberry pi, the raspi is accessible via ssh only.

Just started a bit with arduino-cli ; I upload a sketch which reads my analog pins. How can I access the serial monitor to get the data??

title: Access serial monitor on linux cli? Using arduino-cli?

Answers: 3

body:
I use `minicom`.

```
$ sudo apt-get install minicom
... blah blah blah ...
$ minicom -D /dev/ttyACM0 -b 115200
```

Minicom can take a bit of getting used to. Use `CTRL-A` to initiate a command sequence. `CTRL-A X` is exit. `CTRL-A O` is configuration ("*O*ptions") where you can configure flow control and such.

Many people also use `screen` to do the same job, but I like the interface that `minicom` gives - it's more terminal-like.

body:
Programs such as `screen`, `minicom` or (my favorite)
[`picocom`][picocom] are useful if you want bidirectional communication
between the Arduino and the host computer. If you only want to _read_
what the Arduino sends, that can be done with `cat`:

```shell
stty -F /dev/ttyACM0 raw 115200
cat /dev/ttyACM0
```

[picocom]: https://github.com/npat-efault/picocom

body:
I also had the problem that arduino-cli includes no serial monitor. I tried out screen, minicom and other but they are a bit difficult to get used with them. So I created a small python script which works as an serial monitor in the command line:
https://github.com/PBahner/Serial-Monitor


body: * I am trying to use the Arduino MAP function to allow me to PWM 4 LEDs between 0 and full brightness. I guess the tricky part is that the joystick neutral position is at the venter of the range of the potentiometers so the analog voltage to the inputs is at +2.5V when the joystick at neutral). Ideally I want to make a red LED that is associated with the Y axis to go from 0 to full as the joystick is pushed away. Similarly, I want a blue LED associated with the Y axis to go from 0 to Full on when the joystick is pulled toward me. I want to duplicate that action for the X axis with green and yellow LEDS but I can't seem to be able to figure out how to compensate for the 2.5V offset* I hoped I could just use mapping of the values.

title: How can I PWM 4 LEDs from 0 to full brightness using a two axiz resistive joystick?

Answers: 1

body:
There's a number of steps you need to go through:

1. Read the ADC to get the joystick position
2. Subtract 50% of the full range (512) to get a ±512 value
3. Note the sign to get the direction
4. Take the absolute value to get the distance
5. Subtract a small amount to create a "dead zone" in the centre of the joystick
6. Map the result to 0-255 for the PWM.

The code might look like (note: untested):

```c++
int y = analogRead(0);    // Get the current value
y -= 512;                 // Subtract 512

int pin = 2;              // Unless otherwise told, use pin 2
if (y < 0) {              // If it's negative...
    pin = 3;              //    then we'll use pin 3 instead
}

y = abs(y);               // Take the absolute value (discard the sign)
y -= 20;                  // subtract 20 for a dead zone
If (y < 0) y = 0;         // zero any negative
y = map(0, 492, 0, 255);  // map the new full range of 0-492 to 0-255
analogWrite(pin, y);      // light the LED on the pin we chose above.
```

And do the exact same thing for X with different pins.


body:
*https://create.arduino.cc/projecthub/MisterBotBreak/how-to-use-temperature-and-humidity-dht-sensors-9e5975*

**Copied Error Message:**

    Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"

    In file included from C:\Users\soumy\OneDrive\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.cpp:15:0:

    C:\Users\soumy\OneDrive\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.h:36:10: fatal error: Adafruit_Sensor.h: No such file or directory

     #include <Adafruit_Sensor.h>

              ^~~~~~~~~~~~~~~~~~~

    compilation terminated.

    exit status 1

    Error compiling for board Arduino Uno.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

**The code:**

```#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {

  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  float hif = dht.computeHeatIndex(f, h);
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
}

title: Compiling Error - exit status 1 for DHT11 using Arduino UNO (code/process/connections same as website given bellow)

Answers: 1

body:
I didn't download the "Adafruit Sensor Library"
https://github.com/adafruit/Adafruit_Sensor
It ran after I added it.


body:
I am trying to use WS2812B LEDs with an Arduino.
I have 24 LEDs connected to pin 6.

When I first received the strip I connected it to 12V and data.
Using the cyclone example in the FastLED library worked.

But then I cut them and added extension wires.
I have 3 LEDs on single strip; so it is 8 strips of 3 LEDs.
The extension is about 30cm long.
Now when I power them, they just glow bright white.

So, I thought the extension wire was the problem.
I removed extension and connected them as they came.
But still, they are turning on bright white.

I connected the Arduino out to DIN.

title: WS2812B NeoPixels no longer working after cutting the strip and adding an extension

Answers: 0


body: Can I achieve nanosecond accuracy with Arduino Vidor MKR 4000? Has anyone experience? Obviously by using the FPGA it has on it. I do not find much support on this module on google search...

title: Achieving nanosecond accuracy with MKR Vidor 4000

Answers: 1

body:
No. You can't.

To achieve 1ns precision you need a 1GHz clock. That can't happen.  The MKR Vidor 4000 uses an FPGA with an "A7" speed grade. That means that (according to Table 20 [here](https://www.intel.com/content/dam/www/programmable/us/en/pdfs/literature/hb/cyclone-10/c10lp-51002.pdf)) you can't run at any more than 402Mhz internally (200MHz is all Arduino are rating it for).

Not even half.

Around 5ns precision would be the absolute maximum precision you could get if you stick to the Arduino clock specs.


body:
I am just getting back into electronics and have started to play around with making my own button box.

I am trying to control an LED's brightness using a potentiometer, while also reading the potentiometer's value with the Arduino's analogue pin. I want to limit the number of pins I am using for things because I have lots of buttons that will need to be hooked up, so I am trying to control the LED without any code.

I have put together the following circuit (sorry, not my tidiest diagram. I am also using a Pro Micro rather than a Leonardo, but I didn't think that would make any difference :) ).

[![Circuit Diagram][1]][1]

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

This works to a degree. I am able to adjust the LED brightness using the pot, and I do get a reading on the Arduino from the pot, however, the reading does not go up linearly as I would expect. It seems to get to about 500 out of 1023 at 4/5 of the rotation and then jumps up to 1023 within the last 1/5.

Could someone explain why this happens, and if it is even possible to do what I am attempting?

Thanks in advance!

title: Can I control LED brightness with potentiometer without any code, as well as reading the potentiometer value?

Answers: 4

body:
Some good remarks have already been made by jsotola.

**Potentiometer types**

(updated because of Majenko's comment):

Note there are three types of pots:

- Logarithmic (with name A\<value>K, e.g. A50K for a logarithmic 50K pot)
- Linear (with name B\<value>K, e.g. B50K for a linear 50K pot)
- Reserve logarithmic/Exponential (with name C\<value>K, e.g. C50K for a rserve logarithmic 50K pot)

**Mapping values**

However, in code you can map a value from a pot to any other value, even from logarithmic/linear to anything you want, using logarithmic or other functions available in C/C++.

**Shift Registers**

Also, to reduce the number of pins you need for buttons you can use shift registers. The most known is 74HC595 for output and in your case you need an input shift register, which is 74HC165, see e.g. https://dronebotworkshop.com/shift-registers/ or https://playground.arduino.cc/Code/ShiftRegSN74HC165N/

body:
You need to "buffer" the potentiometer to separate it from the LED and resistor. The simplest circuit for that is a unity-gain voltage follower with an op-amp:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

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

<!-- End schematic -->

You want to choose a "Rail to Rail I/O" op-amp so that it can get right down to 0V and right up to 5V, otherwise you will clip the top and bottom of the range of the potentiometer.

body: I am surprised that the pot has survived so far. LEDs are current devices not voltage devices. The above circuits will work to some extent but not very well. You need to vary the current either using an adjustable current source/sink or PWM.

body:
Thanks for all the suggestions.

In the end, I ordered some dual-gang potentiometers as jsotola suggested and Mejenko confirmed would work. These are working perfectly in my circuit now.

Thanks again!


body:
The issue: In the following example even though complexManoeuvre == 3, `Serial.print(CTA5: "); ...` is executed.

```
void loop()  {
  if(complexManoeuvre == 0) {
    if(timeisup == true && goingForwards == 1)  {   // If time is up while going forward, assume it's stuck
      goingForwards = 0;
      Serial.print("CTA4: "); stuck(stk);
    }
    if(timeisup == true && goingForwards != 1)  {
      Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
    }
  }
}
```
However, if I include the first condition within the other if() statments two then it works:
```
if(complexManoeuvre == 0 && (deltaBegan >= manoeuvreFor) && goingForwards == 1) {
  goingForwards = 0;
  Serial.print("CTA4: "); Serial.print(complexManoeuvre); stuck(stk);
}
if(complexManoeuvre == 0 && (deltaBegan >= manoeuvreFor) && goingForwards != 1) {
  //Serial.print("complexManoeuvre == "); Serial.println(complexManoeuvre);
  Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
}
```
Being completely stumped, I suspected compiler issue so I reinstalled Arduino to clear Meguno-link avrdude wrapper but the problem remains.

The full code (for a robot hoover) is as follows, slimmed down as much as possible to simplify reading:
```
const int fwd = 12000;            // ms duration
const int stk = 1600;
unsigned long beganManoeuvre;     // millis time when manoeuvre began
int manoeuvreFor;                 // Duration
unsigned long lastStuck;
byte goingForwards;               // Yes or no
byte complexManoeuvre;            // 0 = none, 1 = center, 2 = stuck, 3 = doubleStuck
byte progress;                    // complexManoeuvre progress

void setup() {
  Serial.begin(9600);
  Serial.print(F("CTA0: ")); spinR(4800);     // Spin through 360 degrees
}

void loop() {
  bool timeisup = false;
  if((millis() - beganManoeuvre) >= manoeuvreFor) {
    timeisup = true;
  }

  if(complexManoeuvre != 0 && timeisup == true)  {          // If part way through a in a complex
    switch(complexManoeuvre)  {                             // ..manoeuvre (eg; stuck)
    case 1:
      // do other()
      break;
    case 2:
      Serial.print(F("CTA2: ")); stuck(manoeuvreFor);       // return to the complex manoeuvre
      break;
    }
  }

//  if(complexManoeuvre == 0 && timeisup == true && goingForwards == 1) {
//    goingForwards = 0;
//    Serial.print("CTA4: "); Serial.print(complexManoeuvre); stuck(stk);
//  }
//  if(complexManoeuvre == 0 && timeisup == true && goingForwards != 1) {
//    //Serial.print("complexManoeuvre == "); Serial.println(complexManoeuvre);
//    Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
//  }
  if(complexManoeuvre == 0) {
    if(timeisup == true && goingForwards == 1)  {   // If timeisup while going forward, assume stuck
      goingForwards = 0;
      Serial.print("CTA4: "); stuck(stk);
    }
    if(timeisup == true && goingForwards != 1)  {   // If finished another manoeuvre, go forwards
      if(complexManoeuvre != 0) Serial.println("What the?!");
      Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
    }
  }
}

void stuck(int dur)  {
  Serial.print(F("void stuck(int dur == "));  Serial.println(dur);
  switch(progress) {
  case 0:
    Serial.print(F("CTA26: "));
    complexManoeuvre = 2;
    reverse(dur);
    progress = 1;
    break;
  case 1:
    Serial.print(F("CTA27: "));
    spinR(dur);
    progress = 2;
    break;
  case 2:                     // Reset
    progress = 0;
    complexManoeuvre = 0;
    lastStuck = millis();
    break;
  }
}

void forward(int dur)  {
  Serial.print(F("void forward(int ")); Serial.print(dur);
  if(goingForwards != 1) {
      Serial.print(F(") >> if(goingForwards != 1) then do"));
      goingForwards = 1;
      beganManoeuvre = millis();
      manoeuvreFor = dur;
      digitalWrite(9, HIGH);
      digitalWrite(10, LOW);
      digitalWrite(11, HIGH);
      digitalWrite(12, LOW);
  }
  Serial.println();
}

void reverse(int dur)  {
  Serial.print(F("void reverse(int dur == "));  Serial.println(dur);
  beganManoeuvre = millis();
  manoeuvreFor = dur;
  digitalWrite(9, LOW);
  digitalWrite(10, HIGH);
  digitalWrite(11, LOW);
  digitalWrite(12, HIGH);
}

void spinR(int dur) {
  Serial.print(F("void spinR(int dur == "));  Serial.println(dur);
  beganManoeuvre = millis();
  manoeuvreFor = dur;
  digitalWrite(9, LOW);
  digitalWrite(10, HIGH);
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
}
```

The questionable Serial output is:
```
1) 19:59:31.964 -> CTA0: void spinR(int dur == 4800
2) 19:59:36.765 -> CTA5: 0void forward(int 12000) >> if(goingForwards != 1) then do
3) 19:59:48.771 -> CTA4: void stuck(int dur == 1600
4) 19:59:48.811 -> CTA26: void reverse(int dur == 1600
5) 20:11:12.695 -> What the?!
6) 19:59:48.851 -> CTA5: 2void forward(int 12000) >> if(goingForwards != 1) then do
7) 20:00:00.854 -> CTA2: void stuck(int dur == 12000
8) 20:00:00.894 -> CTA27: void spinR(int dur == 12000
9) 20:00:12.860 -> CTA2: void stuck(int dur == 12000
10) 20:00:12.900 -> CTA4: void stuck(int dur == 1600
...
```

Edit to add: Arduino version 1.8.13, Win7, tested on Nano Atmega168PA and Mega2560

title: if(val == 0) being ignored when it contains another nested if() statement

Answers: 1

body: Your `void Stuck() { ... }`, which is called inside the first `if (timeisup == true && goingForwards == 1) { ... }` can set `complexManoeuvre`  to a non-zero value, before reaching the second `if (timeisup == true && goingForwards != 1) { ... }` (the one with *"What the?!"*).


body:
I have a code here, from DFmini player. I have a tactile switch. when I press it on and release it will play a sound. My question is that when I press the tactile but not release it so I want it still play the same sound.
But while the tactile switch is pressed down it keeps repeating the same sound. I want it to play just for once while the tactile button is still pressed down.

    //#include <SoftwareSerial.h>   //If we use other pins than D0 adn D1 for TX and RX for the music player
    #include <DFMiniMp3.h>          //Downlaod here: https://electronoobs.com/eng_arduino_DFPlayer_Mini_Mp3_by_Makuna.php

    int sw1 = 3;
    int sw2 = 4;
    int sw3 = 5;
    int sw4 = 6;
    int sw5 = 7;
    int sw6 = 8;
    class Mp3Notify
    {
    public:
      static void OnError(uint16_t errorCode)
      {
        // see DfMp3_Error for code meaning
        Serial.println();
        Serial.print("Com Error ");
        Serial.println(errorCode);
      }

      static void OnPlayFinished(uint16_t globalTrack)
      {
        Serial.println();
        Serial.print("Play finished for #");
        Serial.println(globalTrack);
      }

      static void OnCardOnline(uint16_t code)
      {
        Serial.println();
        Serial.print("Card online ");
        Serial.println(code);
      }

      static void OnCardInserted(uint16_t code)
      {
        Serial.println();
        Serial.print("Card inserted ");
        Serial.println(code);
      }

      static void OnCardRemoved(uint16_t code)
      {
        Serial.println();
        Serial.print("Card removed ");
        Serial.println(code);
      }
    };

    DFMiniMp3<HardwareSerial, Mp3Notify> mp3(Serial);   //Create the UART connection to the module

    void setup()
    {
      //3 push buttons with pullups
      pinMode(sw1,INPUT);                        //Define each button as input with pullup
      pinMode(sw2,INPUT);
      pinMode(sw3,INPUT);
      pinMode(sw4,INPUT);
      pinMode(sw5,INPUT);
      pinMode(sw6,INPUT);
      digitalWrite (sw1, HIGH); //12 Votls supply set to off state
      digitalWrite (sw2, HIGH); //5 Votls supply set to off state
      digitalWrite (sw3, HIGH); //3 Votls supply set to off state
      digitalWrite (sw4, HIGH); //Ajustable Votls supply set to off state
      digitalWrite (sw5, HIGH); //3 Votls supply set to off state
      digitalWrite (sw6, HIGH); //Ajustable Votls supply set to off state
      Serial.begin(9600);
      mp3.begin();                                      //Start communication with the DFplayer module
      uint16_t volume = mp3.getVolume();                //Get actual volume
      mp3.setVolume(30);                                //Set new volum (max is 30)
      uint16_t count = mp3.getTotalTrackCount();        //Get the total tracks on the SD card in case we want to sue this later...
    }

    //just a fucntion that we use to create delays in "ms"
    //without using the delay() function
    void waitMilliseconds(uint16_t msWait)
    {
      uint32_t start = millis();

      while ((millis() - start) < msWait)
      {
        // calling mp3.loop() periodically allows for notifications
        // to be handled without interrupts
        mp3.loop();
        delay(1);
      }
    }

    void loop()
    {
      if(!digitalRead(sw1))
      {
          mp3.playMp3FolderTrack(1);  // Play audio track 0001
          waitMilliseconds(1000);     // 1s of delay
      }

      if(!digitalRead(sw2))
      {
          mp3.playMp3FolderTrack(2);  // Play audio track 0002
          waitMilliseconds(1000);     // 1s of delay
      }

      if(!digitalRead(sw3))
      {
          mp3.playMp3FolderTrack(3);  // Play audio track 0003
          waitMilliseconds(1000);     // 1s of delay;
      }

      if(!digitalRead(sw4))
      {
          mp3.playMp3FolderTrack(4);  // Play audio track 0001
          waitMilliseconds(1000);     // 1s of delay
      }

      if(!digitalRead(sw5))
      {
          mp3.playMp3FolderTrack(5);  // Play audio track 0002
          waitMilliseconds(1000);     // 1s of delay
      }

      if(!digitalRead(sw6))
      {
          mp3.playMp3FolderTrack(6);  // Play audio track 0003
          waitMilliseconds(1000);     // 1s of delay;
      }

    }//end of void

title: DFplayer, Play sound when pin is high

Answers: 1

body:
BOUNCE 2

Basically, the mechanical part of buttons and switches vibrate slightly when closed or opened causing multiple undesired false states (similar to noise). This library filters out these undesired state changes. More about debouncing:

John Errington's Experiments with an Arduino : Using digital inputs: Switch bounce and solutions to it
Wikipedia article : http://en.wikipedia.org/wiki/Debounce#Contact_bounce
See the bottom of this page for a basic usage example and the "examples" folder for more.

The library is composed of three classes:

Debouncer : The code that does the actual debouncing. Only advanced users should play with this class.
Bounce : This is the general use library. It links the Debouncer to a hardware pin on your board.
Button : A special version of Bounce for buttons that are pressed.

https://github.com/thomasfredericks/Bounce2


body:
Led1 is on the left Led2 is on the right The code is making LED1 blink every second but it should also turn on Led2 so that whenever I press the push button it should turn off Led2. But Led2 isn't turning on when I run the code but Led1 is blinking
[![My schematic][1]][1]

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

    #include <avr/io.h>
    #define F_CPU 16000000
    #include <util/delay.h>
    #include <avr/interrupt.h>
    void setup();
    void initInterrupt0();
    // ---------Main Program -------------------------------------------
    int main()
    {
    setup();
    initInterrupt0();
    // ------ Event loop: Just flashing LED-----------------------------
    while (1)
    {
    PORTB ^= 0b00000010; // flash PB1 at 1 sec interval
    _delay_ms(1000);
    }
    }
    // -------- Initialization ------------------------------------------
    void setup( )
    {
    DDRB = 0b00000011; // LED PB0, PB1 active
    DDRD = 0b00000000; // all inputs
    PORTD = 0b00000100; // enable pullup on PD2
    }
    // ---------- Initializing Interrupt 0 ------------------------------
    void initInterrupt0( )
    {
    SREG |= 0b10000000; // set global interrupt enable bit
    EIMSK |= 0b00000001;// enable INT0
    EICRA |= 0b00000000; // trigger when button is low
    }
    // Interrupt Service Routine: Runs every time there is a change on button
    ISR (INT0_vect) // INT0 interrupt function
    {
    int PButton = PIND; // read portd
    if (PButton & 0b00000100) // is button PD2 pressed
    {
    PORTB |= 0b00000001; // turn PB0 on
    }
    else
    {
    PORTB &= 0b11111110; // turn PB0 off
    }
    }

title: Can someone check my schematic and code? My Led is not turning on

Answers: 0


body:
I'm investigating for some function of Lora E32-TTL-100.
Currently, I can communicate between two E32 like the following image:
[![enter image description here][1]][1]
But 3 days ago, I saw a person used only one MCU to scan the other E32 is power-on or power-off:
[![enter image description here][2]][2]
It's so interesting, and tried many way, but wasn't successful.
I found many documents but they always mention communicate 2 MCUs + 2 Loras.

Again, the purpose is how to do for the 1st E32 know that the 2nd E32 is power-on.
Can anyone please help me with it or have any ideas about it?

This's the link I followed https://www.mischianti.org/2019/11/10/lora-e32-device-for-arduino-esp32-or-esp8266-fixed-transmission-part-4/

This is the schema to simulate it:
[![schema][3]][3]
Thank.

  [1]: https://i.stack.imgur.com/mabR2.png
  [2]: https://i.stack.imgur.com/aAQIF.png
  [3]: https://i.stack.imgur.com/WELZb.png

title: How to scan Lora E32-TTL-100 devices by using only one ESP 8266 + Lora E32-TTL-100s?

Answers: 0


body:
I've a exhaust fan that runs when the humidity is high. When the exhaust fan is on it should work for 3 minutes and should wait another 5 minutes to on. I am a beginner to this struggling for almost 2 days now. with this code the led just blink and off

    int ledPin =  2;      // the number of the LED pin
    int ledState = LOW;             // ledState used to set the LED
    unsigned long previousMillis2 = 0;
    unsigned long previousMillis = 0;
    long interval = 10000;           // in
    long OnTime = 1000;           // milliseconds of on-time
    long OffTime = 2000;          // milliseconds of off-time

    void setup()
    {

      Serial.begin(9600);
      // set the digital pin as output:
      pinMode(ledPin, OUTPUT);
    }

    void loop()
    {

      unsigned long currentMillis2 = millis();

      if (currentMillis2 - previousMillis2 > interval) {
        // save the last time you blinked the LED

        // check to see if it's time to change the state of the LED
        Serial.print("hellohh ");
        unsigned long currentMillis = millis();

        if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
        {
          Serial.print("hellohh2 ");
          ledState = LOW;  // Turn it off
          previousMillis = currentMillis;  // Remember the time
          digitalWrite(ledPin, ledState);  // Update the actual LED
        }
        else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
        {
          Serial.print("hellohh 3");
          ledState = HIGH;  // turn it on
          previousMillis = currentMillis;
          previousMillis2 = 0; // Remember the time
          digitalWrite(ledPin, ledState);    // Update the actual LED

        }
      }
    }

title: How to use Multipile millis()

Answers: 2

body:
For your current issue (turning LEDs on and off after 1s / 2s, much of your code can be simplified:

    int ledPin =  2;     // Number of the LED pin
    int ledState = LOW;  // ledState used to set the LED
    unsigned long TimeLedOFF = 0;     //Time at which the LED was last turned off
    unsigned long TimeLedON = 0;      //Time at which the LED was last turned on
    unsigned long TimeLastCheck = 0;  //Time at which the next LED state was determined last
    long interval = 100;  // How often to check for changes in environment - should be shorter than your switching durations
    long OnTime = 1000;   // Milliseconds of on-time
    long OffTime = 2000;  // Milliseconds of off-time

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT); // set the LED pin as output:
    }

    void loop() {
      if (millis() - TimeLastCheck > interval) { //If the LED state should be evaluated again - "interval" has passed
        TimeLastCheck = millis();

        Serial.println("Determining next LED state");

        if (ledState == HIGH && (millis() - TimeLedON >= OnTime)) { //If LED was on for long enough
          Serial.println("OnTime elapsed. Turning off.");
          TimeLedOFF = millis(); // Remember the time
          ledState = LOW;        // Turn LED flag off
          digitalWrite(ledPin, ledState); // Update the actual LED
        }
        else if (ledState == LOW && (millis() - TimeLedOFF >= OffTime)) { //If LED was off for long enough
          Serial.println("OffTime elapsed. Turning on.");
          TimeLedON = millis(); // Remember the time
          ledState = HIGH;  // turn it on
          digitalWrite(ledPin, ledState);    // Update the actual LED
        }
      }
    }

This results in the LED being turned on for one second, then off for two seconds.

body:
If I understand correctly, you wrote an example code that switches an
LED between two states (on and off), and you are stuck because the
actual problem you want to solve is more complex than that. And indeed,
it seems to me that you want to manage a system with _three_ possible
states: it can be on or off but, when it is off, it can be ready to turn
on if the humidity is high, or it can be in the five minute wait.

The most natural way to think about this kind of systems is a [finite
state machine][fsm], or FSM. An FSM is defined by the set of states it
can be in, the conditions that make it switch states, and the actions
performed when doing so. If I correctly understood your specification,
your system can be either READY, RUNNING or WAITING, and the transitions
are:

* when READY, if the humidity is too high it switches to RUNNING; it
  turns the fan on when doing so
* when RUNNING, if it has been running for 3 minutes, it switches
  to WAITING and turns the fan off
* when WAITING, if it has been waiting for 5 minutes, it switches
  to READY

This can be illustrated by the following [state diagram][diag]:

[![state diagram][1]][1]

You should correct me at this stage if I did not fully understand your
specification. Otherwise, if the state diagram matches your
requirements, converting it to code is quite straightforward:

```c++
const uint32_t MINUTE = 60000;

void loop() {
    static enum {READY, RUNNING, WAITING} state;
    static uint32_t last_change;
    uint32_t now = millis();
    switch (state) {
        case READY:
            if (humidity_is_high()) {
                turn_fan_on();
                state = RUNNING;
                last_change = now;
            }
            break;
        case RUNNING:
            if (now - last_change >= 3 * MINUTE) {
                turn_fan_off();
                state = WAITING;
                last_change = now;
            }
            break;
        case WAITING:
            if (now - last_change >= 5 * MINUTE) {
                state = READY;
            }
            break;
    }
}
```

[1]: https://i.stack.imgur.com/grG0t.png
[fsm]: https://majenko.co.uk/blog/finite-state-machine
[diag]: https://en.wikipedia.org/wiki/State_diagram


body: I am building a robot that runs only when a matching rfid tag is identified..for that i need motor driver shield for running the motors and rfid module. The problem is if i attach the motor driver shield directly to arduino (MEGA) there won't be any 3.3v left which is necessary to power rfid so what i am thinking is connecting all the pins of arduino and shield seperately using jumper wires and leaving the 6 power sockets unconnected. If i connect 9v battery to arduino mega to power the rfid and micro-controller itself, what battery should be connected to the shield? Is it necessary to connect the GND of arduino awa shield even if power sources are seperate? Is it necessary to attach 2 switches for each source?

title: How to connect arduino mega 2650 and motor driver shield with seperate powers source?

Answers: 0


body:
For some weeks my latest dozen of Nano's isn't recognized any more by Win 10 computer: After two days of experiments I have suspicions:
1) Is there any change in Win10 since all Arduinos now are only shown in "Hidden devices" in the device manager? However, my old Uno and also an old Nano are still working despite of that... (The old nano has a chip named CH340G on the downside; the new nano's chip has no name at all).
2) The Nanos I'm trying to program now I got from China (order date 26 sep 2019) and they are said to be compatible with CH340SER. In fact I have programmed several of them early this year - turning back to them in October, upload was no longer possible.
3) In the meantime, I have switched from Arduino IDE 1.8.6 to 1.8.13 - however, I guess this is not the reason for my troubles since not even Windows recognizes the device when I plug it in...
Any advices to this problem?
Dieter

title: Arduino Nano not recognized on Windows 10

Answers: 0


body:
Im trying to find a way to run two codes from the one arduino me being an absolute begginer doesnt even know where to start the DHT11 thermometer is connected to a LCD showing temperature and humidity and uses a "DHTlib" library whereas the joystick controlling 2 servos has no library. I have two seperate working codes but putting them together and getting them to work is a big problem.

The concept is to control a space rover for my school project there will be a camera attathced to the servos so it can move along 2 axes and the thermometer is to prove the rover can gather imformation.

title: DHT11 thermometer connected to a LCD and 2 servos connected to joysrick

Answers: 0


body:
[![enter image description here][1]][1]I have constructed 2 ceptometers that measure light intensity. Each ceptometer consists of 50 photodiodes that are connected to 2 copper wires (+ and - of the photodiodes are on the same orientation). Those wires are soldered with cable (+ to the copper wire where the positive side of the photodiodes is and the ground wire soldered to the copper wire where the negative side of the photodiodes is). Then, pins were soldered to the cables so as to can be connected to the breadboard.

The paper where the protocol for the construction is present, states that a 1.5 ohms resistor needs to be connected to the copper wires so as to enhance the range of the signal that the ceptometers will give. However, it mentions that this step can be followed later and the resistor can be connected to the wires (that is something that makes sense). I need to mention that one more ceptometer is present that was constructed by another person the previous year and it has the 1.5 ohms resistor soldered on the copper wire. It is something very important to keep in mind for the rest of the text!

I decided to use an arduino uno for my experiment and I connected the 3 ceptometeres (the old from the previous year and the 2 that were constructed by me) to a breadboard. Firstly, I applied light to the ceptometers with a projector and I tried different resistors from 470R to 5K but the values I got were the same. I thought that a kind of signal disturbance or noise may has been caused and I made 3 opAmp circuits in 3 different breadboards. When the breadboards were connected to the Arduino I tried the same resistors again but the values I got were the same. For the old ceptometer that has the 1.5 ohms resistor soldered to the copper wires the change of resistors altered a lot the signal and it gave a wide range of values. Here I have to say that when I applied to the 1.5 ohms resistor to the new captometers I got a pure 0 as a value. And it was the same when I placed them under sunlight.

When I converted the output of the Arduino to voltage signal by multiplying it with 5 and then divide it with 1023 I had the same voltage signal as when I measured it with the multimeter. And it was the same under both artificial and sun light. So, I can imagine that it is something that depends on the resistor that is not applied to the copper wires. I mean that maybe this is the case that I do not get a wide range of values like the old ceptometer but only 20 units

My question is: Do you know any way to enhance the range of the output or do you have any recommendation? Thank you a lot in advance!

With kind regards,

Dimitrios

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

title: How can i increase the range of values that a light sensor gives?

Answers: 1

body:
The circuit is a current-to-voltage converter.  The - input to the op-amp is held at 0 (the voltage at the + input, since it is grounded) so there will be no voltage across the diodes.  The current drawn by the diodes is supplied by the op-amp output through the feedback resistor, so the larger that value, the greater the output voltage will be at any given current.  The short answer is that to increase the output voltage, you need to increase the feedback resistor. (7 ohms seems pretty small to me, unless your diodes draw a LOT of current.)

The other complicating issue is that this circuit depends on the op-amp having a low input offset voltage, since its value (~2 mV for the LM358) causes output errors.  Normally a low-offset-voltage op-amp would be used here, but maybe the use of so many diodes makes a large enough current to swamp the offset error.  If increasing the feedback R doesn't help, you might try a different op-amp (even another LM358) in case the offset of the one you have is trying to force a negative output and that's why you see 0.

Edit 11-8-20:  I looked up the sensor used in the PAR-BAR article that seems to be the source of your circuit.  It pulls about 10 microamps at 1000 lux, so 50 of them would give 500 microamps.  If you want to get (say) a 5V output at 1000 lux, you'd need a feedback resistor of 5/0.0005 = 10 kOhms.  That's without the 1.5 ohm shunt.  Also, are you applying your test illumination evenly over all 50 sensors?  The above calculation assumes that all get 1000 lux.

If you have a single sensor available, I'd recommend breadboarding with just that and a 500 kOhm feedback resistor, and no shunt.  That way there will be no issue about equal illumination.  If you still have problems, and you are committed to the LM358 for some reason, try using a simple circuit to compensate for input offset.  These typically involve a potentiometer (could be a trimmer in the final unit) that adjusts a very small voltage applied to the + input.  In your tests you may find that it needs to be negative, which you would have to apply from some external source (since there is no - supply on the Arduino).  If that's needed to resolve your problem, consider a better op-amp or a different circuit configuration.

Edit 11-9-20: Had another look at the PAR-bar article and noticed that they are measuring *differential voltage* across the photodiode array, which is not the same as your current-to-voltage converter (although that is indeed typical of photodiode circuits).  The voltages that they get are 30 mV or less.  I suggest you get a DMM and measure the voltage across the array, without any connection to other circuitry.  Cheap DMMs have 200 mV full-scale, which should at least show you what's going on.  The article used an expensive datalogger and only *suggests* that Arduino-type solutions may be possible, but gives no circuits.  You probably don't need a true differential amp, since the photo voltage is always in the same direction.


body:
I'm trying to control my arduino with a raspberry pi with python instead of C++ (which I don't know). I've found code to take a string from serial and print it, but instead I'd like to use IRsend to use the code. Unfortunately I'm getting the error invalid conversion from 'char*' to 'uint32_t {aka long unsigned int}' [-fpermissive]. I know this must be an incredibly dumb question but is there a int() function for uint32_t for arduino C++? that I could set blah=uint32_t(buf) and then use my irsend.sendNEC(buf, 32)? If it's not painfully obvious, I don't know C++ and my python isn't great.

    #include <IRremote.h>

    char buf[80];

    int readline(int readch, char *buffer, int len) {
      static int pos = 0;
      int rpos;

      if (readch > 0) {
        switch (readch) {
          case '\r': // Ignore CR
            break;
          case '\n': // Return on new-line
            rpos = pos;
            pos = 0; // Reset position index ready for next time
            return rpos;
          default:
            if (pos < len-1) {
              buffer[pos++] = readch;
              buffer[pos] = 0;
            }
        }
      }
      return 0;
    }

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

    IRsend irsend;

    void loop() {
      if (readline(Serial.read(), buf, 80) > 0) {
        Serial.print("You entered: >");
        Serial.print(buf);
        Serial.println("<");
        irsend.sendNEC(buf, 32);

      }
    }

Error:

    /home/pi/Desktop/sendIRfromserial2addingir/sendIRfromserial2addingir.ino: 39:27: warning: invalid conversion from 'char*' to 'uint32_t {aka long unsigned int}' [-fpermissive]
                 irsend.sendNEC(buf, 32);

                      ^

In file included from

    /home/pi/Desktop/sendIRfromserial2addingir/sendIRfromserial2addingir.ino:1:0:
    /home/pi/Arduino/libraries/IRremote/src/IRremote.h:444:10: note:   initializing argument 1 of 'void IRsend::sendNEC(uint32_t, uint8_t, bool)'
         void sendNEC(uint32_t data, uint8_t nbits, bool repeat = false);
              ^~~~~~~`

title: How can I use IRsend with a string or convert a char from serial to uint32_t?

Answers: 1

body:
Instead of

    irsend.sendNEC(buf, 32);

cast it to an unsigned int32 type:

    irsend.sendNEC((uint32_t) buf, 32);


body:
There's no end to my frustration trying to figure out how the arduino build system works -- despite my best efforts I just can't seem to grok it. Anyhow, I did this:

```
ALTERNATE_CORE_PATH=/path/to/MightyCore/avr
BOARD_TAG=324
...
```

`make show_boards` shows me several boards available, including `324`. Yet whenever I try to build my project, I get this error:

```
avr-g++: error: missing device or architecture after ‘-mmcu=’
```

Can someone point me in the right direction?

Thanks.

title: Arduino.Mk together with MightyCore

Answers: 1

body:
Resolved with the following Makefile options:

```
BOARD_TAG=324
MCU=atmega324a
VARIANT=standard
```


body:
    //www.elegoo.com

    #include <RobotIRremote.h>

    #define RECV_PIN  12        //Infrared signal receiving pin
    #define LED       13        //define LED pin
    #define L         16738455
    #define UNKNOWN_L 1386468383

    bool state = LOW;           //define default input mode
    unsigned long val;

    IRrecv irrecv(RECV_PIN);   //initialization
    decode_results results;   //Define structure type

    void stateChange() {
      state = !state;
      digitalWrite(LED, state);
    }

    void setup() {
      pinMode(LED, OUTPUT); //initialize LED as an output
      Serial.begin(9600);  // debug output at 9600 baud
      irrecv.enableIRIn();  // Start receiving
    }

    void loop() {
      if (irrecv.decode(&results)) {
        val = results.value;
        Serial.println(val);
        irrecv.resume();      // Receive the next value
        delay(150);
        if(val == L || val == UNKNOWN_L) {
          stateChange();
        }
      }
    }

It says that there are errors compiling from my Arduino Uno board. How can I fix this?

title: How do I fix my code on the Arduino IDE App?

Answers: 1

body:
This can solve your issue:

Sketch > Include Library > Manage Libraries

In the 'Filter your search' box, type 'irremote'

Click on 'IRremote by shirriff'

[![library picture][1]][1]

Click 'Install'

Wait for installation to finish.

Click 'Close'.

Then try compiling the sketch again. The error might go.

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


body:
I am currently using [these motors][1] and driving them off [these drivers][2] and an arduino uno, and alternatively trying to make them turn using the setup in step 6 (both with l298n and without) in [this instructable][3]. I have 4 motors and all are exhibiting the same behaviour.

Using the drivers, I just sent a constant PWM via PWM pin, and the motor would only spin at high values around 255, but even then only when I touch the motor does it start spinning. This spinning is then not even smooth, it pauses a bit every second or so and results in a sort of jittering. After a bit more, plugging the motors in it now just makes an increasingly louder whining noise, kind of like it's getting ready to take off but doesnt really spin. Code used here is just basic as below:

    void setup () {

    pinMode(9, OUTPUT);

    }

    void loop (){

    analogWrite(9, 255);

    }

Using the instructable setups, I've wired exactly the same way (wiring for l298N version is in step 10, wiring for discrete steps is just directly pwms to the motor), but the motors will not spin like theirs do (same poles and slots, 12n14p). Mine just jitters back and forth in tiny steps and looks like it's just twitching. Code used is exactly as at the end of 'step 6'.

[Imgur album of issues][4]

  [1]: https://hobbyking.com/en_us/2206-140kv-brushless-gimbal-motor-ideal-for-gopro-style-cameras.html
  [2]: https://www.iot-store.com.au/products/brushless-4-click-bldc-motor-driver?utm_campaign=order-confirmation-email&utm_medium=email&utm_content=product&utm_term=link&utm_source=OrderlyEmails
  [3]: https://www.instructables.com/DIY-Brushless-Gimbal-with-Arduino/
  [4]: https://i.stack.imgur.com/WSQ59.jpg

title: Brushless motor vibration/jitter/noise - arduino uno

Answers: 0


body:
I have a dev board for my attiny85.
when connecting it to the computer I get "unknown USB device(device descriptor request failed)"
although I have the needed drivers, so I thought of trying using my nodemcu.
Tried connecting the SPI (to the nodemcu hmiso;hmosi;hcslk;hcs)and upload using "arduino as ISP" and compitable settings(https://www.hackster.io/arjun/programming-attiny85-with-arduino-uno-afb829).
pressing "burn bootloadre" using this way gives me errors:

"avrdude: stk500_recv(): programmer is not responding

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

......

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

Error while burning bootloader."

***EDIT:

After changing a line(#define USE_OLD_STYLE_WIRING) in ArduinoISP (from example)
the error code changed a bit and it shows up much faster:

"Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "ATtiny25/45/85, ATtiny85, Internal 8 MHz"

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

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

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x61

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x67

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xc1

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xc4

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xc5

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xa1

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xcc

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe2

Error while burning bootloader."

Any help on how to use nodemcu to program attiny85 will be great
thanks

title: use Nodemcu to program Attiny85

Answers: 1

body:
Modifications to the ArduinoISP.ino sketch
==========================================
I made the following changes to the ArduinoISP.ino file it exists in IDE version 1.8.13, and uploaded it to the NodeMCU board.

In short, I commented out (by way of #if 0) the heartbeat, err, etc LED related stuff.  Not doing this causes the board to reset for reasons that would probably be apparent if I researched it, but I haven't and since I don't plan on using the LEDs and that you may not, I figured I would get this to you sooner.

I changed RESET to be SS which on NodeMCU is D8.

Why LED related code causes resets
----------------------------------
... Out of curiosity I just went and looked at the ESP-12F and ESP8266EX datasheets.  GPIO7, GPIO8, GPIO9 all go to the ESP-12F's SPI flash (program storage), so ostensibly monkeying with them interferes with the modules ability to keep executing from the SPI flash.  They're not routed to NodeMCU pins, probably for that reason.  So there's the answer to that.

Differences
-----------
````diff
@@ -70,7 +70,7 @@
 // The standard pin configuration.
 #ifndef ARDUINO_HOODLOADER2

-#define RESET     10 // Use pin 10 to reset the target rather than SS
+#define RESET     SS // Use pin 10 to reset the target rather than SS
 #define LED_HB    9
 #define LED_ERR   8
 #define LED_PMODE 7
@@ -216,15 +216,17 @@

 #endif

 void setup() {

   SERIAL.begin(BAUDRATE);

+#if 0
   pinMode(LED_PMODE, OUTPUT);
   pulse(LED_PMODE, 2);
   pinMode(LED_ERR, OUTPUT);
   pulse(LED_ERR, 2);
   pinMode(LED_HB, OUTPUT);
   pulse(LED_HB, 2);
+#endif

 }

@@ -276,6 +278,7 @@
 }

 void loop(void) {
+#if 0
   // is pmode active?
   if (pmode) {
     digitalWrite(LED_PMODE, HIGH);
@@ -291,6 +294,7 @@

   // light the heartbeat LED
   heartbeat();
+#endif
   if (SERIAL.available()) {
     avrisp();
   }
````

NodeMCU to ATTiny85 ISP Wiring
==============================
The board is wired to the ATTiny85 as follows:

````
NODEMCU 3.3V -> ATTINY85 PIN 8
NODEMCU GND  -> ATTINY85 PIN 4
NODEMCU D5   -> ATTINY85 PIN 7
NODEMCU D6   -> ATTINY85 PIN 6
NODEMCU D7   -> ATTINY85 PIN 5
NODEMCU D8   -> ATTINY85 PIN 1
````

On the NodeMCU you'll find all 6 of these together on the right.

Verifying AVRDUDE functioning
=============================

avrdude -P /dev/ttyUSB0 -c stk500v1 -b 19200 -p attiny85

````avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e930b (probably t85)

avrdude: safemode: Fuses OK (E:FF, H:DF, L:71)

avrdude done.  Thank you.
````

I've been playing with this chip, so don't be surprised that I don't have the same fuse values you have.


body:
I have optimised it as much as I feel I can and want to know what suggestions you have that could make it more efficient etc.

Note: I know the array goes on forever :)

    volatile uint16_t IRCode[]={340,171,21,21,21,21,21,21,21,64,21,21,21,21,21,21,21,21,21,64,21,21,21,64,21,21,21,64,21,64,21,64,21,64,21,64,21,21,21,21,21,21,21,64,21,21,21,21,21,21,21,21,21,64,21,64,21,64,21,21,21,64,21,64,21,64,21,1556,340,86,21,3654}; // ProntoHex to uint16_t delete first 4 array numbers.
    volatile uint16_t MicrosPassed;
    volatile uint8_t Array_Seq;
    uint8_t State;

    void setup() {
      Config(); // Config sketch will set working settings for different microcontrollers.
      SendIRCode();
    }

    void loop() {

    }

    void SendIRCode() {
      switch(State) {
        case 1:
          TCCR1A&=63; // Opposite of case 0 -193 = 63
          State=0;
          break;

        case 0:
          TCCR1A|=192;
          State=1;
          break;
      }
    }

    void Config() {
      DDRB|=10;
      ICR1=416;
      OCR1A=9983;
      TCCR1A=2;
      TCCR1B=24;
      TCCR1B|=1;
      TIMSK1=1;
    }

    ISR(TIMER1_OVF_vect) {
      MicrosPassed++;
      if(MicrosPassed==IRCode[Array_Seq]) {
        SendIRCode();
        MicrosPassed=0;
        Array_Seq++;
           }
    }

title: What can I do to optimise this code?

Answers: 1

body:
As hinted by chrisl in a comment, there are various criteria you may
want to optimize for: speed, size, readability... Judging from the
current state of this sketch, I would say that your first goal at this
point should be to optimize for readability.

The hardest think to make sense of are most of the plain numbers. When
setting registers that are bit fields, do not use decimal values: use
either hexadecimal or binary. Or, better yet, use the names of the bits.
The avr-libc defines those names, as well as the macro
`_BV(bit_position)`, which expands to `(1 << bit_position)` and is meant
to be used with those names:

```cpp
void Config() {
  DDRB   |= _BV(PB1) | _BV(PB3);  // PB1 and PB3 as output
  ICR1    =  416;        // timer period = 417 cycles
  OCR1A   = 9983;        // ???
  TCCR1A  = _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
  TCCR1B  = _BV(WGM12) | _BV(WGM13);  // ...ditto
  TCCR1B |= _BV(CS10);   // clock @ F_CPU
  TIMSK1  = _BV(TOIE1);  // enable TIMER1_OVF interrupt
}
```

Granted, the bit names are somewhat obscure, but they do make the
program easier to read if you have the datasheet nearby. I do like to
have comments that make the code understandable even without reading the
datasheet.

Note that evaluating those expressions does not make the program any
slower, as they are evaluated at compile time.

When a variable is used in a single function, it is better to define it
in that function. Keeping the definition close to where the variable is
used makes the code more “local” and thus easier to read. Since you want
some of those variables to remember their values across invocations of
the function, give them the `static` qualifier.

You may not need to optimize this program for speed. There is, however,
a low hanging fruit here: remove the `volatile` keywords. This keyword
is meant to explicitly _disable_ some compiler optimizations that are
unsafe when a variable is shared between the interrupt and non-interrupt
contexts. None of the variable you use needs this.

If I understood correctly, the function `SendIRCode()` just toggles a
couple of bits in `TCCR1A`. You can simplify it to this:

```c++
void SendIRCode() {
  TCCR1A ^= _BV(COM1A0) | _BV(COM1A1);  // toggle PWM output on OC1A
}
```

Finally, there is I believe a bug in this sketch. The variable
`Array_Seq` is continuously incremented and never reset. The program
will then end up reading past the end of the `IRCode` array.


body:
I'm trying to communicate via I2C on the Raspi, programming it with the Arduino Create Web Editor.  I have enabled I2C on the pi, made sure /dev/i2c-1 exists.  The pi can see the device (just a simple LCD for now) via the command line on the pi itself.

I'm getting the error "no I2C device available for Wire10".  I'm wired to SDA1/SCL1 (pins 3 and 5).  I have previously tested the display and the code on an UNO and it works fine.

Please help!  I saw someone had this issue before and simply said "I fixed it" but didn't provide an explanation.

Thanks!  (Code below for reference)

    /* I2C LCD with Arduino example code. More info: https://www.makerguides.com */

    // Include the libraries:
    // LiquidCrystal_I2C.h: https://github.com/johnrickman/LiquidCrystal_I2C
    #include <Wire.h> // Library for I2C communication
    #include <LiquidCrystal_I2C.h> // Library for LCD

    // Wiring: SDA pin is connected to A4 and SCL pin to A5.
    // Connect to LCD via I2C, default address 0x27 (A0-A2 not jumpered)
    LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4); // Change to (0x27,16,2) for 16x2 LCD.

    void setup() {
      // Initiate the LCD:
      lcd.init();
      lcd.backlight();
    }

    void loop() {
      // Print 'Hello World!' on the first line of the LCD:
      lcd.setCursor(0, 0); // Set the cursor on the first column and first row.
      lcd.print("Hello Worlds!"); // Print the string "Hello World!"
      lcd.setCursor(2, 1); //Set the cursor on the third column and the second row (counting starts at 0!).
      lcd.print("LCD tutorial");
    }

title: Arduino Create and Raspi I2C

Answers: 0


body:
this is my first Project on an ESP.
I found a Code for a coffee-grinder-timer, which is programmed for a ESP8266, but unfortunately meanwhile the Sonoff changed to the ESP8285 with internal Flash.
I presume this is the reason for a memory problem. By default the times are according to the code 1000ms and 2000ms, but on the WebPage are the following times are displayed:

 - Singleshot: 16711680ms
 - Doubleshot: 807611680ms

Beside this problem I can't change these values by pressing the save-button.
what is my mistake?

```
// Libraries
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <TTBOUNCE.h>
#include <EEPROM.h>
extern "C" {
#include "user_interface.h"
}

//======SERVER PART======================================================
const char* ssid     = "SSID";
const char* password = "password";
ESP8266WebServer server ( 80 );
char htmlResponse[3000];
//======LOKALER PART======================================================
os_timer_t myTimer;
bool tickOccured;
bool timerrunning;
int RelaisPin = 13;                 // GPIO13 Blaue LED auf dem Sonoff
TTBOUNCE b = TTBOUNCE(0);

int time_ss = 1000;
int time_ds = 2000;

void handleRoot() {

  snprintf ( htmlResponse, 3000,
"<!DOCTYPE html>\
\
  \
    <meta charset=\"utf-8\">\
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
  \
  \

Zeiten für Singleshot und Doubleshot
\

Singleshot: %d% ms
\
          <input type='text' name='date_ss' id='date_ss' size=2 autofocus> ms \

Doubleshot: %d% ms
\
          <input type='text' name='date_ds' id='date_ds' size=2 autofocus> ms \

\

<button id=\"save_button\">Save</button>\

\
    \
    \
  \
",

time_ss,
time_ds
);

   server.send ( 200, "text/html", htmlResponse );

}

void handleSave() {
  if (server.arg("ss")!= ""){
    Serial.println("Singleshot: " + server.arg("ss"));
    time_ss = server.arg("ss").toInt();
    eeWriteInt(0, server.arg("ss").toInt());
  }
    if (server.arg("ds")!= ""){
    Serial.println("Doubleshot: " + server.arg("ds"));
    time_ds = server.arg("ds").toInt();
    eeWriteInt(4, server.arg("ds").toInt());
  }

}

// start of timerCallback
void timerCallback(void *pArg) {
Serial.println("Tick OccurredCB");
      tickOccured = true;
}

void setup() {
//======SERVER PART======================================================
  // Start serial
  Serial.begin(115200);
  delay(100);
WiFi.mode(WIFI_STA);
  // Connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  server.on ( "/", handleRoot );
  server.on ("/save", handleSave);

  server.begin();
  Serial.println ( "HTTP server started" );
//======LOKALER PART======================================================
  os_timer_setfn(&myTimer, timerCallback, NULL);
  pinMode(RelaisPin, OUTPUT);       // GPIO13 als Ausgang definieren
  b.attachClick(click);         //attach the click method to the click event
  b.attachDoubleClick(doubleClick);//attach the double click method to the double click event
  b.attachPress(press);        //attach the press method to the press event
  delay(50);
  digitalWrite(RelaisPin, HIGH);  // turn LED ON
  tickOccured = false;
  timerrunning = false;
   EEPROM.begin(8);  //Initialize EEPROM
   time_ss = eeGetInt(0);
   time_ds = eeGetInt(4);
}

void loop() {
//======SERVER PART======================================================
  server.handleClient();
//======LOKALER PART======================================================
  b.update();
  delay(10);

   if (tickOccured == true)
 {
    Serial.println("Timer ausgelaufen");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
 }

 yield();  // or delay(0);
}

void click(){
  if (!timerrunning)
  {
    Serial.println("Clicked");
    digitalWrite(RelaisPin, LOW);  // turn LED ON
    os_timer_arm(&myTimer, time_ss, false);
    timerrunning = true;
  }
  else
    {
    Serial.println("ABORT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
    }
}

void doubleClick(){
    if (!timerrunning)
  {
    Serial.println("DoubleClicked");
    digitalWrite(RelaisPin, LOW);  // turn LED ON
    os_timer_arm(&myTimer, time_ds, false);
    timerrunning = true;
  }
    else
    {
    Serial.println("ABORT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
    }
}

void press(){
  if (!timerrunning)
  {
    Serial.println("long_Clicked");
    digitalWrite(RelaisPin, LOW);  // turn LED ON
    os_timer_arm(&myTimer, time_ds-time_ss, false);
    timerrunning = true;
  }
 else
    {
    Serial.println("ABORT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
    }
}

 void eeWriteInt(int pos, int val) {
    byte* p = (byte*) &val;
    EEPROM.write(pos, *p);
    EEPROM.write(pos + 1, *(p + 1));
    EEPROM.write(pos + 2, *(p + 2));
    EEPROM.write(pos + 3, *(p + 3));
    EEPROM.commit();
}

int eeGetInt(int pos) {
  int val;
  byte* p = (byte*) &val;
  *p        = EEPROM.read(pos);
  *(p + 1)  = EEPROM.read(pos + 1);
  *(p + 2)  = EEPROM.read(pos + 2);
  *(p + 3)  = EEPROM.read(pos + 3);
  return val;
}

title: Timer with Webserver ESP8285

Answers: 1

body:
At least one problem is this:
````
          <h3>Singleshot: %d% ms </h3>\
````

If you want a literal percent sign, you would need to double it, a form of escaping:

````
          <h3>Singleshot: %d%% ms </h3>\
````

It's not entirely clear how this implementation of snprintf handles %<space>, but experiments here show that it isn't being forgiving and merely interpreting it as %%.

In C and C++ and by proxy "arduino", adjacent string literals are concatenated at compile time into one logical string literal, so you can do that rather than \\, which you may find cleaner.

It should also be possible to just .print the chunks of your payload to the stream rather than to cobble together one large string as a payload.