text:
How to get timestamp of when the data was collected
Basically I want to be able to display the time the arduino collected the data with the data value, not the time the arduino printed off the data. Theres a timestamp feature on the console, however I want to find the time the data was collected.
I'm a bit new to this so any help is greatly appreciated!

did you record the time when the data was collected?

Which Arduino are you using (just in case you mis-tagged the question)?

By itself, an arduino-uno's only timestamp is the number of milliseconds since reset.
Serial.println(millis());

Getting a "timestamp" of when data is collected is entirely down to you.
Most Arduinos don't have any concept of the current time, only the time since the program started running. To know what the time "now" is you have to have some mechanism to tell the Arduino what the time is, along with a method of keeping track of that time.
There are devices called Real-Time Clock (RTC) modules which keep track of the time for you. They don't magically know the time - you still have to tell them at least once.
You could tell it the time through the serial port to set the clock - from then on (assuming the RTC has power) the RTC will know what the time is.
Another option to get the time into the RTC is to use an internet connection (ESP8266, WiFi shield, Ethernet shield, etc) to perform a Network Time Protocol (NTP) query to a time server on the internet (such as pool.ntp.org) to get the current time and update the RTC.  This should be done regularly to correct any drift in the RTC.
Once you have an RTC and a method of setting the time you can query the time whenever you sample some data and store that time along with the data in whatever way is most suitable for your situation.

It depends on how you define the time stamp. A Unix timestamp is the number of seconds elapsed since Unix epoch time, i.e. January 1 1970 00:00 UTC, this is a very common time stamp. You can setup with NTP via the internet, or you can use a RTC on your board. How you do it depends on how accurate you want it and what you have available. Try this link it may help: https://currentmillis.com/


text:
Trying to use Nano Every as a sort of USB logic analyzer, but can't isolate it from "device under observation"
Here's the scenario: I have a radio that displays information on a 1602A LCD. The 1602A is plugged into a header so I can easily pull it out and instead plug in logic analyzer leads. The logic analyzer decodes the HD44780 protocol and shows me the data that would have gone to the 1602A. The logic analyzer, not surprisingly, doesn't have any noticeable effect on the radio.
Now I want to replace the logic analyzer with a Nano Every. I wired it up so that the signals to be observed are connected to digital input pins on the Every. The Every is powered through USB and doesn't intentionally draw any power from the radio. Everything runs as expected and the Every shuffles readings to the PC via serial. HOWEVER, in this combination, the radio draws at least twice as much current from the power supply and the radio's voltage regulators begin to heat up substantially!
I would have thought that the digital input pins of the Every are high enough impedance that it would have no significant effect on the radio, just like the logic analyzer didn't. I can only assume that "significant" current is flowing from the radio's LCD header into the Nano Self's input pins, since they are the only connection between the radio and the Nano.
So, I guess my question is this: How can I make the Nano Self work more like a logic analyzer? Do I need additional circuitry between the signals being tested and the Self's input pins, perhaps logic buffers? Or might something else be going on here?

you may have one of the pins set as an output ... determine which pin(s) are causing the problem ... please post your code if you can

This is my first time working with the port registers and I had "PORTD.DIRCLR = 11111111; // Set the entire port to INPUT". I think it should have been B00000000 instead, correct?

11111111 is a decimal number ... B11111111 is binary .... you could do DDRD = B00000000; to set the D register pins as inputs

Sorry, that was a typo -- the code had the B prefix for the binary literal. I don't think DDRD is even defined for the Arduino Nano Every or other ATMega4809 based Arduinos. It might be if "registrly emulation" is selected under Tools in the IDE, but I decided to use the new port registers instead..

@jsotola was correct and the software defined pin directions incorrectly. Looks like I fried one of the pins in the process (multimeter shows continuity between the pin and ground), but when I rewired to a new pin on Port D and ran the corrected software, everything seems to work as expected!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Measuring solar power with an Arduino
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.

