text:
Connecting CAT5 robustly between portable Arduino and more portable sensors
Newbie wiring question. I’m building a lightwand of some sort, involving an RGB LED and a few pushbuttons that I want to wave around (the “remote”), while staying connected over ~0.5 - 3m to an Uno (the “head”).
In a portable incarnation, the remote might be on your finger and the battery-operated head in your backpack. I’m hoping to use stranded CAT5 for the connection between them (“the bridge”) — it’s the right number of conductors, good flexibility, I have lots of it.
My question is: how should I best mate the CAT5 to both ends — pins on the Arduino at the head, and pins or bare wire off my LED and switches at the remote?
At the head, I like the idea of an RJ45 jack (“NOT ETHERNET”), both for modularity and as I’m a bit worried about strain on the cable pulling wires out of Arduino pins. (The jack basically gives me a good interface at the enclosure level.) I could get an RJ45-to-wiring-terminal-block, and then run solid jumpers from the block to the pins, but they’re expensive. I could try a keystone jack and just try using solid jumpers rather than more CAT5 going between the jack’s wire-breakout and the Arduino board — but I worry the jumpers won’t be the right “size” for the jack, and I’m worried about flimsiness. (If the entire head enclosure is in your backpack, it’s going to get jostled. I want something durable.)
I see some examples of an RJ45 jack soldered directly to a board. What sort of RJ45 is that, and could I do that and solder straight to the board pins on a cheap shield, with relatively novice soldering skills? Or is this at risk when people yank the cable inadvertently?
As I said: I’m a newbie, don’t know what’s reasonable, and keep coming up with overcomplicated architectures where the CAT5e connects to a jack to a block to jumpers to pins,  etc. etc.
At the remote, I think I’m better off. Things need to be as small/portable as possible, so I think I bring the bare stranded wire out of the CAT5e onto a tiny bit of board, and just solder the strands directly to the leads coming off my buttons and LED, and wrap some tape around it, then attach the whole thing to a glove or a bracelet to keep it relatively immobile at the end of the cable. Ok or terrible?
Thanks for suggestions, directions, and other help. I’ve looked around and don’t see questions at this level of ignorance. One of the answers to this mentions that “people wire a RJ45 sock directly to an Arduino” (my head problem) but doesn't say exactly how.  How can I attach sensors without a shield for a wearable project? is doing what I want, but also underspecified...

Certainly go for RJ45 sockets.  Not only does it help protect the wire, but it gives you a really easy way of swapping the wire for different lengths should you want to.
You can't solder an RJ45 socket directly to a normal prototyping board. The pins aren't in the right pattern.  So, you could go for something like this

That can then either be soldered to wires or, since the pins are now in a normal 0.1" pitch, solder the whole module to a prototype board or shield.
Be sure you get a vanilla RJ45 socket, not a "MagJack", which contains extra Ethernet-specific electronics inside it.
If you do want to solder the wires directly to a PCB simply drill a couple of holes just in from one edge of the PCB, run the cable between them, and strap a cable tie around it.  Here's an example:

That PCB has specially shaped slots designed into it for the cable tie.
Also, for soldering, you want a good quality cable. A cheap one from eBay will most likely be made of aluminium with a thin plating (if you're lucky) of copper. A better quality one will be made entirely of copper. Aluminium cables don't solder well. Fine for crimping to an RJ45 plug, but rubbish for soldering.

Thanks @Majenko, esp. for the clarification re MagJack. I can use both of your suggestions on different ends of my cable: breakout board soldered to Arduino shield at the head end, cable tie to local support deck at the remote end.


text:
I need help with code for two 74HC595
I created and learned this code myself from many examples. I tried to add another chip to it, but I have no idea. Do I need to rewrite all of it? Just some simple code is needed.
int latchPin = 2;
int dataPin = 3;
int clockPin = 4;
const int analogPin = A0;
const int ledPin = 13;
const int EmptyEn = 0;
const int GreenOne = 100;
const int GreenTwo = 200;
const int GreenThree = 300;
const int GreenFour = 400;
const int YellowOne = 500;
const int YellowTwo = 600;
const int RedOne = 750;
const int RedTwo = 900;
const int MaxHold = 1000;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop() {
  int analogValue = analogRead(analogPin);
  if (analogValue > GreenOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00000000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > GreenOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B10000000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > GreenTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11000000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > GreenThree) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11100000);
    digitalWrite(latchPin, LOW);
    delay(1);
  }
  if (analogValue > GreenFour) {
    digitalWrite(latchPin, HIGH);
    shiftOut(dataPin, clockPin, MSBFIRST, B11110000);
    digitalWrite(latchPin, LOW);
    delay(1);
  }
  if (analogValue > YellowOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > YellowTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111100);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > RedOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111110);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > RedTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111111);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > MaxHold) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00000000);
    digitalWrite(latchPin, HIGH);
    delay(100);
  }
  Serial.println(analogValue);
  delay(1);
}

Can you give more guidance, such as stating what is wrong, posting any compile errors, and then asking a specific question?

Look for a repetition in your code.
  //Repeating code..
  if (analogValue > GreenOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00000000 );
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

  if (analogValue > GreenTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B10000000 );
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

You will notice that you have a lot of repetition of the general structure of a if-comparison (always with a different value) and then a shiftOut with a different value to be shifted out.
  //General code structure
  //Only things to change is someComparisonValue and someDataValue
  //the rest is the same.
  if (analogValue > someComparisonValue) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, someDataValue);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

You can generalize and simplify the code by storing those different comparison values and data values in a look-up table (LUT). Now you could use two arrays to hold these values but you could also further condense it in a C struct, a "data structure".
Let's define a data structure which holds a threshold value and then the data to be shifted out as  struct.
/* Defines a LUT entry */
struct LutEntry {
    int treshhold;  /* threshhold value */
    byte data;      /* data to be shifted out */
};

We can then pack the actual data into a single variable. Because this is constant data, it will take up flash memory instead of RAM.
static const LutEntry lutTable[] = {
    { GreenOne, B00000000},
    { GreenOne, B10000000},
    { GreenTwo, B11000000},
    { GreenThree, B11100000},
    { GreenFour, B11110000},
    { YellowOne, B11111000},
    { YellowTwo, B11111100},
    { RedOne, B11111110},
    { RedTwo, B11111111},
    { MaxHold, B00000000}
};

From there we can also see that there is a computable relationship between the index of the treshhold value and the data to be shifted out - an entry at index i will be associated with the data bitstring in which all bits from the MSB up to i inclusive are 1, the rest being 0. Except for MaxHold as special value. We could exploit this property to get rid of that data member entirely, but that is an exercise left to you.
Now we can re-write the loop code by simply taking a analogRead sample and then iterating through the entires of the LUT to shift out the corresponding data.
void loop() {
    int analogValue = analogRead(analogPin);
    int numLutEntries = (int)(sizeof(lutTable) / sizeof(lutTable[0]));

    for(int i=0; i < numLutEntries; i++) {
        if (analogValue > lutTable[i].treshhold) {
            digitalWrite(latchPin, LOW);
            shiftOut(dataPin, clockPin, MSBFIRST, lutTable[i].data);
            digitalWrite(latchPin, HIGH);
            delay(1);
        }
    }
    Serial.println(analogValue);
    delay(1);
}

Which transforms 69 lines of repeating code into 12 lines of non-repeating code.
After this general code cleanup it becomes easier to add another shift register: You can define a new look up table, or modify the structure of the old one, to hold the information you need (treshholds, data to be shifted out, the clock, data and latch pin for the register, ...). What logic needs to be there is something only you know, because the description "add another chip [to this code]" is quite broad.
In short:

DRY: Don't repeat yourself. If you use a piece of code over and over again with only slight variances in used values, make it a function
recognize the differences of the used data values in used code pieces and try to group them neatly together. Use the language feature of structs or class to express the meaning of this data
exploit certain properties / relationships of your data to save even more memory / computing time.

source: Stack Exchange

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

sort: votes


