text:
light detection system: Response different from power bank and computer system
Hello friends
I'm working on a light detection system for the higher secondary summer term project, for which I'm using a simple Arduino board, Adafruit 16-Bit ADC, an LDR with some resisters, a 5V USB power source either the computer USB 2.0 port or a mobile power bank 5V-500mA/1A/2.1A, a USB mobile charging cable (not the data cable) and a Bluetooth module to communicate with Arduino system, an android or a computer (different from Arduino power source) to record the data.
The difference in maximum and minimum response is very poor when replacing the power source from the computer USB to power bank USB. With the same environmental and experimental conditions, the response goes from 50000 to 45000 counts (the changes in response are 5000 counts) with the power bank. For the same situations, the response goes from 50000 to 5000 counts (the changes are 45000) with the computer power source which is more suitable but it's better to use a small power supply.
How can I get the better and stable response? Kindly help me to solve out this issue. Thank you.

Could you please provide a link to the ADC product page or datasheet?

You could use the on-board ADC on the Arduino. See the Analog Read Serial and Read Analog Voltage built in examples.

Thanks for your valuable comments. ADC must be at least 16 bits for my project while on arduino board it has 10 bit only.That's why I'm using ADS115 here. For datasheet: www.ti.com/lit/gpn/ADS1115.

Based on limited knowledge of the design and limited knowledge of the requirements here are 3 possible reasons.  More may exist.

The USB 2.0 definition stats such a port provide 0.5A of current.  Some devices limit the current as a precaution.  Therefor the battery may provide more current then the USB source.  The type of USB source was not specified and no voltage measurement data was provided.
How fast does the device need to react to a change in light level?  A light-dependent resistor or LDR can have a latency of as much as a second with respect to light level changes.
With regards to the 16 bit ADC.  What precautions have been made with regards to precisely controlling the ADC's voltage reference?  Any fluctuation can cause large errors.  What precautions have been made with regards to filtering out the ADC's random noise?  For example, many ADCs only have a fraction of their resolution if averaging is not used.

Source info.: 1) USB 2.0 5V 0.5A        2) MI  and Intex original power bank has 3 port for 5V 0.5A/1A/2A supply.
All 3 ports of each power bank are providing the same response. All data is being received only through the Bluetooth communication with all other things remain same. In my case the output should be at least first, so 5000 is minimum with a computer USB2.0.

In my case the output should be at least first, so the computer is 5000 minimum with USB2.0. But for similar situations, when the source is replaced with the above power bank, the output response for all the same conditions for the minimum response varies from 5000 to 45000. Again, with the computer's USB 2.0 / 3.0 port, it goes from 45,000 to 5000 for similar conditions.

Get a volt meter and measure the actual voltage across the USB power pins.  Do this under the most current demanding situations.  Likely when communicating with the Bluetooth device.  If you can not do this, start simplifying the project.  Start by removing the Bluetooth device and communicating with the Arduino over the serial port.  Keep simplifying until you stop getting unexpected results.

Hello dear st2000
Thanks for your precious time and response.
It is working perfectly with serial or Bluetooth when
connected to the computer USB 2.0 port via cable or charging cable.
But with above mentioned power bank or mobile charger, it is not showing the same response with Bluetooth and I can't go for the serial in case of power bank.
Computer USB 2.0 port voltage = 4.91 V.
Power bank USB port voltage = 5.17 V.

@AsTJ, this is not much of a voltage difference.  Also, I looked up your ADC.  Is this one the ADC you are using?  If so the ADC chip contains an internal voltage reference.  So the small voltage difference you measured between your computer and power brick should not make the difference you are seeing.  I am at a loss.  Perhaps try a different power brick or ordinary battery.

@AsTJ, which Arduino board are you using?  I see that the ADC chip needs a serial port.  I assume the Bluetooth does too.  Are you using a software defined port by any chance?  Software defined ports are fine for slower speeds and simple projects.  But if the processor is tasked with too much to do, the software defined ports usually act unexpectedly.

Dear st2000, thanks for kind response. It's the same as available on the link send by you. The system has been checked with MI and Intex 10000mAh power bank have 3 seperate ports 5V - 0.5A, 1A, 2A and one Micromax 5V-0.5A power adaptor and one MI 5V-2A power adaptor. Also checked with 3 different Dell computers and one HP laptop.
Generally I'm using arduino uno but due to this issue, the system has been checked with a duplicate arduino nano also. The software defined serial ports are used to communicate in between but no other issue has found except amplitude or response counts.


text:
ESP8266 spend 10mA, even though It is in the deep sleep mode
I am using Nodemcu ESP8266. I want to know how much my ESP board consume the battery during sleep mode.
as the Mannual said it spend about micro-ampere, but my multi meter said it spend 10 mili-ampere, I cannot believe the result.
so please see My arrangement is right and give some advice
arrangement image

red line is for vin, black line is for GND.
black pin is COM, red pin is mA.
I set multimeter on 20mA, 200mA, it said it is 10mA.
when I change multimeter to 10mA, 1mA, microAmpere, number was overflowed.
I already connected to RST - D0, so It is properly sleep & wake up automatically. and here is my running code in the board
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

void setup() {

}

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

ESP.deepSleep(60e6);

}

You seem to be measuring the consumption of the whole board, not just the ESP8266.

O really? then I should optimize board also? but is it possible?

Usually, those breakout boards use CH340 Serial-USB converter. If USB is not connected, it automatically goes in deepsleep mode, It shouldn't consume more that 50uA. It can't be the problem, however, if you are skilled enough, you can desolder it to test its the power consumption.

There are other ESP8266 dev boards that consume less power while in deep sleep. Looks like you have a NodeMCU. Try a few other dev boards (e.g. I found that the LOLIN D1 mini consumes about 100 uA or 0.1 mA while in deep sleep). I also found that over time, components on the dev boards can become damaged (e.g. the voltage regulator) due to abuse, so that's also something to watch for.

ESP.deepSleep(60e6, WAKE_RF_DEFAULT); Try this code, it should decrease it a bit.

The Board you are using contains an ESP-12F Module, along with other chips that make it easy/possible to connect to UART over USB and thus flash the chip. This USB-to-UART converter chip isn't related to the ESP-12F Module, so is unaffected when the ESP goes to sleep, so the converter continues to draw about 10mA. You can't do anything about this unless you desolder it, or use a pure ESP-12F Module.

source: Stack Exchange

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

sort: votes


text:
Having issues with sending output to WiFi Shield
I am doing simple proof of concept trying to send C++ program output to Adafruit CC3000 WiFi Shield (using Visual Studio 2013 Desktop Edition on Windows 8.1).
In my design laptop is connected to UNO via USB, UNO is connected to WiFi Shield, and WiFi Shield is connected to D-Link router running Adafruit example sketch ("EchoServer"). These connections are working fine.
Next, I am using TCP client sample code from Microsoft for WiFi connectivity with client code running on the laptop to connect to WiFi Shield. Tested this code with sample TCP server code from Microsoft, and client was able to communicate with server code but for some reason this client is not able to find WiFi Shield TCP Server. I get "Unable to connect to server" error with CC3000 continue to show it is listening for connections but never finds one
I am sure it is due to my lack of understanding TCP/networking world. Below is the client code I am running on laptop using Visual Studio:
#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include<iostream>

// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

#define DEFAULT_BUFLEN 512          //Default buffer length of port
#define DEFAULT_PORT "7"        //Change this to change port

int main()//int argc, char **argv
{
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
        *ptr = NULL,
        hints;
    char *sendbuf = "100";
    char recvbuf[DEFAULT_BUFLEN];
    int iResult;
    int recvbuflen = DEFAULT_BUFLEN;
    /*
    // Validate the parameters - not necessary for use
    if (argc != 2) {
        printf("usage: %s server-name\n", argv[0]);
        system("pause"); return 1;
    }
    */

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        system("pause"); return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if (iResult != 0) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        system("pause"); return 1;
    }

    // Attempt to connect to an address until one succeeds
    for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {

        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
            ptr->ai_protocol);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            system("pause"); return 1;
        }

        // Connect to server.
        iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR)
        {
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);

    if (ConnectSocket == INVALID_SOCKET) //If failed to get a socket, end program
    {
        printf("Unable to connect to server!\n");
        WSACleanup();
        system("pause"); return 1;
    }

    // Send an initial buffer
    iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
    if (iResult == SOCKET_ERROR) {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        system("pause"); return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);

    // Receive until the peer closes the connection
    do {

        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0)
        {
            printf("Bytes received: %d\n", iResult);
            std::cout << recvbuf << std::endl;
        }
        else if (iResult == 0)
            printf("Connection closed\n");
        else
            printf("recv failed with error: %d\n", WSAGetLastError());

    } while (iResult > 0);
    // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        system("pause"); return 1;
    }
    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
    return 0;
}

At no point in your program are you telling it where to connect to.  You are requesting service "7", which of course is resolved to port number 7, but you aren't giving it an IP address or host name to connect to.  Ergo, it is trying to connect to port 7 of the same computer that the program is running on - which will fail.
You need to specify the IP address of the WiFi shield as the first parameter to getaddrinfo() (currently NULL):

int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res);
node specifies either a numerical network address (for IPv4, numbers-and-dots notation as supported by inet_aton(3); for IPv6, hexadecimal  string format  as  supported  by  inet_pton(3)),  or  a network hostname, whose network addresses are looked up and resolved.  If hints.ai_flags contains the AI_NUMERICHOST flag, then node must be a numerical network address.  The  AI_NUMERICHOST  flag suppresses any potentially lengthy network host address lookups.
If the AI_PASSIVE flag is not set in hints.ai_flags, then the returned socket addresses will be suitable for use with connect(2), sendto(2), or sendmsg(2).  If node is NULL, then the network address  will  be  set  to  the  loopback  interface address  (INADDR_LOOPBACK  for  IPv4 addresses, IN6ADDR_LOOPBACK_INIT for IPv6 address); this is used by applications that intend to communicate with peers running on the same host.
-- Extract from the getaddrinfo(3) manual page

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