transformers require AC

You can't measure DC current with a coil; you would need a Hall-effect sensor, or a very small resistor and measure the voltage drop across it. You need at least a diode between solar panels and battery, and possibly a proper charger. You need to be sure the battery voltage doesn't exceed 12V by too much, or you will put more than 5V on the Arduino's input pin. What is a "deep cell battery"? What chemistry is it and what capacity does it have? What is the power rating of the solar panels?

I was planning on using a small resistor with the coil I just didn't put it in the schematic, but I think the hall effect sensor would probably work better.   I meant deep cycle battery - lead acid, 12V 9Ah.  I didn't have a specific solar cell picked out yet, but I just found these: https://www.sparkfun.com/products/14798

This question might do better on the EE Stack Exchange site.

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.

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.

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

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.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Drawing a bar graph in a LCD
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?

review how to operate on arrays ... https://www.arduino.cc/reference/en/language/variables/data-types/array/

your code repeatedly prints to location 0,0 ... i do not see what is unclear about that

You're using an array vector2[] inside loop() that has an undefined size because you did not properly declare it. The error is quite descriptive and will also highlight the line where the error was found.

Okay got the part of the vector2 already! Thanks

How do you hope to draw a 16 element bar graph in a text LCD? The closest you could get is to use user-defined characters to have partial blocks for a vertical graph.

@Majenko that was what I was thinking about but can't think of a way to put a column character on both rows or how to draw it deppending on the value of the value2*potentiometer

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 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):
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:
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:
▁█ ▄ ▆█▇   ▃ ▃▇
██▃█▇███▅▆▇█▆██▃


text:
Button and twist knob to send keystroke to PC
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

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 that can do it for you.

Thanks for that. I can get a different board if it’s more suitable for the application. Would this take over the keyboard? Or would the keyboard still be fully functional while my project is connected and sending keystrokes?

connect two keyboards to your PC and see

@Craig Your keyboard would be fully functional. You can connect multiple keyboards to a computer and they all work as one keyboard.

Thank you, @majenko. I’ll order a Arduino Micro (seems to be the new version of the Leonardo?) and the Rotary Encoder I linked in my post. Your post indicated I don’t need software on the pc? Basically connect the Micro, it will get power off the same USB that is sending the signal - and write the code to send the commands using Keyboard.h?

@Craig The Micro is to the Leonardo what the Nano is to the Uno. With that you don't need software on your PC. Just Keyboard.begin(); and Keyboard.println("format c:"); https://www.arduino.cc/reference/en/language/functions/usb/keyboard/

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.

Thanks. I think that’s the hard part. Converting things from the board, into a signal that the pc sees as a keystroke. I’ll look around.


text:
Uno Wifi Rev2 - sending program via WIFI
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?

two different unrelated questions ... please delete the one about the RGB LED and post separately

Does this answer your question? https://arduino.stackexchange.com/questions/70774/make-ota-work-with-arduino-uno-wifi

sad is, almost a year later the answer there is still valid. while there is a progress they still didn't publish the OTA update for Uno WiFi Rev 2.


text:
Raspberry Pi 3B+ BLE communication to Arduino Nano 33 IOT
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?

this describes the Arduino side ... you will have to figure out the RPi side since it is off topic here .. https://www.arduino.cc/en/Reference/ArduinoBLE

Okay thank you.

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)

Will this work on the Pi 3B+ because I don't know if it has BLE.

If you add a BT adapter, you should be able to.

The specs on the 3B+ say it has BLE, so this might work.  I have not tested it however; only with an Ubuntu 20.04 LTS system with (Anaconda) Python 3.7.7.


text:
No response in Serial Monitor from es8266 with Arduino nano
I have exactly this model of esp8266:

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.

with io 0 LOW the esp8266 starts in flashing mode. add a pull-up resistor for io 0. the TX pin of nano is wired to RX pin of the USB chip. so to have RX to TX wire TX to TX :-)