text:
PROGMEM Corrupted Array
I am trying to store a large number of values into a couple of arrays using PROGMEM, but I am finding that a few of the values are read back corrupted. I am storing just 1s and 0s, but when I read these values back, I will sometimes get values greater than 1. I am using a MEGA 2560 to do this.
// Each array contains 32000 values
const byte VALUES_1[] PROGMEM = { 1, 0, 1, .... 0 };
const byte VALUES_2[] PROGMEM = { 1, 1, 0, .... 0 };
const byte VALUES_3[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_4[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_5[] PROGMEM = { 1, 0, 1, .... 1 };

const long ARR_LEN = 32000;
long index = 0;

void setup() {
  Serial.begin(57600);
  while (!Serial) {}
}

byte readNextValue() {
  if (index >= 160000L) {
    return -1;
  }

  Serial.print(index);
  Serial.print(" ");

  long arr = index / ARR_LEN;
  long i = index % ARR_LEN;
  index++;

  byte j = -1;
  switch(arr) {
    case 0:
      j = pgm_read_byte_far(VALUES_1 + i);
      Serial.println(j);
      return j;
    case 1:
      j = pgm_read_byte_far(VALUES_2 + i);
      Serial.println(j);
      return j;
    case 2:
      j = pgm_read_byte_far(VALUES_3 + i);
      Serial.println(j);
      return j;
    case 3:
      j = pgm_read_byte_far(VALUES_4 + i);
      Serial.println(j);
      return j;
    case 4:
      j = pgm_read_byte_far(VALUES_5 + i);
      Serial.println(j);
      return j;
  }

  Serial.println("Unable to return next value");
  return -1;
}

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

What I have noticed is that when I use pgm_read_byte_far for case 0 I will get garbage values for right away, but using pgm_read_byte_near will cause these garbage values to occur sometime later. Any insight to this problem is appreciated.

Don't use either near or far? Let the compiler work out which is which?

Your total array size is 5 * 32000 = 160,000 bytes. Why not store it as bits which would only take 20000 bytes? Then all the issues of far-addressing would go away. You could use a small script to turn your 0s and 1s into suitable bytes, and then a simple macro or function to extract the individual bits.

Also see this question about indexing into large arrays, where I posted an answer that avoided corruption.

Thanks for the answers guys. Ill try some of the suggestions tomorrow and see how it goes. If worst comes to worst, it looks like I will have to just use bits like Nick suggested to avoid the 64k addressing problem that Arduino seems to have.

The Mega has reasonably limited memory, if you are storing only 0 or 1 in a byte (8 bits) you lose a lot of memory (7 unused bits per byte). Consider combining 8 0's and 1's into 1 byte (using bit shifting operators).

Just a follow up in case someone else has the same problem. One solution is Nick's answer in his comment, which grabs the far addresses first in the setup, storing them in an array, and using them. I
// Each array contains 32000 values
const byte VALUES_1[] PROGMEM = { 1, 0, 1, .... 0 };
const byte VALUES_2[] PROGMEM = { 1, 1, 0, .... 0 };
const byte VALUES_3[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_4[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_5[] PROGMEM = { 1, 0, 1, .... 1 };

long VALUES[] = { 0, 0, 0, 0, 0 };

const long ARR_LEN = 32000;
long index = 0;

void setup() {
  Serial.begin(57600);
  while (!Serial) {}

  VALUES[0] = (long) pgm_get_far_address(VALUES_1);
  VALUES[1] = (long) pgm_get_far_address(VALUES_2);
  VALUES[2] = (long) pgm_get_far_address(VALUES_3);
  VALUES[3] = (long) pgm_get_far_address(VALUES_4);
  VALUES[4] = (long) pgm_get_far_address(VALUES_5);
}

byte readNextValue() {
  if (index >= 160000L) {
    return -1;
  }

  Serial.print(index);
  Serial.print(" ");

  long arr = index / ARR_LEN;
  long i = index % ARR_LEN;
  index++;

  byte j = pgm_read_byte_far(VALUES[arr] + i);
  Serial.println(j);

  return j;
}

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

This runs perfectly with all bytes correct. The better answer would be to convert the bytes into bits like everyone else was saying in order to save memory space.

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


text:
Arduino + nRF24L01 + ESP8266 mod
I was wondering if it is possible to connecting two Arduino boards with each other (Uno + Nano) using an ESP8266 mod on one of them and an nRF24L01 on the other board?
I have seen lots of details of connecting two nRF but couldn't find any about ESP talking to nRF.

No. That would be like trying to connect your TV to your microwave. Both RF devices, but both work different ways and do different things.
Just because they are both rectangular boxes with a window in the front doesn't mean they are the same.

No, that is not possible: the ESP8266 is a WiFi SoC, and the nRF24L01 uses a proprietary protocol.
The fact that they both operate in the same frequency range doesn't matter if the protocols are different.


text:
Bluetooth module HC-05 not finding mobile phones, only PC
I put the HC-05 in the AT mode with arduino and the comands:
AT+CMODE=1
AT+ROLE=1
AT+INQM=0,10,48
AT+CLASS=0
AT+INIT
AT+INC

It responds "OK" after all till AT+INC, and after this, shows only my notebook's adress, but it has many other mobile phones near with bluetooth on (I can find with my cell phone) and they are not found. Why? Someone help me please

Bluetooth maybe on, but some phones are "invisible" until you put them in "other Bluetooth devices can find me" -mode. Current iPhones are visible when Bluetooth is on but, Androids for example, (at least 7.0 upwards) are visible only when you have the Bluetooth settings screen open.

I'll make my comment an answer then, which you can mark as correct, so other people with the same problem can find the solution here. ;)

Bluetooth maybe on, but some phones are "invisible" until you put them in "other Bluetooth devices can find me" -mode.
Current iPhones are visible when Bluetooth is on but, Androids for example, (at least 7.0 upwards) are visible only when you have the Bluetooth settings screen open.


text:
What are these components in Arduino Mega Schematic?

I was looking at Arduino Mega's reference schematic here and trying to understand how the circuit functions. However, I am unable to understand what these schematic symbols (marked in black rectangles) represent or what their function is. Can anyone please explain it to me?

@Transistor accurately answered what they are. I'll approach their specific function.
The Arduino Mega documentation gives some information on "RESET-EN" and "UBOOT."

"RESET-EN" allows you to enable/disable the auto-reset feature. By default there is a trace between the pads. That's why it look like there is a short in parallel below it. Cut the trace to disable auto-reset. Solder bridge back together to re-enable.
With auto-reset enabled, the board will automatically reset every time the serial communication is initially established. This causes problems if you are using a non-usb power supply and want to plug in for some debugging or have a design that opens and closes serial comm.
"UBOOT" is related to the DFU (Device Firmware Update) bootloader. This may be on the back of the board and will be different between revs.

The ATmega16U2/8U2 is loaded with a DFU bootloader, which can be activated by:

On Rev1 boards: connecting the solder jumper on the back of the board (near the map of Italy) and then resetting the 8U2.
On Rev2 or later boards: there is a resistor that pulling the 8U2/16U2 HWB line to ground, making it easier to put into DFU mode.

You can use this to update the USB firmware and even change the device name when you plug it in. More info here.

"GROUND" can optionally link USB ground (UGND) to the main circuit ground. I don't know enough about USB comm circuit design to understand what the advantages or disadvantages are here. Perhaps someone else can clarify this idea. ATMEGA8U2-MU datasheet for reference.

The symbol indicates a pair of solder pads that can be bridged by the user using a blob of solder.
Here's something similar.

Figure 1. Source: CyberGibbons.


text:
Arduino Mega not recognized by device manager
My lab partner and I are working on a project for school and we are using an Arduino Mega 2560 for prototyping. The board was working just fine until, out of nowhere, the board was not being recognized at all. I tried reinstalling the IDE but still it does not work. I checked to see if the Arduino driver was installed, but the board does not show up in the device manager. Also, the L LED on the board does not light up at all. Attached are photos to help understand the problem.

If someone could help, it would be much appreciated. Thanks.

Have you tried unplugging all the wires from the Arduino (other than USB) to verify it isn't a problem with something in your project shorting out?

The board was working just fine until, out of nowhere, the board was not being recognized at all - out of nowhere, huh? What was the last thing you were doing with the board when it was working?

The last thing was upload a simple stepper motor code.

Also, to answer Phil C, nothing is plugged to the arduino.

If you guys have any other tips or tricks or advice in general regarding this issue, anything helps.

hey i had the same problem, i am thinking because i installed atmel studio and then this started happening,
I then downloaded arduino from the microsoft store,(no change)
then i restarted the pc, now its compiling and uploaded normally but still does not show the name of the board that is connected just shows lets say just  COM22 with out saying what board


text:
DS2436 Arduino UNO programming
I am struggling with programming my DS2436 chip using an Arduino UNO. To be honest, I am trying to modify DS18B20 code (the one that is anywhere on the internet) to work with DS2436. It's just harder for me to understand how whole memory and adressing thing work, since DS2436 has those pages of memory blocks, unlike DS18B20, which has only 1. Also the language factor is stopping me, I am not a native speaker.
I keep getting wrong data/temperature/CRC. Can someone assist me, please? I need this thing to show me voltage/temperature and cycles.
#include <OneWire.h>
OneWire  ds(10);

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

void loop(void) {
  byte i;
  byte addr[8];
  byte data[32];
  byte type_s;
  byte present = 0;
  float celsius, fahrenheit;

  if (!ds.search(addr)) {
    ds.reset_search();
    delay(1000);
    return;
  }

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }
  Serial.print("\n");
  if (OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("CRC is not valid!");
    return;
    Serial.print("\n");
  }
  if (addr[0] != 0x1B) {
    Serial.print("Device is not a DS2436 family device!");
    Serial.print("\n");
  }
  {
    Serial.print("CRC= ");
    Serial.print(OneWire::crc8(data, 8), HEX);
  }
  Serial.print("\n");
  ds.reset();
  ds.select(addr);
  ds.write(0xD2, 1);
  delay(1000);
  present = ds.reset();
  ds.select(addr);
  ds.write(0xB2);
  Serial.print("  Data = ");
  for (int i = 0; i < 13; i++) {
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();
  unsigned int raw = (data[1] << 8) | data[0];
  int sig = raw & 0x8000;
  if (sig) {
    raw = (raw ^ 0xffff) + 1;
  }
  celsius = (float)raw * 0.03125;
  Serial.print("Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius ");
  Serial.print("\n");
  Serial.print("_______________________________________________");
  Serial.print("\n");
}

Please take a look at the OWFS sources, it has host code examples for almost every onewire chip ever produced: https://github.com/owfs/owfs/blob/master/module/owlib/src/c/ow_2436.c

You are a savior!

Yes necro, but having my own example of a DS2436 to try this out on, and having to write code for it with little else to go on, seems like the IC doesn't really know what to send you when reading the bus after sending the read register command.
As per the datasheet, 0xFF is data the IC sends when the bus master reaches the end of a page or an address that's reserved. Adding in ds.write(0x60); before performing the read cycles fixes most of this.
Haven't gotten into much past that, but it seems like there's also something not quite right going on with your arithmetic to turn your binary into temperature. Even with my fix getting something serviceable as output, I get 1024.00 Celsius.

Re “there's also something not quite right going on with your arithmetic to turn your binary into temperature”: It is indeed broken. Try this fix: int16_t raw = (uint16_t) data[1] << 8 | data[0]; float celsius = raw * (1.0/256);

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


text:
Digital input signal to be converted to analog signal
Hello and a very good day.
I am currently doing my final year project which involving Arduino KY-031 Knock Sensor as my input signal and it is apparently a digital type of sensor. So, my question is can the digital signal be converted to analog signal ?
The reason I need it to be analog signal because I wanted it to be classified into 3 type of stages (low,medium,high).
p/s: I am using Arduino Uno as my controller.

Yes, there is a Digital-to-analog converter. it is apparently a digital type of sensor - what is this sensor? Please read How do I ask a good question?.

The Arduino is a digital device. You are getting a digital input. How will it help to convert it to analog?

@NickGammon It's a KY-031 as per the question :-)

Oh yes, sorry. If you want loudness then you need a different sensor, like a small microphone where you could detect the level of output from it.

You can create an analogue representation of any signal - but you can't add in information which wasn't previously there.  The KY-031 doesn't give you any more information than "knock" or "no knock", so there's no way to get further detail out of it.


text:
Having an issue running an Arduino sketch
I just got my USB host shield attached to my Arduino Uno, opened the program sketch for USBDESC.ino and I'm getting an error. It says "usbhub.h not found". It won't compile. How did I go wrong?
I am using the Mac version of the Arduino IDE and downloaded the USB host shield Master v 2.0 file directly into /Arduino/java/examples. This was how I have added every previous library download. Please help. Thanks.

is that file in the arduino path? did you search for it?

I don't know how you came up with that location as the right place to put libraries. It is wrong. Oh so very wrong.
Libraries go in ~/Documents/Arduino/libraries as stated in the first hit for "arduino macos libraries" on Google.

ok that worked, but now I just get a garbled output from running the script


text:
GPS showing incorrect speed
I am using Arduino ATmega 2560.
When i am using "AT+CGNSINF" command to get GPS value, sometimes it showing incorrect speed.
The correct speed should be (50-60)km/h but sometimes it showing (200-300)km/h.
How can I fix the problem or avoid/ignore the unexpected speed.
here is my code
void get_GPS()
{
    sendATCommand("AT+CGNSINF","OK", 1000);

    // condition for valid response
    while (strstr(AT_Buffer, "+CGNSINF: 1,1") != NULL)
    {
        delay(3000);
        strtok(AT_Buffer, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        Serial.println("\n");
        Serial.println(strtok(NULL, ","));

        //sendATCommand("AT+CGNSINF", "OK", 1000);
    }
}
uint8_t sendATCommand(char* ATcommand, const char *expectedResponse, unsigned long timeout)
{
    uint8_t x = 0, answer = 0;

    memset(AT_Buffer, '\0', AT_BufferLength);    // Initialice the string
    delay(100);
    while (Serial1.available() > 0) Serial1.read();    // Clean the input buffer
    if (ATcommand[0] != '\0')
    {
        Serial1.println(ATcommand);    // Send the AT command
    }

    unsigned long previous = millis();

    // this loop waits for the answer
    do {

        if (Serial1.available() != 0) {    // if there are data in the UART input buffer, reads it and checks for the asnwer
            AT_Buffer[x] = Serial1.read();
            //Serial.print(AT_Buffer[x]);
            x++;
            if (strstr(AT_Buffer, expectedResponse) != NULL)    // check if the desired answer (OK) is in the response of the module
            {
                answer = 1;
                break;
            }

        }
    } while ((millis() - previous < timeout));    // Waits for the asnwer with time out

    return answer;
}

Need to check your code, May you need to correct something there...

here is my code https://pastebin.com/Rzc1qXTF

Edit your question, put the code into it. Select it and press Ctrl+K to format it as code.

ERR_CONNECTION_TIMED_OUT link is not opening..

Speed calculation in most GPS systems is very crude. It consists of simply "Where was I then? Where am I now?". Many will also add "How long has passed between then and now?", but many also don't - they assume a fixed time between points (1 second, for example). It doesn't know it's supposed to move, all it knows is the coordinates it has at the moment.
With the latter, if you don't get a reading for a couple of seconds (buildings in the way, for example) the position can suddenly jump a long way.  You can see the effect in your phone's GPS in built-up areas - your position may jump long distances and then pause for a bit.
To visualise it in 1-dimension, you can think of a simple number sequence 0-9 and the difference between each value:
Value:        0 1 2 3 4 5 6 7 8 9
Difference:     1 1 1 1 1 1 1 1 1

The difference equates to the "speed" of the sequence.
Now if the numbers don't get updated smoothly, but all at once at the end, you get something like:
Value:        0 1 2 2 2 2 2 7 8 9
Difference:     1 1 0 0 0 0 5 1 1

The end results is the same, but you get a "dead" period with no "movement" and then a big jump with an unusually high speed.
It's up to you to filter out such anomalies. It's simple enough to say "5 is too much - ignore it". You could also average the past 10 seconds worth of data (for example) and use that as your average speed over that time period, which would smooth out such peaks and troughs.


text:
A4988 and capacitors
I’m working at a project which involves 3 stepper motors that are driven by A4988 drivers. I have read that I have to connect an 100uf capacitor in parallel with the motor power supply that goes to the driver, but do I have to use a capacitor for every driver, or only 1 capacitor because the drivers are connected in parallel to the same 12v power supply.

I saw the scematic

I saw the schematic in an instructable, it explained why he uses it, but it was only for one stepper

Yoiu have missed to post the url to  what you refere to!

There are two purposes of such capacitor:

first it supply power for short peaks in demand, so effectively enabling the 12V power source supply much more current for short time, than it can support over long time and so the driver have more stable power and works generally better. Also it protects the driver from noise of other parts.
the other is protect all other parts from voltage drops and noise caused by the driver. It is recomended to have capacitors as near as possible to any IC/driven circuit for this reason.

So basically - if you have good power source, you can often get away even without such capacitors. But if you power also logic from the same source, it is already better to have some capacitors on power lines where posssible. Escpecially if you expect some noise around (like having motors near or lines to motors in paralel with other lines ...). Depends how much you care and how critical you see the project. Hobby project just for fun can go even without capacitors and be all good. Good industry projects have capacitors always everywhere.
I had project, where it worked even without capacitors (laser printer), but now I would place some there in any case near each driver, just to be sure. 100uF is really good capacity, enables for lot power. But if you use any other value (which you have more ready), it should not hurt too. It is not about if it would work or not, it is more about if it ensures, that it would work flawlessly even in bad conditions even under unexpected conditions and would not have "sometimes strange problems, which disapear spontaneously during debugging".
Also note, that for improving power are good high capacity electrolytes. For preventing noise are much better ceramic (which are fast, even if they have a lot smaler capacity) and so many people put both there (like 100uF electrolyte and 100nF ceramic in paralel).
Short answer: Do as you want, it would probably work anyway. I personally would place big+small capacitors near each driver.

Thanks for your detailed answer, it clarified my problem.


text:
Printing transmission data from nRF24L01+
I have a beginner's problem. I have 2 nRF24L01+ devices. They are communicating with each other great, and I can talk with the nRF via SPI.
The problem is I want to display, on the serial monitor, the number of retransmitted packets (ARC_CNT) and the number of lost packets (PLOS_CNT), which are both in the "observe_tx" register on the nRF.
I am using the "Getting Started" example from RF24 1.3.1, with Arduino 1.84, with a few more bits added, and it all works great apart from getting it to show PLOS_CNT & ARC_CNT! I have tried:
printf_P(PSTR("OBSERVE_TX=%02x: PLOS_CNT=%x ARC_CNT=%x\r\n"));

But this does not give the correct result.
As you have probably guessed, I know nothing about C or C++. There must be a simple way of showing the 2 numbers?
The code I am using is:
#include <SPI.h>
#include "RF24.h"
#include <printf.h> // Required for "radio.printDetails();"

/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 0;

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(7, 8);
/**********************************************************/

byte addresses[][6] = {"1Node", "2Node"};

// Used to control whether this node is sending or receiving
bool role = 0;

void setup() {
  //pinMode(53,OUTPUT); //may not be required after all
  Serial.begin(115200);
  printf_begin(); //required for "radio.printDetails();" to work
  Serial.println(F("RF24/examples/GettingStarted"));
  Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));
  radio.begin();
  // Set the PA Level low to prevent power supply related issues since this is a
  // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  radio.setPALevel(RF24_PA_LOW); // _MIN, _LOW, _HIGH, _MAX
  radio.setDataRate(RF24_250KBPS); //250KBPS, _1MBPS, _2MBPS  Lowest rate gives longest range.
  radio.setChannel(108); // 0 - 124 (2.4GHz - 2.524GHz) Usually above 100 best. USA 70 - 80 best.
  radio.setRetries(15, 15); // set retry delay and no of retries. delay between retries, 0=250uS, 15 = 4000uS
  radio.setCRCLength(RF24_CRC_16);  // 8 or 16 bit crc
  radio.printDetails();
  Serial.print(radio.getChannel());
  radio.setAutoAck(1);
  // Open a writing and reading pipe on each radio, with opposite addresses
  if (radioNumber) {
    radio.openWritingPipe(addresses[1]);
    radio.openReadingPipe(1, addresses[0]);
  } else {
    radio.openWritingPipe(addresses[0]);
    radio.openReadingPipe(1, addresses[1]);
  }
  // Start the radio listening for data
  radio.startListening();
}

void loop() {
  /****************** Ping Out Role ***************************/
  if (role == 1)  {
    radio.stopListening(); // First, stop listening so we can talk.
    Serial.println(F("Now sending"));
    unsigned long start_time = micros();
    // Take the time, and send it.  This will block until complete
    if (!radio.write( &start_time, sizeof(unsigned long) )) {
      Serial.println(F("failed"));
    }
    radio.startListening(); // Now, continue listening
    unsigned long started_waiting_at = micros(); // Set up a timeout period, get the current microseconds
    boolean timeout = false; // Set up a variable to indicate if a response was received or not
    while (!radio.available()) {
      // While nothing is received
      if (micros() - started_waiting_at > 200000 ) {
        // If waited longer than 200ms, indicate timeout and exit while loop
        timeout = true;
        break;
      }
    }

    if (timeout) {
      // Describe the results
      Serial.println(F("Failed, response timed out."));
      printf_P(PSTR("OBSERVE_TX=%02x: PLOS_CNT=%x ARC_CNT=%x\r\n"));
    } else {
      unsigned long got_time;
      // Grab the response, compare, and send to debugging spew
      radio.read( &got_time, sizeof(unsigned long) );
      unsigned long end_time = micros();
      // Spew it
      Serial.print(F("Sent "));
      Serial.print(start_time);
      Serial.print(F(", Got response "));
      Serial.print(got_time);
      Serial.print(F(", Round-trip delay "));
      Serial.print(end_time - start_time);
      Serial.println(F(" microseconds"));
    }
    // Try again 1s later
    delay(1000);
  }

  /****************** Pong Back Role ***************************/
  if (role == 0) {
    unsigned long got_time;
    if (radio.available()) {
      // Variable for the received timestamp
      while (radio.available()) {
        // While there is data ready
        radio.read(&got_time, sizeof(unsigned long));
        // Get the payload
      }
      radio.stopListening();
      // First, stop listening so we can talk
      radio.write(&got_time, sizeof(unsigned long));
      // Send the final one back.
      radio.startListening();
      // Now, resume listening so we catch the next packets.
      Serial.print(F("Sent response "));
      Serial.println(got_time);
    }
  }

  /****************** Change Roles via Serial Commands ***************************/

  if (Serial.available()) {
    char c = toupper(Serial.read());
    if (c == 'T' && role == 0) {
      Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
      role = 1; // Become the primary transmitter (ping out)
    } else if (c == 'R' && role == 1) {
      Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));
      role = 0; // Become the primary receiver (pong back)
      radio.startListening();
    }
  }
} // Loop

printf_P(PSTR("OBSERVE_TX=%02x: PLOS_CNT=%x ARC_CNT=%x\r\n"));

This should be
printf_P(PSTR("OBSERVE_TX=%02x: PLOS_CNT=%x ARC_CNT=%x\r\n"),
 OBSERVE_TX, PLOS_CNT, ARC_CNT);

Where the two variables contain the values.

first OBSERVE_TX= means the text that is literally printed
%02X is the format of the variable which is printed
OBSERVE_TX is the variable name

The variable names should be in the same order as the formatting (%'s).
However, in your case the above will not result in the values you want. The items above (OBSERVE_PLOS_CNT and ARC_CNT) are offsets from an addres. What you want is to print the content of that address. Since I don't have an Arduino IDE nearby, you should find yourself the address, and use *(address + OBSERVE_PLOS_CNT). This will use the address, adds OBSERVE_PLOS_CNT, and * means it will show the content of that new address.
Btw, I'm not sure about the exact use of printf_P and PSTR.

When i try that, it gives me "observe_tx was not declared in this scope" and the same error for "plos_cnt", and does not compile. So if i declare a variable called "observe_tx", and substitute "4" for "plos_cnt" ("#define PLOS_CNT 4", in nRF24l01.h), then it prints in the serial monitor : "OBSERVE_TX=401: PLOS_CNT=0 ARC_CNT=7304, with ARC jumping 7304, 1ec4, ca88, 7650, 2218, cddc, 79a8.... each time the loop executes.
I expect PLOS, ARC to initially both be 0, and for ARC to increment  Thanks for your explanation of the additional details - good for my understanding.

The "observe_tx" register is address 0x08. "PLOS_CNT" is defined as 0x04, and ARC_CNT as 0x00. Bits 0-3 of 0x08 register are counting retries, bits 4-7 of 0x08 are counting packet loss. So, if i substitiute address 0x08, and the other numbers:       printf_P(PSTR("OBSERVE_TX=%02x: PLOS_CNT=%x ARC_CNT=%x\r\n"),
*(0x08), 0x04, 0x00);     it prints OBSERVE_TX=8: PLOS_CNT=4 ARC_CNT=0. These are the numbers, rather than the any value of an address. Have i understood it right ?

True, if you put * in front of it, it shows the content, HOWEVER, I'm sure OBSERVE_TX is not the address itself, it is an offset from a base address, but to be honest, I don't know which one. There must be another #define that contains the base address, so you should use *(base_address + OBSERVE_TX), and similar for others.

many thanks for your help. I have it working now.


text:
How do I improve Bluetooth communication?
How do I improve Bluetooth communication?
You will see, in this image using the Bluetooth monitor application, in order to receive the "ON" response, I had to repeatedly send the "O" character:

The code that I'm using now is this:
#include <SoftwareSerial.h>
const int RX_PIN = 0;
const int TX_PIN = 1;
char c = 'F';
boolean activar = false;

SoftwareSerial blueTooth(RX_PIN, TX_PIN);
void setup ()
{
  Serial.begin(9600);
  blueTooth.begin(9600);
}

void loop ()
{
  if(Serial.available() > 0){
    c = Serial.read();
    if(c == 'O'){
      activar = true;
      Serial.println("ON");
    }
    if(c == 'F'){
      activar = false;
      Serial.println("OFF");
    }
  }
  if(activar){
     detectarObstaculos();
  }
}

void detectarObstaculos(){

}

How could I improve the response time?

Why are you using software serial on pins 0 and 1? How do you expect to work alongside hardware serial which also uses pins 0 and 1?

I see it on a tutorial (http://www.instructables.com/id/Add-bluetooth-to-your-Arduino-project-ArduinoHC-06/)
Is that the problem then?

The (unused) bluetooth SoftwareSerial object is conflicting with the HardwareSerial object on the same pins that you are using. One or the other. Make your mind up.

Instructables is full of crap. It should be deleted from the internet.

Ugh, so the tutorial was bad .... I see. @Majenko, I will change my pins then

No need to change your pins. Just delete the SoftwareSerial since you're not actually using it.

@TwoDent That tutorial doesn't even mention software serial. And it isn't in the code either.


text:
Looking for Power Bank with "Always-On-Feature"
I want to build a mobile weather station with an Arduino and some sensors. I want to use a power bank as power source. The Powerbank should support "Always-On", because weather data should not be measured continuously. This means that almost no current flows between the time intervals. Common power banks switch off automatically when the current flow is low.
I don't want to connect an additional device or electronic component to increase the power consumption. So I need a power bank that doesn't switch off even when the current flow is low.
During my search I found the Powerbank "V44 USB Battery Pack" from Voltaic. Unfortunately I cannot buy them in Germany.
https://www.voltaicsystems.com/v44
Can anyone recommend an alternative?

Wouldn't you just use a straight battery then?

Welcome to Arduino SE.  There is a great tour available at https://arduino.stackexchange.com/Tour that shows how to get the most out of this site.

Lithium cell based powerbanks use a boost converter to boost the voltage from the Cell to the 5V for the USB. They turn off because keeping the voltage boosted when not used wastes quite a bit of power.
If all your devices can run straight on 3.3V you can use a Lithium cell directly with a voltage regulator (and with the normal protection circuitry).
Otherwise you can simulate a button press on the on button with a gpio pin to activate the boost circuitry when you are ready to take your measurements; let he voltage stabilize; use transistors to connect the components to power; take your measurements; disconnect the components and then let the timeout expire after which the voltage will drop again.

how are you using gpio pin to turn on the power bank, when that power bank is what is powing the arduino

arduino can survive on 3.3V (which the non boosted cell can provide straight up) and the button often just pull a line low which you can do with a GPIO.


text:
Single & multi sensor code
I have been having problems trying to run multi sensor code for my project, this requires four KY-024 Linear magnetic Hall sensors as position sensors that trigger NC independent relays to make a circuit.
I can get the code to run on one independent circuit, one hall switch one relay with no problems.
But when I try the code for 4 hall sensors + relays I get no response from the circuit at this point I am at a loss where to go from here the code compiled with no problems.
int hallswitch = 1;
int val = 0;
int RELAY1 = 6;

void setup() {
  pinMode(hallswitch, INPUT);
  pinMode(RELAY1, OUTPUT);
}

void loop() {
  val = digitalRead(hallswitch);

  if (val == HIGH) {
    digitalWrite(RELAY1, HIGH);
  }
  else {
    digitalWrite(RELAY1, LOW);
  }
}

and
int hallswitch1 = 1;  //Pin for Hall switch
int hallswitch2 = 2;  //Pin for Hall switch
int hallswitch3 = 4;  //Pin for Hall switch
int hallswitch4 = 5;  //Pin for Hall switch

int val = 0;       //Integer for reading Hall statu

int RELAY1 = 6;    // The socket number on the Arduino that the relay1 will go to.
int RELAY2 = 7;    // The socket number on the Arduino that the relay1 will go to.
int RELAY3 = 8;    // The socket number on the Arduino that the relay1 will go to.
int RELAY4 = 9;    // The socket number on the Arduino that the relay1 will go to.

void setup()
{
  pinMode(hallswitch1, INPUT);
  pinMode (RELAY1, OUTPUT);

  pinMode(hallswitch2, INPUT);
  pinMode (RELAY2, OUTPUT);

  pinMode(hallswitch3, INPUT);
  pinMode (RELAY3, OUTPUT);

  pinMode(hallswitch4, INPUT);
  pinMode (RELAY4, OUTPUT);
}

void loop() {
  val = digitalRead(hallswitch1);               //Read Hall pin status
  val = digitalRead(hallswitch2);               //Read Hall pin status
  val = digitalRead(hallswitch3);               //Read Hall pin status
  val = digitalRead(hallswitch4);               //Read Hall pin status

  if (val == HIGH) {                        //If there is a magnet infront of Hall switch...
    digitalWrite(RELAY1, HIGH);             // Turn RELAY1 on:
    digitalWrite(RELAY2, HIGH);
    digitalWrite(RELAY3, HIGH);
    digitalWrite(RELAY4, HIGH);
  }
  else {
    digitalWrite(RELAY1, LOW);               // Turn RELAY1 off:
    digitalWrite(RELAY2, LOW);
    digitalWrite(RELAY3, LOW);
    digitalWrite(RELAY4, LOW);
  }
}

You are writing all four sensors to the save variable 'val'    Although that will not stop the code from running, but it means the only one you are actually doing anything with is hallswitch4, and you using that value to turn on or off all of the relays,

What do you mean 'get no response'? If you are only trying switches 1,2, or 3 you will not get any response as their values are being over written.

how could i get the code to run 4 hall sensors independently ?

This is the quick and dirty way, I would suggest re writing it to use arrays rather then having to declare all these variables and copy paste pinMode, read,writes if statments a bunch of times.
 int hallswitch1 = 1;  //Pin for Hall switch
 int hallswitch2 = 2;  //Pin for Hall switch
 int hallswitch3 = 4;  //Pin for Hall switch
 int hallswitch4 = 5;  //Pin for Hall switch

 int val1 = 0;       //Integer for reading Hall statu
 int val2 = 0;
 int val3 = 0;
 int val4 = 0;

 int RELAY1 = 6;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY2 = 7;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY3 = 8;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY4 = 9;    // The socket number on the Arduino that the relay1 will go to.

void setup()
{

  pinMode(hallswitch1, INPUT);
  pinMode (RELAY1, OUTPUT);

  pinMode(hallswitch2, INPUT);
  pinMode (RELAY2, OUTPUT);

  pinMode(hallswitch3, INPUT);
  pinMode (RELAY3, OUTPUT);

  pinMode(hallswitch4, INPUT);
  pinMode (RELAY4, OUTPUT);

}

void loop() {

  val1 = digitalRead(hallswitch1);               //Read Hall pin status
  val2 = digitalRead(hallswitch2);               //Read Hall pin status
  val3 = digitalRead(hallswitch3);               //Read Hall pin status
  val4 = digitalRead(hallswitch4);               //Read Hall pin status

  if (val1 == HIGH) {digitalWrite(RELAY1, HIGH);}
  else {digitalWrite(RELAY1, LOW);}

  if (val2 == HIGH) {digitalWrite(RELAY2, HIGH);}
  else {digitalWrite(RELAY2, LOW);}

  if (val3 == HIGH) {digitalWrite(RELAY3, HIGH);}
  else {digitalWrite(RELAY3, LOW);}

  if (val4 == HIGH) {digitalWrite(RELAY4, HIGH);}
  else {digitalWrite(RELAY4, LOW);}

}

also all of the 'pin' variables RELAYx and hallswitchx dont need to be variables since you are not changing them, they are constants.   use #define RELAY1 6     ect

Chad thank you for your help the code works as intended


text:
Distance from Arduino UNO to LCD: How far?
How far from the UNO can I place an LCD (the typical 16x2)? Assuming that everything that is plugged into the LCD comes directly from the Arduino (power and data).
I'd like to mount the LCD on the wall at eye level, my "box" will be on the floor, close to a power source.

Sounds like you are talking 6 feet or so? That should be fine,   I have found that I2C starts needing extenders around 10 feet or so. If you can slow the data rate down that would help as well.

The actual distance depends highly on several other factors:

Wire thickness / current carrying capacity / resistance
RFI (Radio Frequency Interference) environment
Data rate that you write to the LCD (Maybe you are using an I2C or SPI backpack)

In general, even 5 meters is probably going to work if you use sufficient wiring, but try it and see.
You may also need to add shielding to mitigate RFI.


text:
CH340 Nano avrdude: stk500_getsync() not in sync resp=0xa4
I'm trying to upload some code to an non-arduino nano with the CH340G chip, and the avrdude refuses to let me upload. The error I'm getting is:
Using Port                    : COM4
Using Programmer              : arduino
Overriding Baud Rate          : 115200

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xf6

avrdude done.  Thank you.

I've tried installing the drivers for the CH340 chip following this guide but have had no luck. I've also tried uploading to my arduino uno and my arduino micro (both are arduino brand) with no problems. I'm running Windows 10, Arduino IDE 1.8.5
Any ideas?

Thanks, this was my issue as well, Arduino Nano from side manufacturer.

Possible duplicate of Arduino Nano uploading gives error: avrdude: stk500_recv(): programmer is not responding

@scruss. it is not a duplicate. read the answer, check the dates

it sure is: it's an older question having the same problem. Sure, the accepted answer isn't any good, but this one is spot on

@scruss, the 'Old Bootloader' problem didn't exist 5 years ago when the other question was asked.

Arduino has recently changed to using a different bootloader on their official Nano boards that communicates at 115200 baud rather than the previous 57600 baud. Support for these new boards was added in Arduino AVR Boards 1.6.21. The new Nano board definition is not compatible with old Nanos and likely most 3rd party Nanos so backwards compatibility is provided via the Tools > Processor > ATmega328P (Old Bootloader) menu selection.

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


text:
How do I execute some code at a certain time without RTC module?
I am building a project when I need my arduino to execute some code at two given hours of the day, for example one at 19:00 and another at 06:00. I know that with a RTC module I can do this easily, however how can I do that without a RTC module? I do not want to have to connect my arduino to a computer neither to the internet. It does not also have to be precise, a couple of minutes off would be ok.
My board is an Uno R3.

It depends on your arduino board. Is there a resonator or a crystal? If you have a crystal then you could use the time and timealarms libraries and let the time library run on millis(). You can also use millis() for 11 hours and 13 hours without the time library, because millis() can count up to 50 days.

@Jot My board is an Arduino Uno Rev3.

the esp8266 can read time from NTP service on Internet

Any built-in time facilities are highly inaccurate, from my experience 1-3 minutes off / day - after a month it could easily be executed an hour earlier/later than intedned. You need either RTC or NTP.

@wondra that is probably with a resonator. I have a uno clone with a crystal and it is less than one hour off per year.

If you start with the "BlinkWithoutDelay" sketch that comes with the Arduino IDE, you can execute your code alternating between 11 hours and 13 hours.
// Power up the circuit at exactly 06:00.
unsigned long delayInterval = 0;
unsigned long previousMillis = 0;
bool twoHoursAdded = false;

void setup(){

}

void loop(){

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis >= delayInterval){

    // previousMillis = currentMillis;

    // Use this "method" of incrementing the previousMillis variable
    // instead of the code used in the BlinkWithoutDelay sketch.
    previousMillis += delayInterval;

    if(twoHoursAdded == false){
      delayInterval = 1000UL * 60UL * 60UL * 13UL;
      twoHoursAdded = true;
    }
    else{
      delayInterval = 1000UL * 60UL * 60UL * 11UL;
      twoHoursAdded = false;
    }

    // Your code here that is run at 06:00 and 19:00.

  }
}

"Down sides" to using this code.

If there is a "power failure", the timing will be off, WAY off until you reboot the Arduino at exactly the right time.
You have to power up the Arduino at exactly the right moment for "it's" timing to match your "clock" timing.

If it's within your budget, have a look at the DS3231 modules available on aliexpress.com / ebay.com. They have a lithium battery backup incase of power outage and are really easy to connect to your Arduino using I2C. There are several libraries on Github that simplify using the DS3231 modules.

I am not sure why you are opposed to the RTC or whether you were excluding all external circuitry for the solution. So, I am just throwing this out there...
A CMOS-4060 ripple counter can be programmed for just about any time period and using two of them would give you two separate time constants.

source Substitute the relay for a signal wire to the CPU.
The Cmos 4060 is a 14-bit binary counter. However - only ten of those bits are connected to output pins. The remaining bits - Q1, Q2, Q3 and Q11 - do exist. You just can't reach them.
The 4060 also has two inverters - connected in series across pins 11, 10 & 9. Together with R3, R4, R5 and C3 - they form a simple oscillator.
While the oscillator is running - the 14-bit counter counts the number of oscillations - and the state of the count is reflected in the output pins.
By adjusting R4 you can alter the frequency of the oscillator. So you can control the speed at which the count progresses. In other words - you can decide how long it will take for any given output pin to go high.
When that pin goes high - it switches the transistor - and the transistor in turn operates the relay.
In single-shot mode - the output pin does a second job. It uses D1 to disable the oscillator - so the count stops with the output pin high. .
If you want to use the timer in repeating mode - simply leave out D1. The count will carry on indefinitely. And the output pin will continue to switch the transistor on and off - at the same regular time intervals.
For example, if you want a period of 9 Hours - the Range table shows that you can use the output at Pin 2. You need Pin 2 to go high after 9 x 60 x 60 = 32 400 seconds. The Setup table tells you to divide this by 512 - giving about 63 seconds. Adjust R4 so that the Yellow LED lights 63 seconds after power is applied. This will give an output at Pin 2 after about 9 Hours.
If you increase the value of R3 - and reduce R4 by the corresponding amount - you can set the time delay more precisely. Select a value for R3 that takes you close to the time you're after. And use the reduced value pot - to make the fine adjustment. Note that even finer adjustments are possible with a multi-turn pot.

As mentioned with VE7JRO's solution, this solution (while being pretty accurate) will eventually drift with time and must be powered up at an exact time that is synchronized with the desired trip times.

This is terrible advice. Why would anyone want to add a dozen extra parts only to have a time source that is way worse than the internal timebase of the Arduino Uno? In terms of frequency stability, an RC oscillator like this is about the worst you can get. The ceramic resonator clocking the Arduino is way better, and the quartz crystal of an RTC module is better yet. People go to the trouble of adding an RTC only because it is a better timebase than the millis() they already have.


text:
Can I generate 5 sec delay within an interrupt program?
void buttonPressed()
{
  if(ledOn)
  {
    ledOn = false;
    digitalWrite(13,LOW);
  }else
  {
    ledOn = true;
    digitalWrite(13,HIGH);
  }

  vout=analogRead(sensor);
  vout=(vout*500)/1023;
  tempc=vout; // Storing value in Degree Celsius
  tempf=(vout*1.8)+32; // Converting to Fahrenheit
  lcd.setCursor(0,0);
  lcd.print("ROOM TEMPERATURE");

  lcd.setCursor(0,1);
  lcd.print("C = ");
  lcd.print(tempc);

  lcd.print("  F = ");
  lcd.print(tempf);
  Serial.print("f ");
  Serial.print(tempf);
}

here is the code of interrupt and i want to monitor the sensor value for about 5second.

You don't need interrupts for any of that. Your main loop just needs to test the switch, eg.
void loop ()
  {
  if (digitalRead (button) == HIGH)  // assuming LOW means pressed
     return;

  // read thermocouple here

  // display results

  delay (5000);

  }

I want to print the value of the thermistor on lcd using interrupts and i want the value to stay about 5 secs

You are misusing interrupts in what you are attempting. See my page about interrupts. You simply should not be attempting to print or delay inside an interrupt routine. The most you should do is detect that the switch is pressed:
volatile bool switchIsPressed = false;

// Interrupt Service Routine (ISR)
void buttonPressed()
  {
  switchIsPressed = true;
  }  // end of buttonPressed ISR

Now in your main loop you detect that the switch is pressed and take your reading. If you want to do something else "remember" the time you showed the value, like this:
unsigned long whenTemperatureDisplayed = 0;

void loop ()
  {
  if (switchIsPressed && whenTemperatureDisplayed == 0)
    {
    // take reading ...
    // display reading ...
    whenTemperatureDisplayed = millis ();  // when we displayed the reading
    switchIsPressed = false;               // ready for next time
    }  // end of if switch was pressed

  if (whenTemperatureDisplayed != 0 &&
      millis () - whenTemperatureDisplayed >= 5000) // 5 seconds are up
    {
    // stop displaying the reading ...
    whenTemperatureDisplayed = 0;
    }  // end of if time is up

  // do other stuff here

  }  // end of loop

I am making a temperature monitoring device Thermocouple is the main sensor and I am using thermistor for room temperature sensing. I want to print the value of the thermistor on lcd using interrupts and i want the value to stay about 5 secs. the code is working but i am unable to make a delay of about 5sec while staying on the interrupt

the code is working but i am unable to make a delay of about 5sec - it's working but it isn't, huh? The "not working" part is the part you have to completely rewrite. It isn't almost working. You are not doing it in a way that will work. See amended answer.

My amended answer does not do any delays, and thus you will not have any trouble doing other things, as well as displaying the temperature for 5 seconds.

It's bad practice to use a delay within a timer, and 5 seconds is a huge amount of time. Also print statements and possibly lcd print statements I would not advice.
What is better, is to calculate the value, store it in a global variable (vout?). Than set a boolean that a new value has been calculated.
Your main program checks the boolean and does all the print/lcd code.
If you think you might miss values, than create a global array where you add values in your interrupt, and let the main program process the array.

I am making a temperature monitoring device Thermocouple is the main sensor and I am using thermistor for room temperature sensing. I want to print the value of the thermistor on lcd using interrupts and i want the value to stay about 5 secs. the code is working but i am unable to make a delay of about 5sec while staying on the interrupt.

You can use a delay of 5 sec in your main, or what's even better is to use millis(). Check the blink Arduino program for an example.

delaying 5 sec in my main would cause a delay in the monitored value. I want the sensed temperature to be accurate with time and as well as the interrupt to stay about 5sec.

If you wait 5 sec in interrupt, your main is interrupted for 5 sec and will not do anything, until the interrupt ends. Interrupt would not help you the way you think it would. Use waiting without delay in main and do your measuring/displaying just there.

@PeouseDutta  delaying 5 sec in my main would cause a delay in the monitored value - delaying 5 seconds in the interrupt will also cause a delay in the monitored value, so you haven't achieved anything by delaying there. If you succeed in delaying inside the interrupt no other code will execute during that delay.

I have tried using the above code
unsigned long startMillis = millis();
while (millis() - startMillis < 5000);
but every time I press the buttom the LCD gets freezed. I don't know what to do!

if you do that, you have the same as a delay... you should not use a while but an IF statement, and than do something you want to do every 5  s.

Strictly speaking, yes you CAN generate 5 second delay in interrupt. But you really, really should NOT do it.
And if you are going to do it anyway, it could not be easily done with delay(), as Arduino supports only one level of interrupts and delay depends on interrupts enabled. (which can also be cheated away, but it should not be).
The right thing is use interrupt for fast detection of key pressed and manage other parts in loop(), see https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay how to wait in main, while doing other work.
Also using lcd and Serial inside interrupt can bring a lot of problems, especially if you are using it also in loop() (as the key can be pressed anytime and interrupt can well -interrupt- such commands in the loop and then make your output all wrong and possibly crash your program on the way too.)

Read http://gammon.com.au/interrupts if you want to know more about interrupts and why your idea is not the best possible way.
Question: Can I hit really hard my thumb with heavy hammer?
Answer: Yes, you can, but you really should not do it. There are much better ways for using thumbs and hammers.


text:
Use ATtiny85 to perform initial config on a Cisco router using its USB console port
We have 200+ brand new Cisco routers that have USB console ports (but not the old RJ45 serial console ports). This is quite frustrating because the routers didn't ship with console cables and Cisco wants to charge $60 for their proprietary USB->RJ45 serial adapters.
When I plug the router in to a computer using a standard USB cable (mini USBb on one end and USB on the other end), it shows up as a virtual com port and allows me to configure the router if I have a VCP driver installed. More specifically it shows up as a "CP2105 Dual USB to UART Bridge Controller". Here's the full lsusb -v output for the router:
Bus 001 Device 005: ID 10c4:ea70 Cygnal Integrated Products, Inc. CP210x UART Bridge
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.00
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0        64
  idVendor           0x10c4 Cygnal Integrated Products, Inc.
  idProduct          0xea70 CP210x UART Bridge
  bcdDevice            1.01
  iManufacturer           1 Silicon Labs
  iProduct                2 CP2105 Dual USB to UART Bridge Controller
  iSerial                 5 12345678
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           55
    bNumInterfaces          2
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0x80
      (Bus Powered)
    MaxPower              100mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass       255 Vendor Specific Class
      bInterfaceSubClass      0
      bInterfaceProtocol      0
      iInterface              3 Enhanced Com Port
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0040  1x 64 bytes
        bInterval               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x01  EP 1 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0040  1x 64 bytes
        bInterval               0
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        1
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass       255 Vendor Specific Class
      bInterfaceSubClass      0
      bInterfaceProtocol      0
      iInterface              4 Standard Com Port
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x82  EP 2 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0020  1x 32 bytes
        bInterval               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x02  EP 2 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0020  1x 32 bytes
        bInterval               0
Device Status:     0x0000
  (Bus Powered)

Is it possible to have an ATtiny85 board (eg Digispark) interface with the router via its USB console port to send several commands over the link to perform a perform basic initial config?

That's not how USB works.

why not write a computer program?

@IgnacioVazquez-Abrams how is this not how the "Universal Serial Bus" works? The router presents as a USB UART interface. All the Attiny needs to do is understand the protocol. There's plenty of projects where the Attiny itself pretends to be a USB UART HOST but I can't find any where it acts as a client. If it can act as a host, surely it can act as a client.

"If it can act as a [device], surely it can act as a [host]." You grossly overestimate USB's flexibility. The relation between host and device is not symmetrical, on purpose. It makes USB devices cheaper and easier to implement at the expense of making hosts more complex.

@Juraj because then our techs will have to lug around a computer to every router ensuring it is kept charged over several months visiting 200 locations. It would be vastly easier if they could plug in an attiny which costs $50 to make 10 and which can draw its power from the USB port, it then acts as a UART client and issues some choice commands to configure the router, it turns on a green led and the tech unplugs it. Job done at a fraction of the time and cost.

@IgnacioVazquez-Abrams it's a single protocol. If it can decode uart-over-usb then it can encode uart-over-usb

I have no problem with you writing a software USB host implementation for the ATtiny85 and proving me wrong.

Aaand back to square 1

you think all strings needed for router configuration fit into Attiny memory with software the (impossible) usb host implementation?

You'd have to implement USB host. Which I haven't seen done before (but I might have missed it). First, I'd ditch the ATTiny85 idea. It's less powerful than the other Arduino's, and a lot harder to work with/debug. I'd suggest looking into the USB-host shield. The Arduino Due has USB-OTG, so that might maybe be an option. A maybe even better option could be to have an Android phone with a USB-OTG cable and some Serial Console App.

It's been a couple of decades since I was programming Cisco routers, firewalls and switches but I appreciate you pain. Like @Gerben says, you need a bigger processor, an ATtiny85 isn't going to be able to hold a lot of config and even the basic configs I used were about 4 to 6KB.
If there is anything in the configs that is different, you idea is going to hit problems.  Are the device names and passwords all the same? In which case you probably want the engineer to be able to set some configuration data in you "programmer", could they set this specialisation data using their mobile phone?
I doubt you will have any problem connecting an "Arduino" via serial (RS232) to a Cisco router. However you now have to encapsulate the serial in "USB", which I don't think will be straight forward for an "Arduino".
I can't think of an option that doesn't require power, but as an alternative to your idea what about using a Raspberry Pi to connect to the router via USB. Stick a touch screen on it and a battery pack to power it.

Can I use a ATtiny85 board (eg Digispark) as a USB CDC device?
Yes!
If I have got this right, to be able to communicate with a USB serial device you need to have USB CDC support and if you want it to fake a keyboard/mouse you need HID.
The Digispark have a CDC library https://digistump.com/wiki/digispark/tutorials/digicdc
But it has its limitations, take a lot of RAM ( ~2K) so to use a Arduino Leonard/Arduino Micro make more sens and then you could add a SD card as well so you can have your commands easily modified on a SD card.
I have the same idea, but I fetch the config from a TFTP source so my commands needed on the Digispark/Leonardo/Micro is minimal.


text:
Trouble with NRF24L01
I've been trying on and off to try and get my nrf24l01's working for some time and they never seem to work. Right now I'm just trying to turn a led on and off over the radio and it isn't working.
Here's the code for the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define button 5
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
boolean buttonState = 0;
void setup() {
  pinMode(5, INPUT_PULLUP);
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}
void loop() {

  buttonState = digitalRead(button);
  radio.write(&buttonState, sizeof(buttonState));
}

And here's the code for the receiver
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

int led = 2;
RF24 radio(7, 8); // CE, CSN
boolean buttonState = 0;
const byte address[6] = "00001";
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}
void loop() {
 radio.startListening();
  while (!radio.available());
  radio.read(&buttonState, sizeof(buttonState));
  if (buttonState == HIGH)
  {
    digitalWrite(led, HIGH);
  }
  else
  {
    digitalWrite(led, LOW);
  }
}

I have the voltage regulator which steps the 5v arduino to 3.3 to the chip so I don't think not having a capacitor (what others recommended) is a problem. I have both radio chips hooked up to arduino nanos.
For the transmitter and receiver I have CE=7,CSN=8, SCK=13, MO=11, and MI=12
I also know that my led is working and the code for my button is working. Is there a problem with my code or is there a chance that my chips are broken even if im using a voltage regulator

The capacitor is not used to regulate the voltage per say, it is used to make sure the supplied voltage is 'clean'   when the radio transmits it draws 'a lot' of current real fast, and if the regulator cannot keep up with that spike, the voltage drops.   I have found that using a capacitor with these radios clears up some issues.

Interesting. I have been having an issue with nRF24L01's as well so I tried your code (modified to work toggling the transmitter and printing the output). You are possibly getting the same issue as me (nRF24L01 continuously reading closed pipe) so I modified your code as follows:
void loop() {
 uint8_t pipeNum;
 radio.startListening();
  while (!radio.available(&pipeNum));
  radio.read(&buttonState, sizeof(buttonState));
  if (pipeNum < 2) {
    if (buttonState == HIGH)
    {
      digitalWrite(led, HIGH);
      Serial.println("ON");
    }
    else
    {
      digitalWrite(led, LOW);
      Serial.println("OFF");
    }
  }
}

and then it worked for me. PS: I normally add a "while (!Serial);" line after Serial.begin to hold off output until the monitor is established.

It is not easy to find the problem remotely. Here is what I would do:

My first problem have always been connections. I gave up using breadboards and other connectors. Use soldering instead to be sure your circuit is properly connected.
Add some Serial.println() in both codes to see what exactly is going to be sent, and what has been received.
On the sender code, add a delay(100) to the loop. That would give the module buffers a chance to process.
You can improve it more by checking for the button value you read with the old value, and only send the value if the state has changed.

Pretty sure your issue is you're not using the capacitor. I used a 10uF capacitor and it works great.

You put the capacitor on pins 1 and 2, make sure ground is on pin 1.
The capacitor is to make sure there is enough power being supplied when it needs it. Without the capacitor it causes unreliable communication.
If you have other issues this is a great summary video on using the NRF24L01+ transceivers: https://www.youtube.com/watch?v=kDTJULtFPgE

Check these things first:

Is your power supply give a constant 3.3V and a minimum of
0.5A(500mA)?
Are you on the right serial baud rate?
Is the path from the radio to the Arduino as short as possible?
Are your MISO and MOSI wires twined into each other?
Try changing your CE to pin 9 and CSN to pin 10.

If none of these things help then, please tell me what library you are using. I had a lot of issues with the RF24 library so maybe try using the NRFLite library.


text:
Need library help for Arduino USB host shield
Recently Purchased a "TOOGOO(R) T45 USB Host Shield" from Amazon. I attempted to use the "USB Host Shield Library" from Github, but It seems like it might not support this particular shield.
I would really like to learn how to use this shield to interact with my joystick but the only tutorial information I have found to help me with this is from Circuits@home and they seem to be using a specific shield in their development of the code library.
Can anyone point me to a tutorial or Github library that can help me learn to work with this setup?
I'm using an Arduino Uno and a Thrustmaster USB joystick.
Thanks in advance.
UPDATE*
I fixed the initial problem of accessing the HIDDESC report. I now have the report, but the formatting of the report is particularly hard to understand. Using the Circuits@home articles I'm a little lost on how to read the report data I was given. It does not seem to be formatted in the same way as the example. Can anyone help with interpreting my device report?

Start
  0000: 05 01 09 04 A1 01 09 01 A1 00 09 30 09 31 09 32
  0010: 09 BB 15 80 25 7F 46 FF 00 66 00 00 66 00 00 75
  0020: 08 95 04 81 02 C0 09 39 15 01 25 08 35 00 46 3B
  0030: 01 65 14 75 04 95 01 81 02 05 09 19 01 29 04 15
  0040: 00 25 01 75 01 95 04 81 02 95 08 81 01 05 08 09
  0050: 43 15 00 26 FF 00 35 00 46 FF 00 75 08 95 04 91
  0060: 82 55 00 65 00 55 00 65 00 55 00 C0
  Usage Page Gen Desktop Ctrls(01)
  Usage Game Pad
  Collection Application
  Usage Pointer
  Collection Physical
  Usage X
  Usage Y
  Usage Z
  Usage Undef
  Logical Min(80)
  Logical Max(7F)
  Physical Max(FF00)
  Unit(0000)
  Unit(0000)
  Report Size(08)
  Report Count(04)
  Input(00000010)
  End Collection
  Usage Hat Switch
  Logical Min(01)
  Logical Max(08)
  Physical Min(00)
  Physical Max(3B01)
  Unit(14)
  Report Size(04)
  Report Count(01)
  Input(00000010)
  Usage Page Button(09)
  Usage Min(01)
  Usage Max(04)
  Logical Min(00)
  Logical Max(01)
  Report Size(01)
  Report Count(04)
  Input(00000010)
  Report Count(08)
  Input(00000001)
  Usage Page LEDs(08)
  Usage Slow Blk On Time
  Logical Min(00)
  Logical Max(FF00)
  Physical Min(00)
  Physical Max(FF00)
  Report Size(08)
  Report Count(04)
  Output(10000010)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  End Collection Game Pad Pointer X Y Z Undef(00)(00)(7F)(00)
  Hat Switch(00)
  Btn0001
  (00) Btn0002
  (00) Btn0003
  (00) Btn0004
  (00)
  (00)(00)(00)(00)(00)(00)(00)(00)
  Slow Blk On Time

I think you will need to get the library for your shield.

Identify the chip on your shield, and identify the chip on the shields that are supported.  Typically these fly-by-night boards are just clones of better supported ones, but you could have anything including an inert paperweight.  Worth considering that a host shield on an Arduino is generally a bad idea to begin with; if you want to host a USB peripheral, use a processor that can do so natively - it will be both cheaper and less roundabout.  Also realize that only trivial well documented USB peripherals make sense for MCUs; for more complex things you probably want an embedded Linux system.

@code Gorilla, where would I get the library for my shield?

@ChrisStratton the chip is a max 3421EE 1637. It seems to work fine, and be designed well enough, but thanks for the input.

@B.Guisgand - The library, if it exists, will be somewhere on the internet, I know that isn't helpful but what else can I say.  I think you might have misunderstood Chris's point.  Put bluntly you well down S creek with no paddle and he was handing you an outboard motor.

@CodeGorilla lol. Yeah I figured as much. I'm trying my best with this project, but can't drop $66 just for joystick functionality, might just have to scratch that portion of the project if I can't buy a cheaper shield option. Honestly all i need is the ability to plug a cheap joystick in and get it to increase or decrease the digits on a 4 digit 7 segment display.

So use a cheap plain joystick directly wired to the Arduino.

@ChrisStratton and where would i get one, been looking everywhere.

The photos on Amazon show a clone of the circuit@home board so the same library should work. You may be running into the problem mentioned in the following page.
https://esp8266-notes.blogspot.com/2017/08/defective-arduino-usb-host-shield-boards.html


text:
How to fade out RGB strip?
I have a NodeMCU controlling an RGB strip. I have followed a guide and used this code:
#include <ESP8266WiFi.h>

#define redPin 13 //D7 - Red channel
#define grnPin 12 //D6 - Green channel
#define bluPin 14 //D5 - Blue channel
#define max(a,b) ((a)>(b)?(a):(b))

WiFiServer server(80); //Set server port

String readString; //String to hold incoming request
String hexString = "FFFFFF"; //Define initial color here (hex value), 080100 would be a calm warm tone i.e.

int state;
int r;
int g;
int b;

float R;
float G;
float B;

int x;
int V;

///// WiFi SETTINGS - Replace with your values /////////////////
const char* ssid = "xxxxxxx";
const char* password = "xxxxx";
IPAddress ip(x,x,x,x);      // set a fixed IP for the NodeMCU
IPAddress gateway(x,x,x,x);  // Your router IP
IPAddress subnet(255,255,255,0); // Subnet mask

void WiFiStart() {
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);
  //Set a fixed IP. You can comment this out and set it in your router instead.
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print("_");
  }
  Serial.println();
  Serial.println("Done");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("");
  server.begin();
}