text:
Hardware serial not working, SoftwareSerial is
On my Uno-equivalent Arduino, a SoftwareSerial connection (on RX, TX = 8, 9) is working*, while a hardware serial connection to the same device, set up in the same way (but on pins RX, TX = 0, 1) is not working. Why is the hardware serial setup not working?
*By working I mean receiving a byte from the external device
Edit: as a simple example:
void setup() {
  Serial.begin(38000);
  pinMode(7, OUTPUT);
}

void draw() {
  if (Serial.available() > 0) {
    Serial.read();
    tone(7, 440, 1000);
  }
}

The above, using Serial, doesn't work, whereas
#include <SoftwareSerial.h>

SoftwareSerial serial(8, 9);

void setup() {
  serial.begin(38000);
  pinMode(7, OUTPUT);
}

void draw() {
  if (serial.available() > 0) {
    serial.read();
    tone(7, 440, 1000);
  }
}

does work.

I don't know if this helps, but connecting RX/TX through an LED to ground gave me the following, using Serial on (0, 1) and SoftwareSerial on (8, 9):
Serial
RX: bright
TX: bright
SoftwareSerial
RX: dim (but still lit)
TX: bright
Is the fact that RX is dim using SoftwareSerial significant?

Please post your code. Please define "not working". What device have you connected?

@NickGammon This is interfacing with a CASIO fx-9750GII. I can receive the request byte from the calculator using SoftwareSerial but not with Serial. If the Arduino receives any data it makes a sound.

What if you try SoftwareSerial serial(0,1);?

38000 bps is not a standard rate and hardware at one end or the other might not support it, while software might not care.  You still haven't said what "doesn't work" means, but if it means garbled characters, use a standard rate, eg 38400 bps.

@jwpat7 'Doesn't work' means no byte is received. The external device supports 38000 bps only, and the Arduino can use it on the hardware serial port (as tested connected to a computer with a Processing sketch). The fact that it is simultaneously connected to a computer through the USB port doesn't seem to be an issue, because it exhibits the same behaviour powered by a phone charger (unless the charger also interferes with something?).

@frarugi87 I don't think SoftwareSerial serial(0, 1); worked either.

What do you mean by "think"? Did you test it?

@frarugi87 Tested again now; no success.

Just a stupid question, but did you try to swap RX and TX? Anyway if SoftwareSerial on pins 0,1 doesn't work it's an hardware problem...

@frarugi87 Yes, I tried swapping – about ten times. Maybe my ESP8266 will work with Serial; I'll give it a try. Do you know if it supports SoftwareSerial?

I think so.. Or at least it can; if the libraries rely on interrupts you'll have to re-write them..

Serial works on the ESP8266; SoftwareSerial fails to compile (I think it is available as an external library though). I was testing this for an ESP8266 project so it will work. I'd say it is a harware issue on the uC.

I would check if the arduino you are using supports your selected baudrate.
38000 is not a standard rate and it could be, that the hardware is not able to work at it with the needed precision.
The software serial (and most USB serial dongles) could use any baudrate, but not the limited hardware within most arduinos.

There may be several reasons

Be sure uC pin connect pin header
In setup part, you write Serial.begin(xxxx);
After serial begin, don't change this pins IO features(Input, output)

Please check that after if not solve, please share code

Can you explain what you mean in 1?

Also explain what you mean by (3).

I think that means don't use pinMode on pins 0 or 1.

I think a translation might be: 1. Make sure you connect to the right pins. 2. Be sure to use Serial.begin(baud). 3. Never use pinMode() on pins 0 and 1 when you are using Serial.

In that case: check, check and check... I think.

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

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


text:
Arduino Due interrupt is taken but not executed completely
I tried to build a simple l-meter with my arduino due. I programmed a simple frequency meter with one timer and one counter. The timer takes an interrupt each 10s, 100ms, 10ms and 1ms. But ones the interrupt is taken it is stopped and even a short Serial.println("Hello World"); does not appear in the serial monitor of the arduino IDE. I don't know what I forgot.
Here is my code:
#define voltage 26

volatile uint32_t current_range = 10000;               //starts with highest range and decrements. longer measurements produce more precise results. measurements for small l values require 11.111ms
volatile const double c_1 = 2533029590000000.0;        //constant value for l value calculation
volatile double correction_value = 0;
volatile boolean calib = true;
volatile uint32_t counter_value = 0;

void initCounter(){
    pmc_enable_periph_clk(ID_TC0);              //enable peripheral clock for TC0

    REG_TC0_CMR0 = TC_CMR_TCCLKS_XC0;           //External clock 0 connected to PB26 (Digital Pin 22)
    REG_TC0_CCR0 = TC_CCR_CLKEN;                //Enable clock
}

void initTimer(){
    pmc_enable_periph_clk(ID_TC1);              //enable peripheral clock for TC1

    REG_TC0_CMR1 = TC_CMR_TCCLKS_TIMER_CLOCK1;  //42MHz clock
    REG_TC0_IER1 = TC_IER_CPCS;                 //Enable compare RC interrupt
    REG_TC0_IDR1 = ~TC_IDR_CPCS;                //Enable compare RC interrupt (disbale interrupt = 0)
    REG_TC0_CCR1 = TC_CCR_CLKEN;                //Enable clock

    NVIC_EnableIRQ(TC1_IRQn);                   //Enable interrupt in nested vectored interrupt controller NVIC (IRQN number = TC number * channels + channel number)
}

double calc_l(uint32_t CV){
    double freq = (double)CV / ((double)current_range / 1000.0);
    freq = freq * freq;

    return c_1 / freq;
}

void calibrate(){
    Serial.println("---Calibrating... shorten inputs then press enter---");
    while(!(Serial.available() == '\n'));
    Serial.print("Start calibration\n");
    initCounter();                              //initialize counter
    initTimer();                                //initialize timer

    REG_TC0_RC1  = 0x1908B100;                  //RC = 420.000.000 to run 10.000ms

    REG_TC0_BCR = TC_BCR_SYNC;                  //reset and start timer and counter simultaneously
}

void measure(){
    calib = false;

    //Serial.println("---Measure... connect inductivity then press any key---");
    //while(!(Serial.available() > 0));
    initCounter();                              //initialize counter
    initTimer();                                //initialize timer
    REG_TC0_RC1  = 0x1908B100;                  //RC = 420.000.000 to run 10.000ms

    REG_TC0_BCR = TC_BCR_SYNC;                  //reset and start timer and counter simultaneously
}

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

    pmc_set_writeprotect(false);                //disable writeprotect for pmc
    pinMode(13, OUTPUT);
    pinMode(voltage, OUTPUT);                   //set digital pin 26 as output
    digitalWrite(voltage, HIGH);                //set digital pin 26 HIGH
    delay(1000);                                //wait 1 second to get circuit working

    calibrate();
}

void loop() {
    analogWrite(13, 25);
    delay(100);
    Serial.print(REG_TC0_SR1);
    Serial.print(";");
    Serial.print(REG_TC0_CMR1);
    Serial.print(";");
    Serial.print(REG_TC0_IER1);
    Serial.print(";");
    Serial.print(REG_TC0_IDR1);
    Serial.print(";");
    Serial.print(REG_TC0_CCR1);
    Serial.print("\n");
}

void TC1_Handler(){

    uint32_t SR = REG_TC0_SR0;                    //save status register
    uint32_t CV = REG_TC0_CV0;                    //save counter value

    if((SR & TC_SR_CLKSTA) == TC_SR_CLKSTA){      //check whether counter clock is enabled
        if((SR & TC_SR_COVFS) == TC_SR_COVFS){      //check whether counter overflow accured
            switch(current_range){                    //check current range. decrement until smallest range is reached. then print error
                case 10000: REG_TC0_RC1  = 0x280DE80;                   //RC = 42.000.000 to run 1.000ms
                            current_range = 1000;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 1000:  REG_TC0_RC1  = 0x401640;                    //RC = 4.200.000 to run 100ms
                            current_range = 100;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 100:   REG_TC0_RC1  = 0x668A0;                     //RC = 420.000 to run 10ms
                            current_range = 10;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 10:    REG_TC0_RC1  = 0xA410;                      //RC = 42.000 to run 1ms
                            current_range = 1;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 1:     //Serial.println("Error: l value out of range!");
                            REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                            REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                            break;
            }
        } else {
            if(calib){
                if(CV < 10){
                    //Serial.println("Error: wrong calibration value!");
                    REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                    REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                } else {
                    //correction_value = calc_l(CV);
                    measure();
                }
            } else {
                if(CV < 10){                           //check if counter value is below 10. then l value is to high to get accurate results
                    //Serial.println("Error: l value out of range!");
                    REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                    REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                } else {                               //l value in nH;
                    counter_value = CV;
                    //Serial.print(calc_l(CV) - correction_value);
                    //Serial.print(" nH; ");
                    //Serial.print(CV);
                    //Serial.print(" ticks in ");
                    //Serial.print(current_range);
                    //Serial.println("ms.");
                    REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                    REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                }
            }
        }
    } else {
        REG_TC0_CCR0 = TC_CCR_CLKEN;
        REG_TC0_BCR  = TC_BCR_SYNC;
    }
}

It would be very nice if someone could help me with this.

Calling Serial from an ISR is not a very good idea. Have you tested removing that?

Yes but after removing these lines the µc still hangs in the ISR. The only thing that changes is that I don't know how far the TC1_Handler is executed.

But the ISR may call measure() and that waits for data on Serial, "while(!(Serial.available() > 0));". You need to rethink the control flow between the ISR and the measurement.

I removed these lines too for testing so that it does not wait for any serial data. I only printed the value of the counter via Serial.println(REG_TC0_CV0) but after some time this output stops and nothing is done. Without any serial communication the measure() function only initializes the timer and the counter and restarts them.

Now check the behavior by reading the timer registers in loop().