how did you remove the ATmega from Nano?

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.


text:
My nodemcu esp8266 is heating a lot and the on board LED of gpio16 is On continuously. What's the Reason of heating?
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

heating is caused by too much current being drawn

what do you have connected to the nodemcu? ... how is it conected?

How did you connect the batteries? 2. What else is connected to the NodeMCU? 3. Where exactly (which component) does the heat come from?

Ok so my Nodemcu is connected with RELAY of 5v the heat is coming from the microcontroller.

And can you answer question 1? How did you connect the batteries?

What is the output voltage of your Lion batteries? The Nodemcu is a 3.3V device. It's voltage regulator needs an input voltage of  7V - 12V, based on the searching I did. If your batteries put out ≈10V then 2 of them in series is too much for the input of the NodeMCU's voltage regulator.

In series both batteries took out 7

Volt and 4000 mah

Is it too much ??


text:
Combining an NRF24L01 transmitter/receiver with an Adafruit Motor Shield V1?
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:
Motor shield and wireless transceiver compete for same pins
A difference in my project is that I'm not using stepper motors, so perhaps that makes a difference?

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.


text:
Using TX/RX serial pins to communicate over USB
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.

why do you want to use a second FTDI?

Are you looking for something like this: https://www.obdev.at/products/vusb/index.html ? Not quite clear to me why you don't want to use the builtin FTDI and associated Adruino tools

Instead of moving the data connection, wouldn't it be easier to add a second USB port for the power supply and connect it to the 5V pin?

Unrelated; you shouldn't connect the the 5V from the USB to the VIN pin. Connect it directly to the 5V/Vcc pin. The VIN pin requires at least 7 volts, and will regulate this down to 5V. Since you already have 5V you can bypass the regulator.

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.

Ah, sorry, my mistake.
So, if I wanted to add an additional USB port, I would also need an additional USB to serial converter chip? Does the included chip only work with the included USB port?
Sorry if my question sounded a bit odd, I'm a student and this is more of a learning exercise. Thanks for the helpful answer!

If you want to add an extra USB port you will have to use SoftwareSerial to communicate with some FT232-like board through other pins that TX/RX.


text:
Arduino Time Library and RTC Libraries
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.
#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:
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

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:
// 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. 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 is designed to provide timekeeping in this
fashion. It all boils down to:
// 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
provided with RTClib.

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
RTC.writeSqwPinMode(DS1307_SquareWave1HZ);

Edit 2: Commenting on the update to the question:

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

Correct.

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

Correct. Date is 2015-07-14.

// 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).

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().

// 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.

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().

-I have read much about these libraries and still confused.  Thanks for your help.  Couple follow ups:  1. Does function now.hour() get time from RTC?  2.  Does hour() get time from Time Library? 3. Does setSyncProvider() set  hour() to the RTC ?

now is the time from the RTC at the moment you assign the now object. .hour() is just the hour contained inside that object. hour() is the time from the TimeLib library, yes. setSyncProvider() doesn't send anything to the RTC, it gets the time from the RTC on a regular basis and updates the TimeLib with the current time.

@Edgar Bonet - Using interrupt pin looks very nice and clean. If Pin 2 is used on Arduino for the interrupt, which pin does Pin 2 connect to  on the RTC?  I assume it is in addition to the SCL and SDA pins (?).

"setSyncProvider() doesn't send anything to the RTC, it gets the time from the RTC on a regular basis and updates the TimeLib with the current time."    Yes, so If hour() is the time from the TimeLib Library then setSyncProvider() makes hour() equal to RTC hour?

It's a little more complex than that. TimeLib uses millis() to keep track of the time. It regularly updates its internal idea of what the time is depending on setSyncInterval(). when you ask for hour(), if more time has passed since it last got the real time that you specified in setSyncInterval() it will go and get the time from the RTC. Otherwise it will just tell you what it thinks the time is according to its own internal calculations.