void allOff() {
  state = 0;
  analogWrite(redPin, 0);
  analogWrite(grnPin, 0);
  analogWrite(bluPin, 0);
}

//Write requested hex color to the pins (10-bit PWM)
void setHex() {
  state = 1;
  long number = (long) strtol( &hexString[0], NULL, 16);
  r = number >> 16;
  g = number >> 8 & 0xFF;
  b = number & 0xFF;
  r = map(r, 0, 255, 0, 1023);  //added for 10-bit PWM
  g = map(g, 0, 255, 0, 1023);  //added for 10-bit PWM
  b = map(b, 0, 255, 0, 1023);  //added for 10-bit PWM
  analogWrite(redPin, (r));
  analogWrite(grnPin, (g));
  analogWrite(bluPin, (b));
}

//Compute current brightness value
void getV() {
  R = roundf(r/10.23);  //for 10bit pwm, was (r/2.55);
  G = roundf(g/10.23);  //for 10bit pwm, was (g/2.55);
  B = roundf(b/10.23);  //for 10bit pwm, was (b/2.55);
  x = max(R,G);
  V = max(x, B);
}

//For serial debugging only
void showValues() {
  Serial.print("Status on/off: ");
  Serial.println(state);
  Serial.print("RGB color: ");
  Serial.print(r);
  Serial.print(".");
  Serial.print(g);
  Serial.print(".");
  Serial.println(b);
  Serial.print("Hex color: ");
  Serial.println(hexString);
  getV();
  Serial.print("Brightness: ");
  Serial.println(V);
  Serial.println("");
}