REG_TC0_CMR1, REG_TC0_IER1, REG_TC0_IDR1 & REG_TC0_CCR1 are all 0. Is it possible that i have to enable the IER each time the interrupt is taken?

Please update the code above. I think we are out of sync with your changes and tests.

Code is now updated. I read that all variables that are manipulated in an ISR have to be volatile so I changed them too.

Do you need to the the floating point inside the ISR?  Or would it be sufficient to put it outside in the 100ms loop()  Same with the range-setting, calibration, and enabling-- Can they be moved into setup? Maybe set up a one-shot measurement (or report) before the 100ms delay in the reporting loop(), and conditionally report the results afterwards?

I don't know if I understand what you mean. Which floiting point and how should I move range settings to the loop() function?

I meant the calc_1() call.  Does it need to be within the ISR?  And do you need to update current_range more often than 100ms?  If an overflow occurs, set a flag for recalculating the range stuff out in the loop.

I need this current_range to specify how much time it take to get in the next interrupt. In the end in 10 ms so updating it iun the isr is needed but the calc_l function is not  required. I removed this but it does not work either.

Maybe I'm dense, but I don't understand why most of the config code is in the ISR.  If the system is getting bound up there, I'd move much of it out and try to simplify it as much as possible, maybe saving only the counter value and the fact that the timer triggered on interrupt, and saving the overflow value if it overflowed.  Then, outside the ISR, on the reporting timescale, I'd check that there was valid data and report or reconfigure as needed.
int validReading = 0;
uint32_t measuredCount;
int overflowed =0;

void TC1_Handler(){
    measuredCount = REG_TC0_CV0;
    if((SR & TC_SR_COVFS) == TC_SR_COVFS){  //counter overflow occurred
       validMeasurement=0;
       overflow=1;
    else {
       validMeasurement = 1;
       // either reset counter and clock or stop handling interrupts
    }
 }

 loop(){
   ...
   if (validReading) { // report
      ...
   } else {
   if (overflowed ) { // shorten sampling time, calibrate, and initialize
      ...
   }
   if ( measuredCount < 10 ) { // lengthen sampling time?
      ...
   }
   // calibrate and reinitialize
 }

Looks like it could work. Did not thought about putting data handling in the loop function. I will try this version tomorrow. Thanks for your help.

authors: Йорданка Запрянова


text:
Arduino Program uses less RAM then expected and doesn't run
I am trying to make a program for my Arduino that will run 4 motors with random actions (forward,backward,left,right) and execution is determined by a random number generator. When I compile there is no errors, and The COM port is connected correctly to my Arduino Mega, but when it uploads the log says this:
Sketch uses 668 bytes (0%) of program storage space. Maximum is 253,952 bytes.

Global variables use 9 bytes (0%) of dynamic memory, leaving 8,183 bytes for local variables. Maximum is 8,192 bytes.

That means only 677 B is being used, but the Arduino file is 6 KB. I know that the program gets somewhat smaller when it is compiled, but not ten times smaller.
What's happening here?
EDIT
// Arduino pins for the shift register
#define MOTORLATCH 12
#define MOTORCLK 4
#define MOTORENABLE 7
#define MOTORDATA 8

// 8 bit bus

#define MOTOR1_A 2
#define MOTOR1_B 3
#define MOTOR2_A 1
#define MOTOR2_B 4
#define MOTOR3_A 5
#define MOTOR3_B 7
#define MOTOR4_A 0
#define MOTOR4_B 6

// Motor pins:

#define MOTOR1_PWM 11
#define MOTOR2_PWM 3
#define MOTOR3_PWM 6
#define MOTOR4_PWM 5

// LED Pins

#define led_r 22
#define led_l 23

// Actions

#define RIGHT 0
#define LEFT 1
#define FORWARD 2
#define STOP 3

// Codes for the motor function.
#define GO 1
#define REVERSE 2
#define BRAKE 3
#define RELEASE 4

// Probability

#define rProb 5
#define lProb 5
#define fProb 88
#define stopProb 2

// other globals

#define defSpd 255

void setup() {}

void execute(int action) {

 if (action == FORWARD) {

  motor(1,FORWARD,defSpd);
  motor(2,FORWARD,defSpd);
  motor(3,FORWARD,defSpd);
  motor(4,FORWARD,defSpd);

  digitalWrite(led_r, LOW);
  digitalWrite(led_l, LOW);
 } else if (action == RIGHT) {

  motor(1,REVERSE,defSpd);
  motor(2,REVERSE,defSpd);
  motor(3,FORWARD,defSpd);
  motor(4,FORWARD,defSpd);

  digitalWrite(led_l, LOW);
  digitalWrite(led_r, HIGH);
  delay(150);

 } else if (action == LEFT) {

  motor(1,FORWARD,defSpd);
  motor(2,FORWARD,defSpd);
  motor(3,REVERSE,defSpd);
  motor(4,REVERSE,defSpd);

  digitalWrite(led_l, HIGH);
  digitalWrite(led_r, LOW);

  delay(150);

 } else if (action == STOP) {

  motor(1,BRAKE,defSpd);
  motor(2,BRAKE,defSpd);
  motor(3,BRAKE,defSpd);
  motor(4,BRAKE,defSpd);

  digitalWrite(led_r, HIGH);
  digitalWrite(led_l, HIGH);

  delay(1000);

 }

}

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

  // Random action
  int i = (1, 101);

  if (i > 0 && i <= rProb) {

    execute(RIGHT);

  } else if (i > rProb && i <= rProb + lProb) {

    execute(LEFT);

  } else if (i > rProb + lProb && i <= rProb + lProb + fProb) {

    execute(FORWARD);

  } else if (i > rProb + lProb + fProb && i <= rProb + lProb + fProb + stopProb) {

    execute(STOP);

  }

}

void motor(int nMotor, int command, int speed)
{
  int motorA, motorB;

  if (nMotor >= 1 && nMotor <= 4)
  {
    switch (nMotor)
    {
    case 1:
      motorA   = MOTOR1_A;
      motorB   = MOTOR1_B;
      break;
    case 2:
      motorA   = MOTOR2_A;
      motorB   = MOTOR2_B;
      break;
    case 3:
      motorA   = MOTOR3_A;
      motorB   = MOTOR3_B;
      break;
    case 4:
      motorA   = MOTOR4_A;
      motorB   = MOTOR4_B;
      break;
    default:
      break;
    }

    switch (command)
    {
    case GO:
      motor_output (motorA, HIGH, speed);
      motor_output (motorB, LOW, -1);     // -1: no PWM set
      break;
    case REVERSE:
      motor_output (motorA, LOW, speed);
      motor_output (motorB, HIGH, -1);    // -1: no PWM set
      break;
    case BRAKE:
      // The AdaFruit library didn't implement a brake.
      // The L293D motor driver ic doesn't have a good
      // brake anyway.
      // It uses transistors inside, and not mosfets.
      // Some use a software break, by using a short
      // reverse voltage.
      // This brake will try to brake, by enabling
      // the output and by pulling both outputs to ground.
      // But it isn't a good break.
      motor_output (motorA, LOW, 255); // 255: fully on.
      motor_output (motorB, LOW, -1);  // -1: no PWM set
      break;
    case RELEASE:
      motor_output (motorA, LOW, 0);  // 0: output floating.
      motor_output (motorB, LOW, -1); // -1: no PWM set
      break;
    default:
      break;
    }
  }
}

void motor_output (int output, int high_low, int speed)
{
  int motorPWM;

  switch (output)
  {
  case MOTOR1_A:
  case MOTOR1_B:
    motorPWM = MOTOR1_PWM;
    break;
  case MOTOR2_A:
  case MOTOR2_B:
    motorPWM = MOTOR2_PWM;
    break;
  case MOTOR3_A:
  case MOTOR3_B:
    motorPWM = MOTOR3_PWM;
    break;
  case MOTOR4_A:
  case MOTOR4_B:
    motorPWM = MOTOR4_PWM;
    break;
  default:
    // Use speed as error flag, -3333 = invalid output.
    speed = -3333;
    break;
  }

  if (speed != -3333)
  {
    // Set the direction with the shift register
    // on the MotorShield, even if the speed = -1.
    // In that case the direction will be set, but
    // not the PWM.
    shiftWrite(output, high_low);

    // set PWM only if it is valid
    if (speed >= 0 && speed <= 255)
    {
      analogWrite(motorPWM, speed);
    }
  }
}

void shiftWrite(int output, int high_low)
{
  static int latch_copy;
  static int shift_register_initialized = false;

  // Do the initialization on the fly,
  // at the first time it is used.
  if (!shift_register_initialized)
  {
    // Set pins for shift register to output
    pinMode(MOTORLATCH, OUTPUT);
    pinMode(MOTORENABLE, OUTPUT);
    pinMode(MOTORDATA, OUTPUT);
    pinMode(MOTORCLK, OUTPUT);

    // Set pins for shift register to default value (low);
    digitalWrite(MOTORDATA, LOW);
    digitalWrite(MOTORLATCH, LOW);
    digitalWrite(MOTORCLK, LOW);
    // Enable the shift register, set Enable pin Low.
    digitalWrite(MOTORENABLE, LOW);

    // start with all outputs (of the shift register) low
    latch_copy = 0;

    shift_register_initialized = true;
  }

  // The defines HIGH and LOW are 1 and 0.
  // So this is valid.
  bitWrite(latch_copy, output, high_low);

  // Use the default Arduino 'shiftOut()' function to
  // shift the bits with the MOTORCLK as clock pulse.
  // The 74HC595 shiftregister wants the MSB first.
  // After that, generate a latch pulse with MOTORLATCH.
  shiftOut(MOTORDATA, MOTORCLK, MSBFIRST, latch_copy);
  delayMicroseconds(5);    // For safety, not really needed.
  digitalWrite(MOTORLATCH, HIGH);
  delayMicroseconds(5);    // For safety, not really needed.
  digitalWrite(MOTORLATCH, LOW);
}

Let me look in my crystal ball....  Ah yes, bits are being optimized out because you haven't written your software right.   Post your code, the others here aren't psychic!

@Majenko Code added.

What is:
// Random action
int i = (1, 101);

supposed to achieve?
/tmp/untitled1/untitled1.ino: In function 'void loop()':
/tmp/untitled1/untitled1.ino:110:13: warning: left operand of comma operator has no effect [-Wunused-value]

Ergo, i is always going to be 101.  So all the if constructs will be false, so they get optimized out (they are all constants).  Because of that the other functions are never getting called, so they are optimized out.
So you are left with next to nothing.
I think you may have missed the word random out from there...

Program size: 2798 bytes
Memory size: 17 bytes
Compilation took 0.227 seconds

I believe I saw in some docs that (min,max) could be used to generate random numbers. Obviously not. Thanks!

@GalenNare Only as parameters to the random() function.


text:
Arduino is freezing during Serial.Print() while passing a char array
This problem is on an Arduino Due.
I am trying to populate a char array buffer that is receiving information over a serial port. I am reading the information off of the serial port and storing it into a buffer array and passing it back to the original function call.
First is the code that initializes the buffer and writes the data that the Serial requires in order to issue a response. This function compares many types of expected responses (uint32_t expect) and returns a confirmation as an int.
//Receive a cmd to send over serial and expect a certain response
int SendCommand(char * cmd, uint32_t expect){
  int cmdSuccess = 0, j=0;
  char buffer[500];
  memset(&buffer,0,sizeof(buffer)); //0 out the buffer
  Serial3.print(F(cmd));
  delay(500);

  Response(buffer);

  if (expect == EXPECT_OK){
    for(int i=0;i<sizeof(RESP_OK);i++){
      if(buffer[i]==RESP_OK[i]){ //RESP_OK is an example of a response of length 6
        j++;
    }
  }
    if(j==sizeof(expect)-1){Serial.print(F("\nGOOD RESPONSE!\n")); return 1;}
  }
  else{return 0;}
  delete [] buffer;
}

void Response(char buffer[500])
{
  int index = 0; //message index;
  int count = 0; //used for timeouts
  while(1)
  {
  if(Serial3.available()) //Data will be coming across serial3
  {
    char data = Serial3.read();
    buffer[index]=data;
    index++;
  }
    count++;
    delay(100);
    if(count == 50){
    Serial.println(F("\nEnd of Response"));
    break;
  }

}

Edit: fixed the braces.
Right now, this code is hanging at the last part of Response right before break;. Am I having memory issues by the time it reaches the println at the end?
That last println was actually working until I began passing the buffer as a pointer and not returning it a char* and declaring void Response as char* Response. But the problem with this approach was that the buffer would reduce to sizeof(buffer) = 4 and would strip off the rest of the information when returned.
Edit: As Matt suggested down below, I declared a static const size_t bufferSize and pass it into the Response() call as well as passing in buffer as char*. Then I reset the buffer size by buffer = (char*)malloc(bufferSize).
What I still don't understand curious is the sizeof(buffer) after Response which is returning 4. However, 6 characters are stored into the array during Response. I've changed the pointer call to Response(char* buffer, const int size) with the following:
  if(index<size){
  buffer[index]=data;
  index++;
  }
  else{Serial.print(F("Buffer length exceeded!"));}

Thanks so much for your time!

What is that delete command for? 1) delete is c not c++ and should only be used to free something allocated with new and 2) that line is unreachable. Secondly you never check whether you're going past the end of your buffer (not an issue right now because of the incorrect } meaning you only ever get 1 byte) What if 501 bytes arrive before you time out?