I updated my post with help provided. Almost have it understood.

Why does output alternate values for tm.hour, etc?  See bottom of updated question. thanks

Because you're constantly changing the sync provider and interval. You set those once and once only in setup, and never again.

Thanks that worked.    Looking at my updated code, to make sure I am not deceiving myself, are the outputs of  tm.Hour tm.Minute. tm.Second  Time Library values which are updated from the RTC  every 5 seconds ?  And am I not creating an Object every loop?

That looks right, yes. Though you don't need the tmElements_t struct at all since all you're dealing with is simple numbers. tmElements_t is just a convenient way of bundling them all together if you want to pass it to another function. Just Serial.print(hour());

thanks for all of your help.  I will post the final code as an answer for anyone else needing to learn this.


text:
Arduino piezo-buzzer melody for car alarm
I would like to play car alarm sound through Arduino buzzer - something like this https://youtu.be/nuPHwijMsIg
Does anybody have a library for such melody?

why would you need a library? ... arduino has tone generation capability

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 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, and released into the public domain under the unlicense so anyone can use it however they like

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


text:
Access serial monitor on linux cli? Using arduino-cli?
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??

I'm trying to upload a program for serial communication with 9600 Br with 1sec delay.
but this error is avrdude: stk500_recv(): programmer is not responding what should I do?

@user137442, Welcome! Placing a question in the comments section under an existing one, will probably not get your question answered. Please consider asking a separate question once you've made sure your question has not been answered elsewhere on Arduino Stack Exchange.

Programs such as screen, minicom or (my favorite)
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:
stty -F /dev/ttyACM0 raw 115200
cat /dev/ttyACM0

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 ("Options") 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.

thx! Forgot about that, I knew it and also screen. Obviously did a bad job at web search on the topic :P

And how do you send "Hi Arduino" to the Arduino board?

@user171780 With minicom? Just type it when connected. With screen? Just type it when connected. From the command line? echo "Hi Arduino" > /dev/ttyACM0

If I type and hit enter, nothing happens. I only see whatever Arduino sent (after reset) but he is not listening to me (so no answer either).

@user171780 Unless you have programmed your Arduino to echo back what it receives you won't see anything. Without knowing what your code is I cannot help you.

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


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

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.

Yes, just map 2.5-5 to 0-255 and analoWrite that value

int x=analogRead(A0);if (x >=512) red=(x-512)/2; etc.

Thanks to all who have responded. I have tried Sim Son's approach and as unsuccessful. I will have to test the other techniques.I'll report back on progress.

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

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

The code might look like (note: untested):
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.

If you subtract 20 from y before mapping, won't that cause some negative values of y? (The range would be -20 to 492 instead of 0-512.) What does map do with out-of-range values?

I'd suggest changing  y -= 20; to if y <= 20 y = 0; instead.

Good question. You should do it at 0.


text:
Compiling Error - exit status 1 for DHT11 using Arduino UNO (code/process/connections same as website given bellow)
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:
#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");
}

what is your question?

The compiler couldn't find the file Adafruit_Sensor.h. Have you installed the Adafruit sensor library correctly?

@chrisl i didnt add the adafruit library, now it's working. Thanks!!

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


text:
WS2812B NeoPixels no longer working after cutting the strip and adding an extension
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.

I thought WS2812B LEDs took 5V, and not 12. If I'm right, you may have fried something. Also, check to see if you reconnected them the right way around; there are usually arrows/labels on the strip for guidance. You could try if you can get one strip of three LEDs to work with the right voltage, and take it from there.

WS2812Bs work at 5V. You may have fried them at 12V. Also, take care to connect the Dout of the first strip to the Din of the second, and so on.

Mate, I think you may fried the led strip, as the strip work on 5V (even with 3.3V iirc)... Anyways, just try to cut the first led and hook up your uC (arduino or any other) to the (back in time) 2nd led (now your first led of the strip)