void setup(){
  Serial.begin(9600);
  delay(1);
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);
  setHex(); //Set initial color after booting. Value defined above
  WiFi.mode(WIFI_STA);
  WiFiStart();
}

void loop() {
  //Reconnect on lost WiFi connection (superfluous - will reconnect anyway)
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  while(client.connected() && !client.available()) {
    delay(1);
  }
  //Respond on certain Homebridge HTTP requests
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100) {
          readString += c;
        }
        if (c == '\n') {
          Serial.print("Request: ");
          Serial.println(readString);
          //Send reponse
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          //On
          if(readString.indexOf("on") >0) {
            setHex();
            showValues();
          }

          //Off
          if(readString.indexOf("off") >0) {
            allOff();
            showValues();
          }

          //Set color
          if(readString.indexOf("set") >0) {
            hexString = "";
            hexString = (readString.substring(9,15));
            setHex();
            showValues();
          }

          //Status on/off
          if(readString.indexOf("status") >0) {
            client.println(state);
          }

          //Status color (hex)
          if(readString.indexOf("color") >0) {
            client.println(hexString);
          }

          //Status brightness (%)
          if(readString.indexOf("bright") >0) {
            getV();
            client.println(V);
          }
          delay(1);
          client.stop();
          readString="";
        }
      }
    }
  }
}