Also when you pass a char* sizeof will always return 4 (or 8 on 64 bit systems) rather than the size of the buffer, you're asking it for the size of the pointer not the size of the buffer it's pointing to. The normal way to cope with this is to pass a pointer and also pass an integer value of the buffer size. That makes the buffer size known to the function without having to hard code it as part of the function parameters.

The 500 in the function's argument is meaningless and ignored by the compiler. If your timeout is supposed to be an inter-character timeout, then you're doing it wrong. You should clear 'count' in the IF block, if that is your intention.

I tried putting it in as @Andrew mentioned, by passing the buffer as a pointer separate to its buffer size. However, it's still only returning with a sizeof = 4, leaving off some of the chars that are being read into it.

Of course it's still returning a sizeof of 4, I said it will always do that. That's why you pass the size as a second parameter. Use that within the function and don't use sizeof.

Sorry, but there are quite a few issues with your code any of which may be contributing to your problem.

memset(&buffer,0,sizeof(buffer)); //0 out the buffer you are taking the address of a pointer and passing it to memset().  buffer is already a pointer of type char*.  Its working, because address of the pointer is the same address as buffer[0], but it is wrong and won't always work.
Serial3.print(F(cmd)); I have never used the F macro, but my understanding is it tells the compiler to store the string in flash memory.  cmd is a variable on the stack, a parameter to the function, so my guess would be the compiler is ignoring the F macro.
500 using a literal value in more than one place is opening you up to problems.  I think you should declare static const size_t BufferSize = 500;
void Response(char buffer[500]) It would be better to pass in a pointer to a char and the size as the parameter, (const char* pBuffer, const int& size) you can treat it the same within your function or you could pass a pointer to the next available item and then return the updated pointer.
1for(int i=0;i strlen(buffer))` then buffer can't contain RESP_OK (its quicker too).

Also the Response function won't compile, because you have too many closing braces (I assume its a copy and paste error).  This is the cause of you code hanging if(Serial3.available()) is inside a while(1) and there is no way of breaking out.  So if you just fix that you code will run.

About point 1: buffer is not a pointer, it's an array. The & does not make the array identifier decay to a pointer, thus &buffer is not the address of a pointer, it's the address of the array.

Yes, these are all good points. First, you are right about the copy-paste error and the hanging bracket, otherwise I'm sure the code wouldn't compile.
So it no longer freezes, and I modifies the buffer call to Response by passing it in as 'char*' (not a pointer) and 'size'. However, I'm still getting the problem when I call 'sizeof(buffer)' right after the call to response. It is reading in 6 characters into the array during 'Response', and when it resumes 'SendCommand' buffer has only a length of 4!

@EdgarBonet In c the name of an array without an index specifier is a pointer to the start of the array not the entire array. That's why sizeof(array) doesn't work within a function if the array is passed as a parameter, all that gets passed is a pointer.

@Andrew sizeof(buffer) will NEVER tell you how many bytes of data are in the buffer. Depending upon the scope it will either tell you the number of bytes allocated to buffer when it was created  (500 in this case) or it will tell you the size of a pointer. If you want to know how many bytes you've written to that buffer then you need to track the maximum index you have used to write data.

@Andrew (user 24459, not the OP) wrote: “In c the name of an array without an index specifier is a pointer to the start of the array”. This is incorrect. An array identifier represents the whole array. However, when you use the identifier in an expression, it does decay to a pointer to the first element, save for three exceptions. Taking the address of the array is one of these exceptions: there is no decay and you get the address of the array. C.f. the C FAQ about the equivalence of pointers and arrays.

I thought sizeof(buffer) was wrong but apparently it is correct.  It tells you the size of buffer in relation to the size of c single char.  However I looked this up as C++ and I don't think the same applies to C, but which language is this in?

The Arduino IDE compiles your program as C++, but whether it's C or C++ makes no difference for this array/pointer/sizeof issue.

I am having difficulties to follow your code due to indentation and additional braces which don't pair up correctly, but to me you are breaking out of the if(count == 50) statement through to the whole function as the while(1) statement was already closed.

Ok, thanks to the responses in this thread, I believe I have the solved the problem. There is a problem using sizeof(char*) when passing through arrays, so I used strlen(char*) instead. This code properly stores the messages of various sizes coming off of Serial3 and correctly compares them to the expected responses. The F() macro in Arduino is very useful in keeping the buffer free and, in general, I use it to print constants during debugging.
int SendCommand(char * cmd, bool resp_type, uint32_t expect){
delay(500);
  int cmdSuccess = 0, j=0, msgSize = 0;
  char * buffer;
  Serial3.print(F(cmd));
  Serial.print(F(cmd)); //Print to serial for debug purposes only
  delay(500);
  buffer = (char *)malloc(bufferSize);
  msgSize = Response(buffer, bufferSize);

  Serial.println("Buffer is: ");
  if (expect == EXPECT_OK){
    for(int i=0;i<msgSize;i++){
      if(buffer[i]==RESP_OK[i]){
        Serial.print(buffer[i],HEX);
        j++;
      }
    }
    Serial.print("\n");
    if(j==sizeof(expect)-1){Serial.print(F("\nGOOD RESPONSE!\n")); return 1;}
  }

  return cmdSuccess;
}

int Response(char* buffer, const int size)
{
  int index = 0; //message index;
  int count = 0; //used for timeouts
  while(1)
  {
  if(Serial3.available()) //Message will be coming across serial3
  {
    char data = Serial3.read();
      if(index<size){
        buffer[index]=data;
        index++;
      }
      else{Serial.print(F("Buffer length exceeded!"));}
  }
    count++;
    if(count == 50){
    Serial.println(F("\nEnd of Response"));
    break;
    }
  } return index;
}


text:
Is there any better choice other than using delay() for a 6-hours delay?
I am designing an incubator system and I need to drive a motor forward and reverse every 6 hours. Is there any better choice other than using delay()? A 6-hours delay seems a little unprofessional.

Use an RTC chip.

Explanation please if you don't mind

https://www.circuitbasics.com/how-to-use-a-real-time-clock-module-with-the-arduino/

A 6 hours delay seems a little unprofessional. The unprofessional attitude comes from the more important, but ignored questions: - Does it matter when/if the Arduino was restarted/reset while running? - Is it useful to have any feedback about the actual state of the cycle? - Which is the required accuracy for those 6 hours? - Is it useful/required to synchronize that period to some real world clock?

How accurate do you need the 6 hours to be, and what processor/plaftorm are you using? Many processors will have sleep modes where you can just tell it to sleep for a given time (though in many instances that will look like a reset it wakes up, so you need to save some state and check the boot reason on startup), but precision is often not very good.

Several options here, and a couple folks have pointed out some challenges.
"Best" answer -- probably to use a real-time clock (RTC) board to assist your timing, and effectively set a target time (next motor run is at 23:14...) each time the cycle restarts.  By saving this target off (to the EEPROM or an SD card for instance), you'd protect against a potential shutdown and reset of the arduino in the middle.
Secondary answer; set your loop() to include a relatively short delay() statement, then check the elapsed time since the last motor engagement.  This would allow you to have other items processing, as someone else noted in this thread.  This I've pseudocoded below.
unsigned long lastMotorRunTime;

void loop()
{
    /*
     * do whatever
     */
    if(millis()-lastMotorRunTime > 21600000)  // 6 hours have passed
    {
         runTheMotor(); // placeholder for the motor movements you need
         lastMotorRunTime = millis();
    }
   /*
    * do other stuff
    */
   delay(100); // loop about every 1/10 second, or whatever works
}

Given you don't seem to need detailed precision -- a few seconds either way wouldn't matter -- this should work reasonably.  Note it WILL fail if the Ardiuno is reset -- then it will only (in my pseudocode) rotate the motor 6 hours after the last Arduino reset.  Probably better to assume that an arduino reset means move the motor 'now', if the point is to ensure periodic motion rather than precise timing.
For precise timing, as noted, the RTC would be required.
(Updated: Changed lastMotorRunTime to unsigned long)

Should be unsigned long lastMotorRunTime to avoid issue with rollover; see https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover

The delay() seems perfectly useless here.

@EdgarBonet delay is probably useless, but it points out the idea, and can be replaced with something more useful like: https://www.arduino.cc/en/Reference/LowPowerSleep

Re “it points out the idea, and can be replaced with something more useful”: The comment do other stuff perfectly fills this role.

@MarkU Good catch on unsigned long -- edited a fix in.
Yes; Edgar Bonet and Patrick M I could have ignored putting in a delay() at all, but placed it there to show possibilities a little more clearly.

You will also want to incorporate some sort of state mechanism and/or a positional readout to ensure that the motor ran the appropriate time.
I've worked on encoders that jittered and caused 'more motion' resulting in time turned off too soon. Power failures, intermittent glitches or spikes- all can wreck movement. There are lots of ideas here and you're showing great pre-planning to solve them.

Using delay() for a 6-hour delay is a bit awkward, but perfectly doable. It will, however, not be very accurate, because the accuracy depends on the accuracy of the Arduino's clock, and it will block all other code you may wish to run.
Using timing with millis() would allow your Arduino to do other things while waiting. It will be just as inaccurate, though.
For long periods, and especially if you want things to be more accurate, you could use an external Real Time Clock, like the DS3231. You can get these as modules on break-out boards, and libraries are also available.
These RTCs have a backup battery, so they also keep running a while without external power, and will also keep time when the Arduino resets. Most also have settable alarm times you could use.
For your application, I would also implement a simple watchdog timer to make sure the Arduino is still waiting and working, and hasn't crashed. Note that a watchdog timer won't play nice with delay(); a simple 6-hour delay will always trigger it, and timing with millis() or an external RTC is the way to go here.

Some of these modules support the alarm function. Let your code set the time when compiling then forget about it. LOOP: When starting the cycle read the clock and calculate the alarm time needed for reversal and set it. When the alarm triggers reverse the motor and repeat the LOOP. If you put the battery in the module this will keep time even if the power fails.

Since this is for an incubator, I suspect that you don't need high precision.  So delay() will work perfectly well, if you don't want to do anything else in the meantime (like maybe monitor temperature, control a heater, and/or light LEDs for over/under temperature).  In that case you could use a loop that handled all those operations at some convenient rate like once per second or once per minute, using delay() in the loop. (I assume that your incubator is slow to respond to the heater, so slow sampling will be fine.)  Then let the loop run for 6 hours, which you can determine by simple count of the 1-minute (or whatever) loop delays.  And if you find that your 6-hour time is consistently high or low, adjust the count limit to compensate.

I have an automatic watering system that (among other things) trigger on time. I use the excellent Timer Library for this. It allows several useful timed interactions such as Pulse or Oscillate in addition to After which would solve your issue - or Every if you want a recurring 6 hour code block to execute
In the end - behind the screen - it is just as unprofessional as millis() - the library itself uses millis() and a scheduler. But the code looks cleaner and is easier to write and update.

There's nothing wrong with using delay here.
There is only a problem if you want to make the Arduino do something else as well. I that case you'd want to use millis, and use that to calculate how much time has passed (see blink without delay).


text:
Troubleshooting WS2812b LED strip with toggle on/off button
I have a very rudimentary setup with an arduino nano, an LED strip, a pushbutton and a resistor.
I was trying to use the pushbutton as a toggle, using this code
#include <stdio.h>
#include <stdlib.h>
#include<FastLED.h> // header file

#define NUM_LEDS 14 // number of led present in your strip
#define DATA_PIN 12 // digital pin of your arduino

CRGB leds[NUM_LEDS];

const int button = 2;            // GPIO 8 for the button
int status = false;

void setup() {
  //Serial.begin(9600);
  pinMode(button, INPUT);         // define button as an input
  pinMode(DATA_PIN, OUTPUT);           // define LED as an output
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}

void loop() {
  if (digitalRead(button)==true) { // if button is pressed
    // flip status
    //Serial.println("Changing status");
    status = !status;
    //Serial.println(status);
    toggle(status);
  }

  while (digitalRead(button) == true) {
    //Serial.println("while loop");
    delay(50);
    //Serial.println(status);
  }//

  delay(50);
} // begin again

void toggle(bool status) {
  if (status == true) {
    for (int i = 0; i < NUM_LEDS; i++) {
      leds[i] = CRGB::White;  //set the all leds to white
    }
    FastLED.show();
  } else {
    for (int i = 0; i < NUM_LEDS; i++) {
      leds[i] = CRGB::Black;  //set the all leds off
    }
    FastLED.show();
  }
}

This is my circuit

I am powering this from a battery (PNY model 12200, 2200 mAh, Output 5 V=1A) via USB into the arduino board. I am having some issues. Mainly, the lights would go on by themselvs after a while, maybe not full power but still would be on. Not sure where the problem is, any hints appreciated.
I also sometimes get the lights turned off, maybe I'm feeding current into the wrong place and a safety mechanism either on the arduino or the battery stick turns everything off to protect itself?

the switch data pin is floating ... its value is indeterminate ... connect the pulldown resistor to the data pin (the other side of the switch)

use INPUT_PULLUP mode so you don't have to mess with external resistors.

@jstola Unless I misunderstood what to do at the level of the hardware, connecting a resistor from the output of the pushbutton to D2 didn't change the behavior.

@dandavis using INPUT_PULLUP didn't change the behavior either.

while(digitalRead(button) == true);{  I doubt the semicolon there is intentional.  It may help to format your code.  Tools/Auto Format will do that for you.  If the commented out code isn't relevant to the question you might remove it.

"battery via USB", more about the battery. Also what happens if you power from the USB jack via a wall adapter, like you would use to charge a tablet or phone?

@timemage thanks for the code edits. See battery info in the post. It might actually be a battery problem, maybe power supply is not stable, when plugged to an outlet it seems to not turn spontaneously on. I need it to be battery powered for my application so I will try another battery pack

The manual for the T2200, which I think is what you're referring to, says:

Note: If the PowerPack does not automatically power on when a device
is connected press the power button. The PowerPack will turn off after
90 seconds when there are no devices connected.

This is a common feature for USB battery banks meant for charging phones and similar devices.  It probably shuts off when the current drops below some set limit, say 50mA for more than 90s.  But it could also be looking every 90s for the average current over the course of 10ms.  They just don't say.  Given their description it sounds likely that it regularly turns on for some short time to probe for a load.  All in all, not knowing the specifics of this may drive you nuts.  Part of the thing to keep in mind is that someone using this thing to charge a cellphone wouldn't necessarily notice or care if it cut in and out every few seconds.  If you want to use this to power an Arduino it's worth getting a good handle on how it behaves through some experimentation.  Some of these power banks do have a way to disable their load detection and auto-shutoff feature; I did not see anything about that for this model.
The Nano, the official one anyway, has a 500mA PTC polyfuse on the USB VBUS ("5V").  Your code says #define NUM_LEDS 14.  The WS2812b LEDs use something on the order of 50mA each at max output.  You should probably measure what you're actually drawing, with the intensity you are commanding them to be, to be sure you're a good margin below 500mA.  If you are in fact using 14 of them, and if it's possible that all can go full brightness, then you are perhaps trying to use something like 735mA, quite a bit above 500mA.  You way find that it's necessary to route 5V around your Arduino to your LED strip, ideally through its own over-current protection.
Each time you power on or reset your project there's going to be some time before the sketch sets the pin connected to WS2812 data signal to output and some defined level.  It may be a good idea to add an external pull resistor on the LED data signal, probably to GND, so that during power-up and reset the LED strip data signal is not picking up noise and trying to interpret it as color data and changing your load on your power source in the process.  Having the powerbank potentially turning your project on and off gives extra opportunities for this to happen.  If you trip the polyfuse, either by commanding the LEDs to draw too much or having the floating data pin do likewise, the voltage on the Nano side of it will drop.  When the voltage drops it may trip the AVR microcontroller's brownout detector, which in turn will reset it the AVR, again bringing about a floating data pin on your LED strip.


text:
Recognize peak in specific frequency area
I am wondering if it is possible to attach a microphone to an Arduino board and make the Arduino recognize a volume peak in a specific range of frequencies.
I want it to detect a specific peak (for example 0,1 dB) in the range of 1000 hz to 5000 hz.

An alternative to the FFT is the Goertzel algorithm. It is intended to only detect a single frequency, so may not suit your purpose of working with a range.
But it may be more practical and require less intensive processing. Although intended to only detect a single frequency, it will of course give results near a given frequency, depending on the sampling rates and detection thresholds.
I have previously used an Arduino Goertzel algorithm library, but there doesn't appear to be anything available through the Library Manager at the moment; a web search shows some hits though.
The beauty of the Goertzel algorithm is that it only needs to keep a small amount of data in memory, so may have some benefit on smaller processors over more data intensive techniques like FFT.
I would try implementing one or more Goertzel detectors across your range (eg one at 3kHz or two at 2kHz and 4kHz) to see if they are sensitive enough.

You can filter the signal and look at the power that lies within the
frequency range you are interested about. You could use an FFT for that,
but it is quite computationally expensive. If you go for the FFT, you
would probably end up sampling the mic in small bursts (a few
milliseconds sampled every few tens of milliseconds), as the Arduino
would spend most of its time processing the data.
A better option is probably to work in the time domain, rather than the
frequency domain. If you do not need to know exactly how much power lies
in each frequency bin, and are only interested in the total power within
the window of interest, then the FFT is computing too much stuff you do
not need. A less computationally expensive option would be to run the
samples through a digital band pass filter tailored to the band you
want. You can then compute the power from the output of the filter and
low-pass it:
raw_sample = sample_the_microphone_somehow();
filtered_signal = bandpass_filter(raw_sample);
instantaneous_power = filtered_signal * filtered_signal:
smoothed_power = low_pass_filter(instantaneous_power);

But you would still need a beefy Arduino if you want to be able to
acquire and process the samples at a reasonable rate: at least twice the
highest frequency that comes out of the microphone.
A still better option could be to do the filtering in the analog domain,
before the signal reaches the Arduino. If you can at least remove the
frequency components above 5 kHz, then the Arduino would only need
to sample at 10 kS/s, and run a digital high pass filter to remove
the part of the signal below 1 kHz. This should be easy enough even
for an AVR-based Arduino.
For the implementation of the filters, you may want to try this online
filter builder

You could sample the sound from the microphone and then apply a Fast Fourier Transformation (FFT).
An FFT lets you decompose a sequence of samples into components of different frequencies, usually into "buckets" that each have a small frequency band. You can then have a look at these buckets to see if there is a peak in a specific frequency range.
There are several examples and libraries for this on Arduinos, like EasyFFT and arduinoFFT.
PS. Edgar Bonet's answer is better; I may have become a bit lazy at coming up with computationally efficient ways of doing things because of my using "beefy" Arduinos exclusively.


text:
ATtiny85-DHT11-TM1637
I have tried many combinations and I can get the Attiny85 to display on the TM1637 just fine, but I cannot get ant readings from the DTH11, tried different pins, libraries. I upload code via UNO as isp and that works fine. Tried same code on UNO and it works.
This is my first question on here, I usually figure things, but also first ATtiny85 adventure.

#include <TM1637Display.h>
#include "DHT.h"
#define CLK 4
#define DIO 3
#define DHTPIN 2  //
#define DHTTYPE DHT11
int MTD (2000);
TM1637Display display = TM1637Display(CLK, DIO);
DHT dht(DHTPIN, DHTTYPE);

const uint8_t celsius[] = {
  SEG_A | SEG_B | SEG_F | SEG_G, SEG_A | SEG_D | SEG_E | SEG_F
}; // oC
const uint8_t Fahrenheit[] = {
  SEG_A | SEG_B | SEG_F | SEG_G, SEG_A | SEG_E | SEG_F | SEG_G
}; // oF
const uint8_t Humidityh[] = {
  SEG_B | SEG_C | SEG_E | SEG_F | SEG_G, SEG_C | SEG_D | SEG_E | SEG_F | SEG_B
}; // HU

void setup() {
  dht.begin();
  display.setBrightness(7);
}

void loop() {
  delay(1000);
  float Humidity = dht.readHumidity();
  float TemperatureC = dht.readTemperature();
  float TemperatureF = dht.readTemperature(true);

  display.showNumberDecEx(TemperatureF, 0b10000000, false, 2, 0);
  display.setSegments(Fahrenheit, 2, 2); delay(MTD);
  display.showNumberDecEx(Humidity, 0b10000000, false, 2, 0);
  display.setSegments(Humidityh, 2, 2); delay(MTD);
  display.showNumberDecEx(TemperatureC, 0b10000000, false, 2, 0);
  display.setSegments(celsius, 2, 2); delay(MTD-1000);
}

Found <TinyDHT.h> and all works ok, just what I wanted.


text:
My 12V DC Vending Machine motor rotates 1 extra 360 degree rotation sometimes. What could be the reasons?
have main board which has motor control circuit and has row and column to control the row and column of the vending machine.
I have made changes in motor in two ways:
A. I have attached an image for circuit diagram

In this design I have some pros and cons
PROS: 1. It stops at its home position after one rotation
2. It detects row and column of the machine
CONS: 1. Sometime it does not stop at its home position or take more than 1 rotation
B. I have attached an image of other diagram

In this design also I have some pros and cons
PROS: 1. It stops perfectly at its home position after one rotation.
CONS: 1. It does not detect ROW
Please suggest What should I follow and what should I made changes in the circuit.
Here is the video
https://drive.google.com/open?id=1N7ItjeU84JiDAOquAD6SGHkVWufDT40K
https://drive.google.com/open?id=1VX9yncrm6pcr1IBQsNvVZ1yR0UMflJKA

it rotates extra because it is programmed to do so

You've programmed 3.1 sec delays but your comments suggest you intended 2 second delays. Are you seeing ~50% extra rotation?

I have tested it with different time delays. Forgot to clear the comment.

Not 50% extra. It rotates little bit forward like 10% extra with 3.1 sec delay,

Why have you chosen 2 seconds? Won't a shorter delay give the rotation you want?

I have not chosen 2 seconds. It was just written in comments only.

I just want to rotate the motor from the home location to the home location when I give signal one time. But i do not know what time delay should I use?

Have a look on this video
https://drive.google.com/open?id=15CmMVI410zq1Vc2Wl7yseq9n4T8Q1rMm

what are the NO and NC pins used for?

find out ... use an ohmmeter to find out when the limit switch closes or opens

@sugandhasharma, what are the results of the switch testing?

jsotola when switch is not pressed then C is connected to NC and when switch is pressed, C is connected to NO.

"It rotates little bit forward like 10% extra with 3.1 sec delay,"
"I just want to rotate the motor from the home location to the home location when I give signal one time. But i do not know what time delay should I use?"

More than 2.0 and less than 3.1! If 3.1 sec gives 110% rotation, then you need
(100/110)*3.1 = 2.818sec to get 100%.
I realize that your 10% extra is an estimate and not accurate to 3 decimals, but I'd use 2.82 as a starting point and tweak it up or down until you get the amount of rotation you want.
Remember that timing a motor to get distance will inherently be inaccurate due to inconsistencies in the motor acceleration rate and rotation speeds, due to variations in its temperature and the power supply voltage, and load, but this should get you started. For long term accuracy, i.e., if you need it to always come back to a fixed position, you'll need some position feedback, which may be as simple as flag on the motor shaft interrupting a photocell. And even that will have some degree of inconsistency due to coasting speed when you shut the power off, but at least those error won't accumulate.
Update:

2.82, My motor rotates 10% less every time and change its location in every rotation

Right - 2.82 was a first approximation. If that is too small, try splitting the difference between 2.81 and 3.1. If that ends up too small, then split the difference between it and 3.1; or if it was too big, try splitting the difference between 2.1 and it. Do that a few more times until you have an acceptably close value.
Then read what I said about accumulating errors. The Arduino doesn't ever know what the motor position is so it can't correct for any overshoot or undershoot. If you need accuracy and repeatability, you'll have to add some kind of position sensing, or switch to using a stepper motor and drive the number of steps that makes one full rotation (and it would still have to be started from a known position).

What position feedback? Motor has limit switch but I could not control the limit switch. Can you help me in this?

With 2.82, My motor rotates 10% less every time and change its location in every rotation

@sugandhasharma Probably, controlling the motor the way you try only works more or less properly for multiple rotations. Due to the number of coils/magnets the motor has stable positions at specific angles. Stopping at positions between those angles might not work

@Sim Son If you know about it please let me know. I have attached the circuit block diagram and video too.
https://drive.google.com/open?id=15CmMVI410zq1Vc2Wl7yseq9n4T8Q1rMm

I feel you might be building a solution that will only work for a short period of time. The time you calculate will work for the environmental conditions you have right now. As temperature and humidity and age of the motor change, friction will change, this will likely have an impact on the amount of time that the motor needs to be active to get.to a desired position.  You should seriously consider an approach that says "I'm here" when the motor reaches the desired position. This is mentioned @jrobert answer as "position feedback" you should investigate(search) it.

In this motor, there is attached a micro limit switch but it is not working,
Common of switch is connected to Ground through MOSFET module
NO is connected to ground through MOSFET module.
It does run the motor but does not stop on its home location.

If that is the case, then you need to fix it. Either fix the switch on the motor (probably not easy) or build a separate one that works alongside of the motor.

Another problem that I forgot to mention in my comment above (but is mentioned in the answer) is accumulation of error. Let's say you can stop the motor perfectly within 0.1mm of where it is supposed to be using time alone. That's pretty good, but after just 10 cycles it will be 1 cm out of place. After 100 cycles it will be a full 1cm out of place and so on. As jrobert mentioned position feedback can avoid this problem.

Does anybody know the reason? It is really very important for me.

If the switch circuit is not stopping the motor, check the switch circuit itself. Does it actually interrupt the power? If it stops the motor, but lets it coast beyond home, you may need to use a slower motor speed to reduce the coasting.


text:
RFduino device required for RFduino hex file
So I have been working trying to measure the velocity of a string attaches using Rfduino microcontroller.
I have downloaded all the library(based on https://www.youtube.com/watch?v=K0JiPQnrkHQ) and check the PCB all the connection via multimeter ( i have made the PCB, and assemble via Chineses manufacture). and connect PCB to my laptop via FTDI board as this;

When I compile the code it. It's compiled nicely. But when I try to download the code it says
RFduino device required for RFduino hex file

Does anyone had any experience with this sort of error message?
(this is my first question in this forum. I don't no this belong to hardware or software side)
EDIT:
I'm trying to program RFD22302 micro using RFD22121 USB shield and USB MicroB Plug Breakout board.
RFD22302
USB Development Kit-RFD22121
USB MicroB Plug Breakout
any help would be appreciated!
Thanks, Heaps!

https://crownstone.rocks/2014/03/05/rfduino-without-rfduino-code

Hi Juraj, unfortunately, the link page video doent work and im trying program RFD22302 micro!


text:
Motor with sinusoidal motion
I need to run a  motor to have a harmonic motion with specified amplitude and frequency ( harmonic motion mean that the angular position of the motor is a sine function of the time). I’m Looking to do a specified number of sinusoidal oscillations.
I don't know how to tell the motor that I want the speed to be a sine function of the time. Any ideas?
Also, I’m still beginning of the project?  Hence I’m pretty flexible to choose any motors (DC/servo/stepper/ brushless motor) or any controller but the system has to be precise.
If you guys know what controllers that allow that kind of motion, please let me know! Thank you :)
EDIT:
so what I'm trying to do is making rheometer which measures the rheological properties of a material. Basically, there are two measuring methods available: Rotational tests and oscillatory tests. With rotational measurements, the measuring bob turns in one direction. In an oscillatory test, the measuring bob "oscillates" around the axis.

what my focus is to with oscillatory tests with set sinusoidal oscillation.
The basic principle of an oscillatory rheometer is to induce a sinusoidal shear deformation in the sample and measure the resultant stress response; the time scale probed is determined by the frequency of oscillation, ω, of the shear deformation. In a typical experiment, the sample is placed between two plates, as shown in the below image While the top plate remains stationary, a motor rotates the bottom plate, thereby imposing a time-dependent strain γ(t)=γ ·sin(ωt) on the sample. Simultaneously, the time-dependent stress σ (t) is quantified by measuring the torque that the sample imposes on the top plate.

So to able to do above testing I need to run the motor with sinusoidal oscillation with exact angle.Hope you get it what im trying to say? does anyone know any  motor controllers that allow that kind of motion ? or any hints how do i wet my feet? cheers!!

what does precise mean?

it is unclear how you want the motor to behave .... please draw a diagram that explains what you are asking ... if possible, describe the project

Sounds like a stepper with lots of microsteps (TMC with interpolation) to me.

A servo may be the simplest option, assuming you can cope with its limited accuracy (aka “dead band”).

A motor with constant speed produces a precise sinusoidal movement if you look at it form the side :)

See https://en.m.wikipedia.org/wiki/Scotch_yoke

Your best option would be:

To have a DC motor with a reduction box so that it spins at lower speeds (Lets say 300 rpm) and have an encoder to count the steps. Either put the encoder before the reduction box (here it can be used a low resolution encoder, like 16 positions) or after the reduction (here you would like a more precise one, such as those 1024 positions).
To have a Stepper motor, which will give a good angular control as long as it doesn't misses steps (if there is too much torque it will halt its movement, and you will lose count of the angle you have already displaced).

Now, to get the motor to move in a way that its angular position is of the form theta(t) = A*sin(ωt) you would have to write some code that moves the motor to each position you want. And the difficulty of it will depend a lot on the amplitude (A) and angular speed (ω) you require.
Obs: feel free to alter/add info here


text:
Serial comms failure after long time - can't open COM port
I've been using an Arduino UNO to log data: it's queried by a LabView VI over a VISA connection. It'll happily sit there and log for days, but very occasionally one of the VISA functions will fail.
After this, I can't open the COM port again (in LabView or elsewhere) and the only way to restore communication is to unplug and replug the USB cable. The Arduino hasn't crashed because I can see the other results of the program it's running working fine, but Serial comms are a gonner.
Has anyone experienced this? Do you know if this is an Arduino problem, a Labview problem, a Windows problem? Or something else?
I'm writing a minimum working example to try and catch this happening in the most simple code possible, but since the error usually takes several days to show up I can't tell you the results yet!

Which Arduino?

Good point: it's an Uno

In the end I found a solution, more or less through trial and error.
Labview default its VISA VIs to "asynchronous" mode: I found that by switching them to "synchronous" (right click on them and select "synchronous") this problem disappeared.
I think this is caused by the computer occasionally getting ahead of the Arduino and asking for the next measurement before it's finished receiving the first one. Switching to synchronous mode forces execution to wait until the VISA exchange is complete before it continues.

Good Job. That is a tough one to fine!

The assumption I am making is "VISA connection" is a PC operating VISA.
I have seen ports shut down on windows several times yet the same port works fine while in DOS.  My suggestion is try a different computer, that should narrow down your problem to which side of the connector is failing.

Cheers Gil, I did give it a shot on another computer and the problem was still there though. In the end I found a solution, I'll add it as an answer.


text:
Convert the Serial.Println to string
I'm working with VirtualWire and I'm trying to get a string value out of the Serial.println in the loop. I've tried create a string and add the message[i] , but surprisingly message[i] becomes an int when added. Serial.println outputs the string correctly, but the string that I get from message[i] is just numbers...
#include <VirtualWire.h>
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
String sensorname;
void setup(){
  Serial.begin(9600);
  Serial.println("Device is ready");
  // Initialize the IO and ISR
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  }
void loop(){

  if (vw_get_message(message, &messageLength)){
    Serial.print("Received: ");
    for (int i = 0; i < messageLength; i++){
      Serial.write(message[i]);
      sensorname += message[i];
      }
      Serial.println();
      Serial.pintln("Name of sensor: " + sensorname);
      sensorname="";  //Reestart the string
      }
}

I'm quite new with VirtualWire so I don't know if there is command to get the message and pass it directly to string...Any help will be appreciated!
EDIT
I think I dind't express myself well. In my original question I didn't add the String sensor name
The Response I get in the Serial is the following:
Device is ready
SensorA
Name of sensor: 8310111011511111465

My aim is to instead of having as sensorname=8310111011511111465, have sensorname=SensorA

Those numbers are the numerical ASCII representation of the characters.
83 = S
101 = e
110 = n
... etc ...

(Find the whole list here: http://www.asciitable.com/)
The reason you are ending up with numbers is because of the type of variable you are receiving the data into - a byte.
A byte stores a number between 0 and 255.  When you add that byte to a String the compiler assumes you want to append a number, since it is a numerical type that you are using.
If you instead tell it to use a char type then the compiler should realise "Ah, this is the numeric representation of a character - I will add the character instead".
You can either change the whole array type:
char message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages

Or cast the variable to be the right type when you append it:
  sensorname += (char)message[i];

Or better still, don't use the String class since it is really too heavyweight and prone to memory issues for use on a little microcontroller.  Stick to C strings. They take a little more getting used to, but are so much more microcontroller friendly.

Thanks, Majeko, that did the trick! In my case I want to use this value to post it into a webserver, but what you suggestest can't be applied because I have to post as a string no? Thanks again!

A "String" is just a "C string" with dynamic allocation and lots of helper functions.  It's rare for a library author to only ever allow you to use String objects.  C strings are far more commonly supported than String objects.


text:
Passing the input from one pin to another as output without polling?
I am trying to pass the input from one pin to another pin as output. Effectively I want to create a blind passthrough. The end goal is to connect two Arduinos and a series of test points together like the diagram below. I want Arduino B to shuffle which test points are connected to which pins on Arduino A on startup.
+-----------+       +-----------+     +-------------+
|           |       |           |     |             |
| Arduino A <-------> Arduino B <-----> Test Points |
|           |       |           |     |             |
+-----------+       +-----------+     +-------------+

I figure one way to do this is to poll the input pins in the loop() and then change the output pins accordingly but I would prefer if the voltage changes just passed right through without it affecting timing.
Update:
For some clarification:

All signaling is digital
I'm looking to "route" around 10-12 test points to Arduino A ideally but 6 at a minimum

How many test points are you planning to test at once? And, for a "test" do you need to measure both an input and an output? Eg. apply 3V to pin A0 and see what happens on pin D3? Something like that? How many simultaneously?

In addition to Nick's questions, are you working with digital signals or analog? If analog, do you have any particular bandwidth requirements?

The plan is to use around 10-12 test points with up to 6-8 active at once. I would like to be able to measure input and output as well. Digital signals.

If this is all digital, what is a "test point" exactly? Why can't Arduino B just generate the test signals, and just connect the pins directly?

The project is to create a puzzle for people to practice some things on. I want the person working on the puzzle to have around a dozen test points available to them to use to communicate to Arduino A. Ideally which test points are the "right" (active) ones will change dynamically each time they turn on the boards.

You could use an analog multiplexer such as the 74HC4051 (8 channels) or the 74HC4067 (16 channels) like this:

Arduino B could alter the multiplex selector (A/B/C) pins to route the signal from the test points to a specific pin on Arduino A. If you are wanting to see the result of the signal on a different pin then a second multiplexer would be required (ie. one to send data to a pin, the second to see the result on a different pin).
I have a post about the 74HC4051 multiplexer / demultiplexer which gives more details about using it.
When I tested it I found only about a 5 ns delay in timing:

Ignacio's answer about a crossbar switch sounds like a more elaborate form of multiplexer. Personally I haven't used one of them.

A multipliexer/demultiplexer is a many-to-one/one-to-many switch. A matrix switcher is a many-to-many switch, which fits the scenario OP described. You could replicate a matrix by just having an array of multiplexers, but depending on how many inputs and outputs he is dealing with there will probably be more address lines to drive than will be practical from an Arduino. I guess you could get around that with shift registers, but then it becomes a question of whether it is easier to have a complex mesh of 74xx series chips, or to just buy a matrix IC.

Agreed, but I can't find many matrix switches in my searches. Do you have a part number that could be suitable?

http://mouser.com/Semiconductors/Communication-Networking-ICs/Analog-Digital-Crosspoint-ICs/

You did better than me. :) Anyway, most of them seem to need SMD soldering skills - and the ones with a reasonable number of points (eg. 16 x 16) are quite expensive (eg. $70 or $180). We probably need more information from the OP as to how many s/he needs to switch. I can't see a 2x2 matrix being particularly useful here.

Analog Devices has a bunch: http://www.analog.com/en/parametricsearch/10630#/p4577=No Usually you can get them on an evaluation board to help breakout the pins for prototyping, but sometimes the price of the boards can be expensive. That is one advantage to 74 series, they are cheap and breadboard friendly.

You could roll your own with a CPLD. Needs additional skills and tools though.

I need to connect ~10-12 test points to pins ideally or 6 at a minimum. All digital. Could this be better accomplished with an FPGA acting as the router and sitting between the test points and the Arduino?

No Arduino is capable of doing this. You need to be looking at a crossbar/crosspoint/matrix switch IC instead.

You can reduce latency by using interrupts to detect input changes instead of polling in loop(), if you're dead set on using an Arduino instead of adding switching hardware (as suggested in other answers).
See attachInterrupt() for details, and beware that different Arduino models differ greatly in how many pins support interrupts.
Alternately, you can speed up the polling approach by using direct port access (e.g., PORTB and PORTD registers) instead of the simpler Arduino read and write functions.  This will bypass some wrapper code and also let you manipulate multiple pins in parallel.

I think some of the hardware people have mentioned in the other answers is more what I need, but interrupts and direct port access will be very helpful for another part of the project. Thanks!

Because this is digital I would like to add a third option in addition to Ignacio's and Nick's great suggestions. Use a logic device such as an FPGA or CPLD. This will require some extra knowledge and set up to get it working, but it is well suited for the functionality you are looking for.


text:
To reduce the Attiny85 current consumption
I am using Attiny85 to control 4 LEDs parallelly with a programmable switch. But even though when the LEDs are in OFF state, current consumption is around 7-8mA.
I am using a 200mAh battery in my project and it is draining up the whole battery in 24hrs (when the LEDs are in OFF state)
Below is the schematic image of my attiny85 circuit:

Code:
//Absolute maximum current of each pin of Attiny85 is 40mA
//So each LED has been given to seperate pins

const int buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin1 = 0;      // the pin that the White LED1 is attached to
const int ledPin2 = 1;      // the pin that the Blue LED1 is attached to
const int ledPin3 = 3;      // the pin that the White LED2 is attached to
const int ledPin4 = 4;      // the pin that the Blue LED2 is attached to

// Variables will change:
int counter = 1;             // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  //Serial.begin(9600);
}

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

  if (buttonState != lastButtonState) {    // compare the buttonState to its previous state
    if (buttonState == HIGH) {             // if the state has changed, increment the counter
      counter++;                           // if the current state is HIGH then the button went from off to on:
    }
    delay(50);                    // Delay a little bit to avoid bouncing
  }

  lastButtonState = buttonState;  // save the current state as the last state for next time through the loop

  if (counter == 2) {
    digitalWrite(ledPin1, HIGH);  //turns on White LED1
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);
  }
  else if (counter == 3) {        //turns on White LED2
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, HIGH);
    digitalWrite(ledPin4, LOW);
  }
  else if (counter == 4) {        //turns on both White LEDs
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, HIGH);
    digitalWrite(ledPin4, LOW);
  }
    else if (counter == 5) {        //turns on Blue LED1
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);
  }
    else if (counter == 6) {       //turns on Blue LED2
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, HIGH);
  }
  else if (counter >= 7) {         //turns on both Blue LEDs
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, HIGH);
    counter = 0;
  }
  else if (counter == 1){         // turns off all the LEDs after one button push
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);
  }
}

For each time push button is pressed, respective LEDs get ON and there are 6 such cases. In 7th case, it goes back to case 1.
So, is there a way to reduce the current consumption?
Is there any commands where we can,

Reduce the clock frequency
Disable all the interrupts
Disable all modules etcc.....when not in use

If the current consumption goes less than 1mA that would be great.

The key word you want to search for is “sleep”.

https://electronics.stackexchange.com/questions/349496/how-to-achieve-low-power-consumption-with-attiny85 . You can have the MCU in power-down mode most of the time, and only wake it up (via an interrupt) when the button is pressed. It's probably easier to move the button pin to the INT0 pin for that. After that you should get sub 1mA currents (when all leds are also off). After that, you can disable the ADC to save a few tens of µA's.

The VCC line of your ATTiny85 is connected to something called VBOOST; I just wanted to point out that the power you save by putting your ATTiny85 to sleep will probably be peanuts compared to what you'll save by shutting down the boost regulator when it's not used.  If you're unable to do that, it may not matter so much whether you put the ATTiny85 to sleep.

Yes. I have placed a SPDT switch in between so that there wont be any drain @timemage


text:
ESP send string to Arduino
I'm trying to send a string from an ESP32 to an Arduino. I'm using a level shifter, where the Uno is now the Mega (since I couldn't get the Uno to work).

RX0 is now RX1, connected to UART2 of ESP32.
// Master sender ESP32

#include <HardwareSerial.h>

void setup() {
  // Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, 16, 17);
  delay(100);
}

void loop() {
  String shape = "1,2,3";
  Serial2.println(shape);
  delay(500);
}

//Receiver Mega

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial1.begin(9600);
  Serial.begin(19200);
  delay(100);
}

void loop() {
  if (Serial1.available()) {
    String received = "";
    received = Serial1.readString();
    Serial.println(received);
  }
}

Is there something in either sketch that should be changed?

did you connect the correct pins? ... do not use pin 0 and pin 1 for software serial

@jsotola In this setup, I'm not using software serial. The pinout is displayed with the exception of RX0 now being RX1 on the Mega.

are you missing the GND connection of the LV side of the level shifter?

@hcheung They're internally connected.

readStringUntil('\n')
//Receiver Mega

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial1.begin(9600);
  Serial.begin(19200);
  delay(100);
}

void loop() {
  if (Serial1.available()) {
    String received = "";
    received = Serial1.readStringUntil('\n');
    Serial.println(received);
  }
}

It's about how Serial.readString() works: it reads from the serial port forever in this case. It stops reading if the serial interface is given a time-out. There are two possibilities:

use readStringUntil() on the receiver
call mySerial.setTimeout(300); (from setup()) to set a 300ms (for instance, as long as it's significantly less than 1000) time out on the receiver — it defaults to one second!


text:
L239D motor driver not able to drive motors
I am making a line follower robot. The issue is trying to make the motors run.
The L239D module has 4 input pins (to control two motors), 4 output pins (to drive motors), and 6 power pins (5V, 5V, GND, GND, 9/12V, and 9/12V).
I have used one 5V pin to connect it to an Arduino's 5V supply and one of the 9/12V pins to two 9V batteries in series.
The motors are barely running and when the robot is on the ground it is not able to move. I even tried three 9V batteries in series to get the voltage up to 27V but it doesn't help.

Is your motor being drived when you hold it in the means when it is not placed on the ground

yes , when it is in hand i do see it getting rotated but not on ground

9 V batteries, assuming you mean the little PP3-size ones, can't supply the current needed for driving robot motors; they are intended for low-current applications.
Putting them in series will give you a higher voltage, not more current, and the higher voltage could damage something else in the circuit.
Assuming you connected everything correctly, including ground: you need bigger batteries. Even 6 AAs in series would be much better than using a 9V battery for getting your robot to move.

If i can connect 3 9V batteries in parallel, is that going to help! , as the current is the requirement.

Have you tried batteries in parallel

It will help a little, but they will be empty very quickly. Make sure they are at about the same voltage before connecting them in parallel.

On your next try use a different H-Bridge, one with MOSFET outputs, you can have a voltage drop across the L239D of 2.4V. Measure the voltage at the motor and at your batteries you will see what I am getting at. You might want to try connecting the motors directly to the battery first to see if it will do what you want.

I guess using 9 Volt battery in parallel will do your work because if the motor is moving as you quoted above means it is getting the voltage but not enough current to drive it, please connect the 9 volt battery in parallel and it will work for you


text:
How can I use both ultrasonic and IR sensor and ultrasonic sensor at ones with Arduino
I  want to use both the ultrasonic sensor and IR sensor with Arduino + motors for a car project. Will I have to do any kind of multithreading on Arduino, or is it something else

No multithreading needed; it is something else. You may want to be more specific in your question, explain what you want to do and what you have already tried. As it stands, you won't get any useful answers.

While it is completely possible to hook two or more sensors to Arduino, once you talk about multithreading, you need to think about RTOS support. You can achieve parallel processing by creating 2 diffenent tasks using xTaskCreate in freeRTOS. Latest development support in Arduino allow to create such tasks.
https://github.com/feilipu/Arduino_FreeRTOS_Library
While the concepts of RTOS are vast, you can quickstart with Arduino freeRTOS library and check whether it meets your requirements. I used to do such project for obstable avoider bot and faced lot of challenges if there is no parallel processing. I am sure you'll be able to acheive much better results with multithreading.
Regarding sensor, make sure ultrasonic sensor is giving reliable data for every readings and don't use IR sensor under sunlight conditions otherwise it'll give erratic results. All the best with your project!

Arduinos don't do multithreading. There are a number of attempts at implementing such things, but they're a waste of time and resources.
Instead you need to get into the habit of two things:

Write non-blocking code
Make use of the internal hardware peripherals when possible

The motors, using the hardware PWM, are very much "fire and forget" - set them going and you can forget about them until you want to change their speed or direction.
Ultrasonic sensors can be made both more accurate and more "in the background" by using the Input Capture peripheral of the Arduino.
IR sensors (I assume you mean proximity sensors) are usually either just like a button or a potentiometer - you just read them when you want to know what it's doing.
It's your task to learn how to fit all that together into a single program that reacts to the inputs in the way you want and control the motors in the right way.


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.

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.

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.

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.