Are these actually WS2812B or one of the other WS281x series parts?  A link to the exact thing you bought may help.


text:
Achieving nanosecond accuracy with MKR Vidor 4000
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...

do you know what frequency is involved in 1 ns time interval?

I think so..., but we are talking for FPGA here...I think they have different rationale than CPUs, don't they?

what are you trying to build?  ... do you know what an FPGA actually is?

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) 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.


text:
Can I control LED brightness with potentiometer without any code, as well as reading the potentiometer value?
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 :) ).

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!

the resistor and the LED are in parallel with the pot .. just having a resistor in paralel causes non-linearity ... furthermore, the LED is not linear, so its "resistance" varies with the amount of current flowing through it

if you want linear response in the reading, then use two ganged pots

why are you doing this anyway?

You could try driving the LED through a MOSFET. If you get the parameters right, so that the MOSFET stays in it's linear realm, that should work I think. The gate of the MOSFET draws nearly no current, thus the measurement through A0 should not be disturbed by it.

@jsotola Thanks for explaining this. I have ordered a few dual gang pots to try this out.

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!

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:

simulate this circuit – Schematic created using CircuitLab
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.

So you're using an op-amp to create a "stiff" variable voltage from the voltage divider so the load of the LED doesn't affect the ADC reading? I wish my analog electronics chops were stronger.

It's worth noting that you want to be sure to use a linear pot. A log pot would give very squirrelly results.

Basically, yes. The potentiometer is just a reference for the opamp to create it's own output with lower impedance.

And then the current limiting resistor lets more or less current though based on the input voltage, thus varying the brightness of the LED. I like it.

The resistor basically converts the voltage into a predictable current through ohms law.

Yeah, that part I get.

@Majenko Thanks for this explanation, I will read up on op-amps as I have not come across them before. Does this mean jsotola's suggestion of using dual gang pots not work? I am not all that familiar with analogue electronics, so forgive me if I have misunderstood something.

A dual gang pot will work fine, but if you don't want to use one (or can't get hold of one of the right type) then a buffer is the way to go.

@Majenko Thanks, I have ordered a few of them so I will report back here once I get it working.

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/

Actually, to be pedantic, there are three types of pot: linear, logarithmic, and inverse logarithmic. Audio pots are actually inverse logarithmic. Exponential, if you like.

@Majenko Thanks for the comment, however, I everywhere read that audio pots/tapers are A type.

Yes, a for audio. Log tapers are rare. Inverse log audio are more common.

@Majenko, thanks for the clarification. I never heard of C types before, I used A for a guitar pedal (never finished, but learned a lot).

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.


text:
if(val == 0) being ignored when it contains another nested if() statement
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

if(timeisup == true) is equivalent to if(true == true) which is redundant ... if(timeisup) is the same

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?!").

exactly Serial.print(F("CTA26: "));    complexManoeuvre = 2; recerse(dur);

But, if I'm not mistaken, it needs to do that in order for the process to return to stuck() to continue through the switch(progress).

It's not exactly "can set", it will set it to 2

Change the if() statements to the second version and everything works as it should. But... that's what I don't understand.

@lsbyte Maybe it needs to do that, but after the struck call ends, it'll continue processing commands after that call. That means it goes out of the first nested if block {} and guess what, another nested if is right after that first one.

But shouldn't the progress only increment once each time the process visits stuck()? I don't understand how changing the if() statements in loop could effect the behaviour of the switch(progress)

@lsbyte You are doing pretty much this int a = 0; if (a == 0) { a = 2; }  if (a != 0) { Serial.println("but why?"); } and you are asking why is the a not zero, after you changed it to 2. The stuck has "side effects" and one of them is changing complexManeuvre.

Let us continue this discussion in chat.


text:
DFplayer, Play sound when pin is high
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

Does this answer your question? DFplayer, Play sound based on pressed button