I have tried to fade out by putting my code below in the allOff() function, but it only fades out then comes back white. I would also be interested in fading between different colours in the setHex() function.
void allOff() {
  state = 0;
  for (int i=r; i <= 1023; i--){
  analogWrite(redPin, i);
  analogWrite(grnPin, i);
  analogWrite(bluPin, i);
  }
}

I would appreciate it if anyone could give me the right way to do this. Thank you.

for (int i=r; i <= 1023; i--){
    analogWrite(redPin, i);
    analogWrite(grnPin, i);
    analogWrite(bluPin, i);
    }

analogWrite expects a range of 0 to 255, not 0 to 1023.
In any case, why are you starting with the r value and decreasing that? What about b and g?
And why not stop at zero? Your code will reach zero, and then keep going down to -1, -2 etc. I think you mean i >= 0 not i <= 1023.
Let's assume that the previously set values of r, g and b are what you want to fade. Make a loop that decreases them at the same rate:
for (float fade = 1.0; fade >= 0.0; fade -= 0.01)  // 100 steps
    {
    analogWrite(redPin, (float) r * fade);
    analogWrite(grnPin, (float) g * fade);
    analogWrite(bluPin, (float) b * fade);
    delay (10);  // short delay so you notice it
    }

So how could I apply this code to fade between colours in my setHex function?

Well, fading to black is a special case of fading from one colour to another. To do it in (say) 100 steps you need to work out a "delta" - that is the difference, for each of r/g/b from the initial colour to the new one. So for example if the old red value was 10 and the new red value is 50, then the delta is 40 (50 - 10). So over your 100 steps you need to change the red value by 40 / 100. Using floating point arithmetic lets you handle numbers which aren't integers (in this case 40 / 100 would be 0.4). Example code:
  const float STEPS = 100;

  // save old values of r/g/b
  byte oldR = r;
  byte oldG = g;
  byte oldB = b;

  // calculate new values
  long number = (long) strtol( &hexString[0], NULL, 16);
  r = number >> 16;
  g = number >> 8 & 0xFF;
  b = number & 0xFF;

  // work out deltas
  float deltaR = (r - oldR) / STEPS;
  float deltaG = (g - oldG) / STEPS;
  float deltaB = (b - oldB) / STEPS;

  // fade from old to new
  for (float f = 0; f < STEPS; f++)
    {
    analogWrite(redPin, oldR + (deltaR * f));
    analogWrite(grnPin, oldG + (deltaG * f));
    analogWrite(bluPin, oldB + (deltaB * f));
    delay (10);
    } // end of for

Thank you this is exactly what I was looking for, I forgot about the b and g values when I was trying to just test how I could get one channel to fade then forgot. Thanks :)