same as your last question ... you have code that does something when you press a button ... you have no code that executes when you release a button ... you also have no code that does anything when the track ends, except for printing a message ... check the messages in the serial monitor

@jsotola, on this line   if(!digitalRead(sw4)), I have to tell the code if the button is held down so do the function. if released don't do. i tried else and break but it doesn't work. don't know what to use to tell the software .

Currently you are checking, if the button is currently pressed. Thus the code inside the if statement will execute as long, as the button is pressed. You want to check for the transition. Have a look at the Bounce2 library, which makes it way easier to check buttons. Then you have if(button.fell()) to check, if the button pin fell (for the press transition), or if(button.rose()) to check, if the button pin rose (for the release transition).

@chrisl, Thanks, the Bounce2 Library was useful and help a lot.

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


text:
Can someone check my schematic and code? My Led is not turning on
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

#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
}
}

I reposted it because the other code was only screenshots and not formatted

There both my accounts I made two accounts by accident.

edit the first post ... delete this one

I guess you want your interrupt to fire on any change, not only when going low, or it'll never turn on.
Change your EICRA line to 0b00000001.
I also found it very useful to include some macros for setting and clearing bits, so you don't have to write out all the bytes and |= / &=s manually

I second @towe 's comment. Secondly; since the button has a pull-up resistor, the PD2 bit of the PIND register will be 0 when the button is pressed, and 1 when not pressed. Your code assumes the reverse. Thirdly; you may have to look into debouncing the button. Lastly; indenting your code makes it more readable, for us and yourself.


text:
How to scan Lora E32-TTL-100 devices by using only one ESP 8266 + Lora E32-TTL-100s?
I'm investigating for some function of Lora E32-TTL-100.
Currently, I can communicate between two E32 like the following image:

But 3 days ago, I saw a person used only one MCU to scan the other E32 is power-on or power-off:

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:

Thank.

please post a link to what you saw 3 days ago

@jsotola, I saw my teacher done it like the above images. We will know that the 2nd is power-off, the 2nd, 3rd E32 is power-on. I'm not sure about how to implement it. I also ask my teacher, but he said that I should find the solutions for it. but no hope.


text:
How to use Multipile millis()
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

    }
  }
}

what problem are you struggling with? ... what is your question?

@jsotola 1st checking and 3nd checking only working

In your serial monitor, what is printed? hellohh / hellohh2 / hellohh 3? Can you edit your question and copy/paste some of the output so we can see what logic branches are being followed.

You said 3 minutes and 5 minutes in your question, but I don't see any reference to that in the code (3 minutes would be 3 * 60 * 1000 milliseconds = 180000).

@NickGammon  now just trying with some leds,

@NickGammon one exhaust fan when the humidly is high for 3 minutes, if the humidity still high fan will on again i need 5 minutes gap between the next fan on thats what i meant

Your first test of if (currentMillis2 - previousMillis2 > interval) { is for a longer interval than 1000/2000 so I expect weird behaviour. You haven't said what is actually happening. Saying a "checking is working" is a bit non-specific. What is being printed? Does the LED light?

now ledblink and off @NickGammon

This isn't a forum. Please edit your question and supply extra information, like what the serial output is, and what is actually happening. Comments are not for debugging the problem.

okay @NickGammon new to things, no idea how to do things sorry

I realise that you are new, and I have suggested that you do certain things, which you haven't done as I write this. I recommend that you follow my earlier suggestions about documenting your issue better, and then we may be able to help you better.

Also the question and comments (multiple fans for 3 / 5 minutes) and your code (1 second on / 2 second off LED) don't seem to match at all.

@towe just testing but it stuck

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, 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:

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:
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;
    }
}

I dont know how to thank you , it work like charm

Thanks for understanding my goal :)

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.

Thanks , when i change the interval time to 20000
OnTime long OffTime change automatically to 20000 @towe

Yes, since you only ever check whether something should happen once per "interval time". By then, the other two durations have long since passed.
What do you need / want interval time for exactly?