How could I do the same with fading between colours in the setHex() function?

Will the float values get truncated to byte for the analogWrite? If so, then just decrement from 255 by 2 or 3, stop when get down to non-detectable level.

Yes, there will be truncation, but this method smoothly dims all three colours at the same rate (eg. R/G/B will at some point all be 50% of what they started). They don't necessarily start at 255, since he wants to dim whatever-colour-it-was he started with. If you just subtract (say) 2, and he starts with R=255,G=100,B=10 then blue will very quickly become zero and the hue will change.

So how could I apply this code to fade between colours in my setHex function(see my code).

See amended answer.

Thank you I tried doing something like this but it didn’t exactly work. Thank you for taking the time to explain it.


text:
Arduino-compatible micro-controller with both I2C and CAN
I am looking for a controller that works with Arduino (i.e. there is official or third-party support for the controller in the Arduino IDE and core libs) and has both built-in CAN and I2C buses. I was looking at the ATMega automotive series (16M1, 32M1, 64M1, 32C1, 64C1) but it does not mention I2C/TWI in the datasheet at all.
(I know I can bitbang I2C, I know there is MCP2515 for CAN over SPI.)
Thanks!
EDIT: The application in mind is a bridge between a few I2C sensors and CAN, no complex logic. High performance is not necessary, plus it will drive costs upwards.

the ESP32 comes to mind. you can disable wifi/bt to save power and make it more like a mega

Thanks, @dandavis, ESP32 is too much :) I added a note on looking for rather low-performance chips.

Is i2c to CAN conversion possible on microcontroller which has both CAN and I2C.(TM4C123GXL)...

Many options come to mind:

Bluepill board
Literally any board with I2C and CAN buses from the STM32 series, as searchable on their website (https://my.st.com/content/my_st_com/en/products/microcontrollers.html)
ESP32

A Bluebill board is programmable with mbed, STM32HAL (CubeMX) and Arduino, all of which have either CAN libraries for the CAN peripheral or have it even built-in in the OS (mbedos).
The Bluepill board is extremely low cost ($1.81 with free shipping from aliexpress) and features an STM32F103C8 microcontroller with 128kB Flash and 20kB RAM. Its peripherals include two I2C and one CAN bus.

Infos & Datasheet: http://www.st.com/en/microcontrollers/stm32f103c8.html, http://wiki.stm32duino.com/index.php?title=Blue_Pill
For flashing and debugging the chip you should have one cheap ST-Linkv2 clone (~3$ from china).
For programming environments you can use:

Arduino IDE (STM32Duino Arduino Core for STM32F1/F3/F4 chips: http://wiki.stm32duino.com/index.php?title=Boards_Manager_package)
PlatformIO, more general purpose and more powerful (https://platformio.org:443/boards?count=15&filter%5Bmcu%5D=STM32F103C&page=1&sorting%5Bname%5D=asc)

As frameworks you can use:

Arduino (see above)
ARM mbedos (builds upon STM32HAL, natively supported by PlatformIO)
STM32HAL (e.g. with project files for an IDE generated by STM32CubeMX)

Documentation references:

https://os.mbed.com/docs/v5.8/reference/can.html
https://www.st.com/resource/en/user_manual/dm00154093.pdf (Chapter 8)
https://github.com/Locoduino/Commanders

8 Bit microcontrollers from STM8AF series have a few micros with 1 I2C and 1 CAN bus: See http://www.st.com/en/microcontrollers/stm8af-series.html?querycriteria=productId=SS1583

Ready buyable evaluation board: http://www.st.com/en/evaluation-tools/stm8a-discovery.html (you want the STM8AF5288 one)
The toolchain changes then, of course. See https://my.st.com/content/my_st_com/en/extended-query.html?querycriteria=productId=LN1759$$associatedTo=SS1584

Good answer. Anything 8bit, though?

@eudoxos sure, updated.


text:
Why do you need to shift bits when reading from an analog sensor?
I was playing around with some analog grove sensors and looking at examples (https://github.com/DexterInd/GrovePi/blob/master/Software/Go/grovepi/grovepi.go - this specific example is in go and for raspberry pi, but it's the same on arduino) I realised that you need to "(int(val[1]) << 8) | int(val[2])" before getting the result.
Why is that so? Why do the second 8 bits need to be left shifted by 8 and why is there then an OR with the third group of bits?

... Because you read one byte at a time.

Can you be more specific? When Read() is called, my array of bytes is filled right away, why do I need this operation afterwards?

Because now you need a number. 123 = 100 + 20 + 3

Alright, but why are we not using the first 4 bytes?

This seems to be a good documentation of the protocol; https://www.dexterindustries.com/GrovePi/programming/grovepi-protocol-adding-custom-sensors/

with color sensor nothing is skiped. it is sensor device specific. if the first 4 bytes from the device are not useful they are skipped. ask an arduino question.

It's about reconstructing the bytes of an int into the int itself. If you Google be read about "big endian", "little endian" and "network byte order" it may help you to understand what's going on.

what sensor it is? "analog"? it is i2c protocol in the link. is it an ADC sensor or why do you call it "analog".

You read bytes in the order:

Most significant byte   (let's call this msb)
Least significant byte  (let's call this lsb)

The formula to get to real value is msb * 256 + lsb
256 because this is the value of the maximum value of one byte, + 1. which is bits (2 ^ 8 = 256).
However, a CPU is normally faster in bit operations than in arithmetic operations.
Assume msb is 10101010
and lsb is    11001100

Now below is the table with the calculation order
sensor value             msb         lsb
00000000 00000000        10101010    11001100
00000000 10101010                                sensor value = msb
10101010 00000000                                msb << 8, or msb * 256
10101010 11001100                                (msb << 8) + lsb, or (msb * 256) + lsb

Actually I would expect a cast to an unsigned byte type (8 bits). However, if the values msb or lsb would be floating points/doubles, than the remainder will be removed, leaving an integer (whole) number.

Great, thanks! But why is this only for the analog read? It doesn't seem like they do it for the digital one

I don't know ... it depends on the order in which the bytes are received.

I still think you do not know what you do. You write about analog, but there is nothing analog in that sensor's interface.

@Juraj Thank you for your contribution, however I believe this community was created for people who do not know what they're doing. If I did I would have written a blog post instead of asking a question.

but I could explain if you would disclose the type of the sensor

"why...only for the analog read?" It is due to the design of the device's interface, regardless of what kind of data is being passed. An 8-bit MCU can only pass 1 byte at a time so any quantity larger than that must be transmitted to it byte-by-byte and reassembled by it once it has been received. Shifting is part of the reassembly - it puts each byte back in into its proper place within the larger (16-bits / 2 bytes in your case) number.


text:
Uno R3 connected via Ethernet shield becomes unreachable after a few minutes
I'm setting up an Elegoo Uno R3 with a Seeed 5200 ethernet shield to monitor water flow and temperature. It needs to run unattended for weeks at time (being called several times a day by a remote script).
I'm normally able to send and receive UDP packets for a few minutes when I've just reset/power-cycled the Arduino. After that, it stops responding to UDP messages. By adding some serial output I can see that it hangs unpredictably at different parts of loop(). Sometimes it seems that physically shifting the device will get it to wake up; or it will wake up on its own after a minute or two. Most of the time it works until it quits, then doesn't work until I reset it.
It does respond to ping while it's otherwise unresponsive.
Is there anything wrong with my code? This is my first Arduino project. Otherwise could it be a hardware problem? If I buy another, I'll buy a genuine Arduino. Is Seeed a reliable source for the ethernet shield?
(By the way--I think it's safe to disregard the PACKETLEN thing, which is a leftover artifact. In the end it's unnecessary to read the incoming message anyway, so the packetBuffer array is superfluous but doesn't seem to change anything one way or another.)
Thanks in advance. Best wishes,
Dan
#include <SPI.h>
#include <EthernetV2_0.h>

#define PACKETLEN 48

//Flow and temp globals
byte sensorInterrupt = 0;  // 0 = digital pin 2
byte flowPin       = 2;
byte tempPin = 0;

float calibrationFactor = 45; // we're going to measure for 10s intervals
float minFlow = 270;          // minimum 6 L/min, measured for 10 s
volatile byte pulseCount;
unsigned long startTime, timeDelta;

int tempReading;
float tempVoltage;
float temperature;

//Communication globals
IPAddress ip(xxx, xxx, xxx, xxx);
byte mac[] = {
  0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx
};
EthernetUDP Udp;

unsigned int localPort = xxxx;
char packetBuffer[PACKETLEN+1];  //buffer to hold incoming packet,

int packetSize;
byte flowOk, tempOk;
IPAddress remoteIP;
unsigned int remotePort;

void pulseCounter()
{
  pulseCount++;
}

void setup()
{

  //Serial.begin(9600);
  Ethernet.begin(mac,ip);
  Udp.begin(localPort);

  pinMode(flowPin, INPUT);
  digitalWrite(flowPin, HIGH);

  // attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
}

void loop()
{

    delay(2000);

    if(packetSize = Udp.parsePacket())
    {
        remoteIP = Udp.remoteIP();
        remotePort = Udp.remotePort();

        //Measure the flow for 10 seconds
        flowOk = 0;
        pulseCount = 0;
        startTime = millis();
        attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
        while((timeDelta = millis() - startTime) <= 10000) ;
        detachInterrupt(sensorInterrupt);
        if (pulseCount >= minFlow)
            flowOk = 1;

        //Check the temperature
        tempOk = 0;
        tempReading = analogRead(tempPin);
        tempVoltage = tempReading * 5.0 / 1024.0;
        temperature = (tempVoltage - 0.5) * 100;
        if (temperature < 35.0)
            tempOk = 1;

        Udp.beginPacket(remoteIP, remotePort);
        if (flowOk && tempOk)
            Udp.write("Ok");
        else
            Udp.write("Not ok");
        Udp.endPacket();
    }

}

If its doing it at random places its most likely to be a memory issue, maybe a buffer overrun?

Thanks for the comment. I assume you're right about a memory issue in one of the libraries. I will post the fix below.

I don't know where my compiler was finding the UDP code in the above sketch, because it's not in EthernetV2_0.h. The problem was fixed by adding the following lines, from the example sketch UDPSendReceiveString written by Michael Margolis and included with the Ethernet_Shield_W5200 library:
#include <EthernetUdpV2_0.h>

#define SDCARD_CS 4

void setup():
    //...//
    pinMode(SDCARD_CS, OUTPUT);
    digitalWrite(SDCARD_CS, HIGH);


text:
NodeMCU successfully uploaded sketch but it does not work from Arduino IDE
NodeMCU successfully compiled and uploaded a simple blink sketch on board, no errors at all, but the LED stays on constantly and does not blink. Also I have checked the power is enough. I have checked this with all pins but the red LED only stays on and doesn't blink. I have no idea what could have gone wrong. And how to fix this?

Fixed it....
turns out that in the tools, the board was selected to be NodeMCU 0.9
when it should actually have been NodeMCU 1.0
so i just changed it to NodeMCU 1.0 and it worked!

accept your answer to finalize this Q&A

@Juraj isn't there a 24h waiting period as on other sites?