Yes , i want the interval time exactly, i don't know how to check :(

my humidity sensor keep checking the temp and hum , i dont want to keep my fan working all time, so i need a interval time 5m if needed

That's not what the "interval time" does in your (or my) sketch - the fan is turned off once OnTime has passed.

Yes, i checked. How can i achieve that ? can you show me an example?

Just to clarify I understand you correctly:
You read the humidity level. If it's too high, you want the fan to run for at most three minutes. Then, it must wait for five minutes, until it checks the humidity again and decides whether or not to turn the fan back on (for three minutes)?

Yes, right.  if(humidity < 50){
fogger();}

else if (humidity > 70){
  digitalWrite(DHTpower, LOW); // exhuast fan on here

}else if ((temp > 32) && (hum < 55))

{
fogger();
}

sensor will keep  checking the humidity once the fan on for 3 minutes , must need 5 minutes gap to on again for 3 minutes

So it'll constantly check humidity, and turn on the fan if your level surpasses 70? What does the fogger() function do?

fogger is actually pump it on when the humidity is below 50

thanks towe for your time and effort , i got the  code. Thanks for your help


text:
How to connect arduino mega 2650 and motor driver shield with seperate powers source?
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?

You should check the schematics for your motor shield to see what pins are actually used. Just because a pin exists doesn't mean it is connected to anything. You may well find the 3.3V pin isn't actually used by the shield.


text:
Arduino Nano not recognized on Windows 10
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:

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).
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.
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

With Chinese clones the best one can ever say is "Maybe..." - and it sounds like you have a clone of a clone - so the best one can say there is "um... probably not...!"

You're lucky it's worked this long.  You get what you pay for. Pay for crud and you get crud.

I've had the same troubles - but it's not Windows 10 being the guilty part.
What kind of Arduino are you using? If it's a Nano (i.e. ATmega328P) then try
selecting "Nano (Old bootloader)" - this works - at least for me.
Regards Dieter


text:
DHT11 thermometer connected to a LCD and 2 servos connected to joysrick
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.

Welcome, I proposed to close it because it's probably helpful to read the duplicated question (which is more generic). In case you have further question, you need to be more specific.
Also I suggest you first try out the components one by one before trying to combine them, especially if you are a beginner.

you are thinking about this incorrectly ... there is no DHT11 connected to LCD ... there is no servos connected to joystick ... these are separate actions ... read temperature from DHT11 and read joystick value and display data on LCD and move servo   .... try to write a sketch that does each of these separately ... read temperature an send the value to serial monitor ... same with joystick ... display "hello world" on LCD ... move servo1 to 90 degrees ... move servo2 to 170 degrees ..... when that all works, then add code to use the temperature value as input to LCD code .. etc.


text:
How can i increase the range of values that a light sensor gives?
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

Can you amend your question to include a copy of your schematic? A sketch would do if necessary. It is hard to visualise a circuit which is done purely by description in words.

A schematic would really help. Have you been able to confirm the voltage output range of your setup outside of the Arduino, by measuring them with a multimeter for example?

Hi Nick and StarCat. Yes StarCat I measured the voltage with a multimeter and it was the same that the Arduino gave me after the conversion of the Arduino output to volts. For example, when I got a value of  90 (from the Arduino) and then did the conversion ((90*5)/1023) what I got was 0.44 that was the same that the multimeter show in voltage. But when I did the calibration with a quantum sensor the value of 90 corresponded to 600 to 690 μmols.

This is something that will affect my experiment since 100 μmols of PAR is an important range but from the arduino it is described as one value.

I have uploaded the schematic on my question. Thank you a lot both of you!

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.

I have tried multiple resistors. Even when I use a 10R or 2200R the output does not change. It seems that the breadboard does not respond to the resistors. But, I have not changed the opAmp yet to see what happens. It is something that I have to do. Thank you a lot!