text:
arduino and esp-1 stop workign after 1 day running
i'm trying to create a system that arduino and esp-1 send an GET request each 2 secs to a server and depend on server reply turns a LED on or off . system works good for 6-7 hours but stops after one day . actually i  checked server logs after one day and i realized no request is sending to serve .
my hardware :
Arduino Uno
ESP-1
LED or Relay
and my arduino codes : ( in know my host is not working now . i turned it off )
#include <ArduinoJson.h>
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <SoftwareSerial.h>

SoftwareSerial Serial1(10,11);

char ssid[] = "AZaz";            // your network SSID (name)
char pass[] = "Az8833394";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
int Relay = 13;

char server[] = "azimi.ir";
unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 1000L; // delay between updates, in milliseconds
WiFiEspClient client;

void setup() {
  // put your setup code here, to run once:

  pinMode(Relay, OUTPUT);
  Serial.begin(115200);
  Serial1.begin(9600);
  WiFi.init(&Serial1);
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println(F("WiFi shield not present"));
    // don't continue
    while (true);
  }

  while ( status != WL_CONNECTED) {
    Serial.print(F("Attempting to connect to WPA SSID: "));
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println(F("You're connected to the network"));
//  printWifiStatus();
}

void loop() {
  while (client.available()) {
  char c = client.read();
  char endOfHeaders[] = "\r\n\r\n";
  if (!client.find(endOfHeaders)) {
    Serial.println(F("Invalid response"));
    return;
  }
  const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 80;
  DynamicJsonDocument doc(capacity);
  DeserializationError error = deserializeJson(doc, client);
  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return;
  }
      int count = doc["counts"];
      if(count == 1){
        int relay = doc["message"];
        int cmd = doc["val"];
        digitalWrite(relay , cmd);
      }

  }
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();

  }
}

void httpRequest()
{

  Serial.println();

  // close any connection before send a new request
  // this will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection
  if (client.connect(server, 80)) {
    client.println(F("GET /check/ HTTP/1.1"));
    client.println(F("Host: azimi.ir"));
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection
    Serial.println(F("Connection failed"));
  }
}

now i have some questions :
1- why system stops working after more hours ? what is the problem ? my codes or my hardware ?
2- if problem is my hardware , what kind of wifi module or arduino you think will work ?
3- i want this project to make someone else's home . it will be a long term project so i want my system works for one or two years at least . is arduino suitable for this kind of projects ?! if its not , what hardware is ?

use StaticJsonDocument. DynamicJsonDocument fragments the small memory of Uno until ot is not able to allocate new space. https://arduinojson.org/v6/api/dynamicjsondocument/

I tried it before , no thing changed !

your way of reading the response is not very reliable. you have while (client.available()) but the code in the while block expects to be run once. you should stop() the client after reading the response, not before sending a new request.

i see , but iam trying to do everything like this tutorial :
https://www.arduino.cc/en/Tutorial/WiFiWebClientRepeating
like this :
https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClientRepeating/WebClientRepeating.ino


text:
Displaying multiple effects in Fast LED
I want to implement three effects which display every 5 seconds. I know that using delay() is not a good method so I want to use milis(). Duration times of the effects are different from each other. How can I assure "non-freezing" or displaying 2 or 3 effects at the same time? Should I measure the time of display of every effect and on its base adjust intervals or is there another solution? What do you think?
EDIT:
Here is my code:
void loop() {
   unsigned long currentMillis = millis();

   if(currentMillis - previousMillis >= interval) {
     previousMillis = currentMillis;
     i++;

    switch (i){
      case 1:
        meteorRain(0xff,0xff,0xff,10, 64, true, 30); // efekt spadającej gwiazdy
        Serial.print("meteorrain: ");
        Serial.print(previousMillis);
        Serial.print("\n");
        break;

      case 2:
         colorWipe(0x90,0x90,0x90, 50);
         colorWipe(0x00,0x00,0x00, 50);
         Serial.print("colorwipe: ");
        Serial.print(previousMillis);
        Serial.print("\n");
         break;

      case 3:
         MyEffect();
         Serial.print("My effect: ");
        Serial.print(previousMillis);
        Serial.print("\n");
         break;
    }
    if (i>3) i=0;
    }
}

I've ommited the code of effects (it doesn't matter, I think).

show us what you have tried so far, do you have some code working for one of the effect (or the 3 of them ?) so we can know what to expect ? also, if your 3 effects all trigger every 5 seconds, can't we call that one big effect with 3 different actions that triggers every 5 seconds ?

Are these effects executed on different LED strips at the same time or sequentially on the same LED strip?

Sequentially on the same LED strip.

So you don't want to have multiple effects at the same time, as you wrote in your question? Or do you divide the LED strip into different parts, which should display the corresponding effect simultaneously? I don't understand, what the end result should look like

If you intend to show every effect sequentially for a time interval (by looking on the code one can assume that) then, there is nothing wrong with the code, except the execution of an effect would last longer than the time interval. If that's not your intention, I do not understand your question for the same reasons @chrisl has mentioned.

I'd take a look at Mark Kriegsmans FastLED example "DemoReel100". This example shows how to delegate to multiple functions.
First, I'll explain that example a bit: You set up an array of function pointers plus a variable for the current index.
typedef void (*SimplePatternList[])();
SimplePatternList gPatterns = { rainbow, rainbowWithGlitter, confetti, sinelon, juggle, bpm };
uint8_t gCurrentPatternNumber = 0;

All the functions (rainbow, juggle, etc) just need to work on your leds[] array that you gave to FastLED.addLeds() in your setup() -- I assume that your functions already fulfill that requirement. But: All functions must have the same argument list (in this case: they must be defined like void rainbow() { leds[x] = CHSV(a,b,c); }), so you might need to wrap them in another function.
Then, in your loop, you call your effect functions like this while calling nextPattern() every 10 seconds:
void loop()
{
  // Call the current pattern function once, updating the 'leds' array
  gPatterns[gCurrentPatternNumber]();

  // send the 'leds' array out to the actual LED strip
  FastLED.show();
  // insert a delay to keep the framerate modest
  FastLED.delay(1000/FRAMES_PER_SECOND);

  // do some periodic updates
  EVERY_N_SECONDS( 10 ) { nextPattern(); } // change patterns periodically
}

#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
void nextPattern()
{
  gCurrentPatternNumber = (gCurrentPatternNumber + 1) % ARRAY_SIZE( gPatterns);
}

EVERY_N_SECONDS is a macro defined in the FastLED library; it basically does what you did with currentMillis, previousMillis and interval (There's also EVERY_N_MILLISECONDS and some other related macros).
That's the example so far, now we need to work with differing "effect switch times".
The easiest method in code would be to find the greatest common factor of all switch times -- let's say you want the rainbow() effect to last for 10 seconds, the juggle() effect for 15 and the bpm() effect for 5 seconds. All those switch times are a multiple of 5, so we put that as the switch delay: EVERY_N_SECONDS(5). Now, to get higher runtimes, we just put those functions multiple times into the array:
SimplePatternList gPatterns = { rainbow, rainbow, juggle, juggle, juggle, bpm };

There's another way, which gives you the option of setting the effect durations directly. First, we need an array of durations of the same length than our effect function array and a variable to remember where we are in the durations:
SimplePatternList gPatterns = { rainbow, juggle, bpm };
int[] gPatternDurations = { 10, 13, 73 };
int effectDurationLeft = gPatternDurations[0];

Then, we reduce the "effect switch resolution" down to 1 second and put a bit of logic around the nextPattern() call:
  EVERY_N_SECONDS( 1 ) {
    if( effectDurationLeft == 0 ) {
      nextPattern();
      effectDurationLeft = gPatternDurations[gCurrentPatternNumber];
    } else {
      effectDurationLeft -= 1;
    }
  }

Now you could set your pattern durations by editing the gPatternDurations array.
Please be aware that I did not test the code above. Syntax Errors may occur :)

source: Stack Exchange

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

sort: votes


text:
What will happen if I supply greater than 1.1V to analogue inputs if analogReference set to INTERNAL?
I am reading a 50Hz AC voltage using the analogue inputs.
If I set the analogReference() to INTERNAL, meaning 1.1V on the Arduino Uno, what will happen if a voltage greater than 1.1V is supplied to the pin? Will the board be damaged? If not, what value will the ADC give?

You will read 1023.
The limit of the voltage is not the reference voltage but the chip supply voltage - so 5v on a 5v board.

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


text:
Sending float values from Python to Arduino using Serial communication
I need to send an array of floating-point numbers from python to Arduino Mega. For that, I read many sources [this this this this this] this] and many more links for the same I referred. But unable to solve the problem.
I tried to send the angles to Arduino through python and return these values to python to print.
Below is the Python code in which I try to send the array named angle and tries to print the values received from Arduino.
import cv2
import numpy as np
import serial
import struct
import time

ser = serial.Serial('COM3', 9600, timeout = 1)
time.sleep(2)
if(ser.isOpen() == False):
    ser.open()
print('com3 is open', ser.isOpen())

angle = [120.2,154.2,14.25]
ser.write(struct.pack('>fff', 10.5,11.9,48.2)) # B for interger and f for float
#ser.write(struct.pack('>f', angle)) # B for interger and f for float

time.sleep(2)
ser.flush()

data = ser.readline()
data = str(data.decode("utf"))
print(data)

ser.close()

Below is the Arduino code:
float f1; float f2; float f3;

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);

Serial.println("Arduino is in parseFloat!");
}

void loop() {

  if (Serial.available() > 0)
  {
    d1 = Serial.parseFloat(); d2 = Serial.parseFloat(); d3 = Serial.parseFloat();

    ad = d1 +2.5;
    Serial.println(ad)
  }
delay(2000);
}

The error I got is:
I got no error or warnings but there is no output also for the print commands as shown in below Figure.

I need help to send the values to Arduino using python.

You seem to be sending binary instead of text.

You aren't giving your Arduino time to reboot after opening the serial port and before sending it any data...

There are two things going on here.
First of all, if you look up the readline() method in Python that is referenced in the PySerial manual, you'll see the following:
readline(size=- 1, /)

Read and return one line from the stream. If size is specified, at most size bytes will be read.
The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.

In your program, you are actually sending more than one line back to serial port from the Arduino. The first line is the ASCII-encoded "Arduino is in ParseFloat!". The second one is the test float calculation. If you don't account for the fact you are expecting multiple "lines" from the serial port,  you wouldn't see the test calculation, because you are not actually reading it. For encoded data, it states that the line ends at the '\n' char/digit (10).
Try it out change the "println" to "print" in your Arduino program and add another message either in the setup or the loop. Run your Python program. What do you see? Now change the "print" back to println". Run your Python program again. What do you see now?
Secondly, Edgar Bonet points out the second issue. The write() method in the PySerial API requires data to be a bytes array, but it's the way you are encoding it. It seems that the Arduino Serial class expects a ASCII-encoded byte-array, rather than a float byte-array (the floats encoded as a single-precision floating point number), which is what you are sending.
If you change your code to something like this (for example):
angle = [120.2,154.2,14.25]
ser.write(str(angle).encode('utf-8'))

you should be able to see your test calculation come back, granted that you read what I wrote in the first part of this answer.

By removing println, I successfully send and receive values.

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


text:
Can I make multiple loop() functions with Arduino Uno?
I have a problem. I want to make a car with a motor, front lights and rear lights. I want to run them at the same time but in different loops.
This is my code.
const int red1 = 10;
const int red2 = 11;
const int blue1 = 12;
const int blue2 = 13;
const int front1 = 3;
const int front2 = 4;
const int back1 = 5;
const int back2 = 6;
const int enablePWMPin = 9;
const int controlPinA = 8;
const int controlPinB = 7;
int buzzer = A0;

void setup() {
  pinMode(red1, OUTPUT);
  pinMode(red2, OUTPUT);
  pinMode(blue1, OUTPUT);
  pinMode(blue2, OUTPUT);
  pinMode(front1, OUTPUT);
  pinMode(front2, OUTPUT);
  pinMode(back1, OUTPUT);
  pinMode(back2, OUTPUT);
  pinMode(enablePWMPin, OUTPUT);
  pinMode(controlPinA, OUTPUT);
  pinMode(controlPinB, OUTPUT);

  digitalWrite(enablePWMPin, LOW);
  digitalWrite(front1, LOW);
  digitalWrite(front2, LOW);
  digitalWrite(back1, LOW);
  digitalWrite(back2, LOW);
  digitalWrite(red1, LOW);
  digitalWrite(red2, LOW);
  digitalWrite(blue1, LOW);
  digitalWrite(blue2, LOW);
  noTone(buzzer);
}

void loop() {
  digitalWrite(enablePWMPin, HIGH);
  digitalWrite(controlPinA, HIGH);
  digitalWrite(controlPinB, LOW);
  delay(3000);
  digitalWrite(controlPinA, LOW);
  digitalWrite(controlPinB, HIGH);
  delay(3000);
}

void loop() {
  digitalWrite(red1, HIGH);
  digitalWrite(red2, HIGH);
  digitalWrite(blue1, LOW);
  digitalWrite(blue2, LOW);
  delay(250);
  digitalWrite(red1, LOW);
  digitalWrite(red2, LOW);
  digitalWrite(blue1, HIGH);
  digitalWrite(blue2, HIGH);
  delay(250);
}

void loop() {
  int directionA = digitalRead(controlPinA);
  int directionB = digitalRead(controlPinB);
  if (directionA == HIGH && directionB == LOW) {
    digitalWrite(front1, HIGH);
    digitalWrite(front2, HIGH);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  } else if (directionA == LOW && directionB == HIGH) {
    digitalWrite(back1, HIGH);
    digitalWrite(back2, HIGH);
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
  } else {
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  }
}

I'm using an Arduino Uno. Can I start all the loop() functions at the same time?

Just trying to compile it should provide you with an answer...

Not with an Uno, but it is possible with a Due

As the others have stated, no you can't have multiple loop functions. What you need to do is modify your approach so that each thing you are trying to do can be done sequentially without blocking (ie: remove the delay function usage). Expanding on some suggestions by JRobert, Here is how I would make these functions "run at the same time":
void loop() {

    lights1();
    lights2();
    motor();

}

void lights1() {

  static unsigned long lastTime = 0;
  const long interval = 3000;
  static bool state = 0;

  unsigned long now = millis();

  if ( now - lastTime > interval && state == 0) {
    state = 1;
    lastTime = now;
    digitalWrite(enablePWMPin, HIGH);
    digitalWrite(controlPinA, HIGH);
    digitalWrite(controlPinB, LOW);
  }

  if ( now - lastTime > interval && state == 1) {
    state = 0;
    lastTime = now;
    digitalWrite(controlPinA, LOW);
    digitalWrite(controlPinB, HIGH);
  }
}

void lights2() {

  static unsigned long lastTime = 0;
  const long interval = 250;
  static bool state = 0;

  unsigned long now = millis();

  if ( now - lastTime > interval && state == 0) {
    state = 1;
    lastTime = now;
    digitalWrite(red1, HIGH);
    digitalWrite(red2, HIGH);
    digitalWrite(blue1, LOW);
    digitalWrite(blue2, LOW);
  }

  if ( now - lastTime > interval && state == 1) {
    state = 0;
    lastTime = now;
    digitalWrite(red1, LOW);
    digitalWrite(red2, LOW);
    digitalWrite(blue1, HIGH);
    digitalWrite(blue2, HIGH);
  }

}

void motor() {
  int directionA = digitalRead(controlPinA);
  int directionB = digitalRead(controlPinB);
  if (directionA == HIGH && directionB == LOW) {
    digitalWrite(front1, HIGH);
    digitalWrite(front2, HIGH);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  } else if (directionA == LOW && directionB == HIGH) {
    digitalWrite(back1, HIGH);
    digitalWrite(back2, HIGH);
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
  } else {
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  }
}

This approach will simulate running all three functions at the same time. Each function runs one at a time. But, since the delay has been removed from the light1/2 functions, they will end quickly during the 'waiting' period instead of pausing execution. This will allow the motor(s) to run and lights to blink all at the same time.

No you cannot.
Not only is it no proper C/C++ to have multiple identical functions, i.e. it will not compile (as jfpoilpret's comment suggests). It is also not in accordance with the idea of programm flow in the Arduino world - the sketches - where you have two methods on the highest (user accessible) level: void setup() and void loop(). setup is run exactly once at the beginning of your program. Following that loop is looped (hence the name) forever. You need to properly restructure your code to implement your intended program flow, i.e. call your own functions from loop. Read more on www.arduino.cc with tutorials worth studying.

To use multiple loops at the same time you need a Arduino Due Board.
It is the only board compatible with library #include <Scheduler.h>
See Examples > Scheduler Library > Multiple Blinks
// Include Scheduler since we want to manage multiple tasks.
#include <Scheduler.h>

int led1 = 13;
int led2 = 12;
int led3 = 11;

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

  // Setup the 3 pins as OUTPUT
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);

  // Add "loop2" and "loop3" to scheduling.
  // "loop" is always started by default.
  Scheduler.startLoop(loop2);
  Scheduler.startLoop(loop3);
}

// Task no.1: blink LED with 1 second delay.
void loop() {
  digitalWrite(led1, HIGH);

  // IMPORTANT:
  // When multiple tasks are running 'delay' passes control to
  // other tasks while waiting and guarantees they get executed.
  delay(1000);

  digitalWrite(led1, LOW);
  delay(1000);
}

// Task no.2: blink LED with 0.1 second delay.
void loop2() {
  digitalWrite(led2, HIGH);
  delay(100);
  digitalWrite(led2, LOW);
  delay(100);
}

// Task no.3: accept commands from Serial port
// '0' turns off LED
// '1' turns on LED
void loop3() {
  if (Serial.available()) {
    char c = Serial.read();
    if (c=='0') {
      digitalWrite(led3, LOW);
      Serial.println("Led turned off!");
    }
    if (c=='1') {
      digitalWrite(led3, HIGH);
      Serial.println("Led turned on!");
    }
  }

  // IMPORTANT:
  // We must call 'yield' at a regular basis to pass
  // control to other tasks.
  yield();
}

void is not a verb.

@gre_gor: Using that word as a verb may void its warranty ;-)

I want to run them at the same time but in a different loop.

First of all, you can only do one thing at a time. So that's out.
Secondly, to run multiple loops sequentially (one at a time), it is fairly easy:
void loop1(void) {...}
void loop2(void) {...}
...

void loop(void) {
  loop1(); //run loop1
  loop2(); //run loop2
  ...
  loopn(); //run loopn
}

Whether it works will depend on how you have coded those loops.

What are you trying to accomplish? Are these loops meant to run simultaneously (not possible)? Or one after the other? You could get pretty close to "simultaneous" if "real fast" is good enough. You'd need to

Give each loop function a new, unique name;
Split each of the first two loops at the delay()s for a total of 5 functions;
Use a timer library such as SimpleTimer to run each of the functions at the rate you need them to.
and from the only loop() function, keep calling SimpleTimer's '.run()' function to keep the whole thing going.

You could improve the speed of the individual functions by replacing the digitalRead() and digitalWrite() calls with direct reads and writes to port and bit you want read or set.

authors: Ильфат Газимзянов

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


text:
Why does my Arduino/Ledstrip combi not work?

simulate this circuit – Schematic created using CircuitLab
I am using an Arduino Uno, and WS2813 led strip (60 leds).
It seems like a default schematics (except I did use a 470 uF (electrolytical) cap instead of 1000 uF electrolytical cap.
(I accidantally marked the VCC pin of U1 VSS).
I don't get any LED of the LED strip glowing.
The program I used is:
#include <FastLED.h>

#define NUM_LEDS 60
#define DATA_PIN 7

CRGB leds[NUM_LEDS];
bool led = false;

void setup() {
    //FastLED.addLeds<WS2813, DATA_PIN>(leds, NUM_LEDS);
    FastLED.addLeds<WS2813, DATA_PIN>(leds, NUM_LEDS);
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
    for (int i = 0; i < NUM_LEDS; i++)
    {
      leds[i] = CRGB::Red;
    }
    FastLED.show();
    led = !led;
    digitalWrite(LED_BUILTIN, led ? HIGH : LOW);
    delay(1000);
}

What I tried was:

Checking different data pins on the Arduino
Checking different wires
Checking that over D7 and after the resistor there is indeed 330 Ohm resistance (it was 345 Ohm)
Tried different data pins (and adapted the scene to use a different data pin)
Checking that LED D1 is on (5V is flowing)
Checking that at the end of the WS2813 there the VCC and GND 5V difference (it is about 5.1 V)
Checking that there is indeed 5 V difference between the adapter + and - (was 5.2 V, unloaded).
Tried with WS2813's BI grounded and unconnected
Tried without the 330 ohm resistor.
Checked with a the same circuit but WS2812B (and adapting the code to use WS2812B)
Used different timings for the builtin LED to see that the sketch is actually uploaded.
Tried with , RGB) added in line: FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
With a logic analyzer I see that every second there is a short burst of data (not analayzed exactly what, I assume FastLed is reliable).

All no difference.
However, what I did see, is the logic analyzer data AFTER the 330 ohm resistor mostly removes the data, while the data before the resistor is ok. However, when remove the resistance, still the LED strip does not light up.
Channel 0 is before the resistor, channel 1 after:

What did I do wrong?

did you connect to the correct end of the LED strip?

@jsotola YES ... I should have asked earlier :-); If you put it as answer, I upvote/accept it.

It is important to connect the Arduino digital pin to the correct end of the LED strip.
LED strips have a unidirectional data line.
The power and ground connections can be made from either end, but the data IN is at one end and data OUT is at the other end.
That arrangement is for the purpose of daisychaining the LED strips.
The LEDs themselves also have data IN and data OUT, and are also daisychained with their neighbouring LEDs.
The LEDs are serially connected to each other through the data line, and are connected in parallel to the power and ground lines.

Yes, I noticed there is a direction (which is logical). Guess when I tried it before it worked instantly, probably because I randomly selected at that time the right side, and now the wrong one.


text:
Is it possible to directly set the registers that control the ADC clock on the Arduino?
Is it possible to directly set the registers that control the ADC in an Arduino Yun (micro-controller side is essentially a Arduino Leonardo) from a sketch or is there a specific file somewhere you must edit?
I am working on a project that collects a signal digitizes it and sends it through a digital filter. I looked up the Datasheet for the micro-controller on the Yun and wrote the code setting the registers associated with the ADC portion of the micro controller. The code setting the registers was something like REGNAME = 0x01;. Yet when tested several of the associated registers were unaffected. Pointers on the process to set the ADC manually without using the analogRead() function would be appreciated.
Edit:
My original code looked something like this:
void setup(){
    // register to turn on ADC
    REG1 = REG1 | 0x01;

    //register to set sample rate and set ADC to Free Running Mode
    REG2 = REG2 & 0x30;

    // register to set other settings
    REG3 = REG3 | 0xF1;
}

void loop(){
    // code to take samples from ADC
    // and send them through a digital filter here.
}

Which part of the datasheet are you having trouble with?

The problem wasnt the datasheet. when I set the registers in the code they were not set on the microcontroller when I tested it.

the sketch recognized the register names and out of the 3 or 4 registers I set only one actually was altered. I debugged it by printing the values of the registers after being set to the console. The output of the ADC was not the same as the input signal either.

The Arduino libraries do things to the hardware. The key is to avoid using them.

I realized that after the fact. We needed a micro-controller and Ethernet in our project but because of time constraints, the research time requirement and budget constraints we could not use a pic micro-controller which would have been the ideal choice. do you know where the libraries do things to the ADC hardware? info on the process to replace  the actual library file would be helpful too.

Do you call analogRead after setting the registers? analogRead does change  the ADCSRB register. So if you are setting ADC High Speed Mode (ADHSM), that will be overwritten. The clock prescaler is only set in the init function, so you should be able to overwrite this in the setup function

What is it that you're trying to achieve that the Arduino library does not allow you to do?

I had intended to avoid the analogRead() method entirely. Because I was using Arduino as a prototyping platform to design the code only and later on I will refactor the code to work with hardware that will be mass producible. Therefore I had intended to directly control the registers so that when I port over the code to the final choice of micro-controller there will not be a relatively small amount of changes to make.

I had originally set the registers in the setup function and not in the running loop function.

There are several issues here. The first is understanding the difference between || and |, && and & in C/C++. Your should then take a look at the code for analogRead() to understand how the ADC is initialed. https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_analog.c#L38. This type of modification requires a lot of detailed insight into the underlaying implementation. You may need to implement your own version of analogRead().

I think I used bitwise operators in my code and made a mistake typing extra '&'s and '|'s in my example. I just edited the example to reflect that. Ill have to double check that. I am going to check the link you listed. It looks like I will have to overload the analog read function so that it works like I want it to. after that, I'll have to  figure out how to replace that part of the library and ill be good to go. @MikaelPatel if you can post an answer with the info you just commented and a link to a tutorial on how to compile a sketch with an edited library I'll accept your answer.

Ill follow up after with a comment listing everything I found out.  Unless it would be better to post the follow up as an answer.

I can see no problem with your pseudo-code. You should probably post a
complete testable code in order to get better feedback.
That being said, here are a few suggestions:

You should completely set the ADC registers to the values that suit
your application, instead of just changing a few bits here and there.
This is because you should not care about how the Arduino core
library initializes those registers, especially if this is a
prototype for a final product that will not use Arduino core. For
example, instead of

REG1 = REG1 | 0x01;

you can write something like this:
REG1 = _BV(FOO)   // use foo mode...
     | _BV(BAR);  // ...in the bar setting

where _BV(x) is a macro from avr-libc that expands to (1<<(x)),
   and the bit names are those of the datasheet, for better readability.

You may want to run the digital filter in the ADC interrupt service
routine. If you can split your processing into a fast filter
(processing every sample) and a slow filter (running on decimated
samples), then do only the fast one in the ISR and leave the slow one
to the main loop. I say this from experience: when I tried to do
all the processing in loop() I always lost samples, which did not
happen when I moved the filter to the ISR.
But then, make sure your filter is optimized to be fast. Avoid
floating point operations in the ISR if at all possible.

I have written a program that looks very similar to what you are trying
to do: it samples an analog input at 9.6 kS/s and runs an
homodyne detection
filter in order to extract the signal power in a very narrow band around
1 kHz. The ADC is set to free running mode. In the ADC ISR, I
retrieve the sample, run it through the filter, and store the result
into volatile variables. In loop(), I read these back from time to
time. Here is how I set the ADC:
static void configure_adc()
{
    ADMUX  = _BV(REFS0)  // ref = AVCC
           | _BV(ADLAR)  // left adjust result
           | analog_in;  // input channel
    ADCSRB = 0;          // free running mode
    ADCSRA = _BV(ADEN)   // enable
           | _BV(ADSC)   // start conversion
           | _BV(ADATE)  // auto trigger enable
           | _BV(ADIF)   // clear interrupt flag
           | _BV(ADIE)   // interrupt enable
           | 7;          // prescaler = 128
}

The complete program is available here:
homodyne.ino.
It was initially intended for an Arduino Uno, but it runs unmodified on
a Leonardo clone.

Since your project is about acquiring signals I guess that the sample frequency is important for you. In fact you need to know exactly how much time passes from one sample to another. This cannot be achieved by simple reading the ADC in your loop(). The easiest implementation is to use an interrupt that occurs every n seconds (e.g. every overflow of timerX).
I'm going to write a pseudo-code for this:
void SetTimer()
{  TISREG |= 1<<Prescaler_bit   //set the prescaler
   TICNT = 0   //sdt the tarting value
   TIINT |= 1<<OVF_Interrupt_enable
   sei() //enable global interrupt
}

ISR(TIM1_OVF_vect)   //happens every [prescaler*2^bit_timer/F_CPU] seconds
{
   while( !(ADCSREG &= (1<<bit_is_ready)) ) ; //usually there is a bit that is 1 while the ADC has read the data, and 0 while it is doing the conversions

//imagine the ADC stores the 3 MSBits in the ADCHI
//and the LSBits in the  ADCLO

value_high = (ADCHI & 0b00000111);
value_low = ADCLO;

value = (value_high << 7) | value_low;

}

At high sampling rates, the best option is to set the ADC in the so called "free running mode". If you read the question carefully, you will notice that's exactly what the OP is doing.


text:
Wire multiple SW-420 Vibration sensors to a single pin
I am working on installing an alarm system using Konnected IO on a NodeMCU esp8266. I have multiple bay widows which will use 4 SW-420 vibration sensors. I would like to wire all 4 of the SW-420 vibration sensors to a single pin. When any of the 4 sensors detect vibration the pin will go to high. I attempted to simply wire the d-outs from all four together and all four sensors stoped working. I'm out of ideas on how to do this any help would be greatly appreciated. I believe sensors send out a low signal when no vibration is detected and high signal when vibration is detected. Link to sensors: https://www.amazon.com/XLX-Vibration-Normally-Sensitive-High-Efficient/dp/B07V8FJRN1/

Two ideas came to my mind, first is to connect each output to four digital pins and then do something like this:
if(digitalRead(pinOne) == HIGH || digitalRead(pinTwo) == HIGH || ...){
do something
}

Or you can use an opamp or comparator for that purpose:

simulate this circuit – Schematic created using CircuitLab
In above configuration if any of the sensors output is HIGH, op amp will drag it's output to the positive rail (~5V). otherwise output is LOW (~0 V).


text:
Using DHT11 and EMF - Lag issue
The code is working but there is a delay when the LED turns on and off (physically). Is there a more efficient way I could write this code? I assume it is the delay in reading the DHT11 causing it.
~Issue resolved

Don't have a delay?

there is one, physically, when the LED lights up and turns off.

I don't know what you mean by "physically", but there is a delay in your code. Remove it, and if you need parts of your code to run slower, use millis() to determine when they should run.

Please leave the original question intact so others can benefit from your question and its solution.

Your question is a bit unclear (A delay is defined by two points in time or one point and a duration -- you only tell us one point).
Reading your code, I can only assume that you mean that an external event on inPin is delayed in showing up on the LED on pin11. This should come up when that external event is emitted just at the beginning of your delay(1000) (and is therefore randomly delayed between 0 and 1000ms).
You could get rid of the delay in your loop using a bit of timer math around the DHT11 reading code:
#define DHT11_SAMPLE_DELAY = 1000
uint32_t last_dht11_reading_ms = 0;

void loop() {
  uint32_t current_ms = millis();

  if( current_ms - last_dht11_reading_ms > DHT11_SAMPLE_DELAY ) {

    DHT.read11(dht_apin);
    Serial.println("....your output....");

    last_dht11_reading_ms = current_ms;
  }
  // also, remove the delay(1000) in your loop()
}

You get the current time (millis() gives you the uptime since boot in milliseconds) and subtract the time of last reading. If the result is bigger than a threshold (in this case: 1000 ms), you do a new reading of the DHT11 while setting the variable containing the time of last reading to the current time. When the loop() comes around again, the threshold will not be reached, so reading the DHT11 value is skipped until millis() returns a sufficiently big number again.

@RobE If you did copy my error in the DHT.read11() call, then I can see why... if you didn't, I'd be very surprised ^^ (Fixed the errorneous call. It should be the same line as in your original code.)

Updated the code, now the temp sensor never reads. I must have done something wrong. I updated the code above in the OP.

@RobE Nice to see that your issue has been resolved, but could you please leave the question here so others can find the solution? The intended way here on Stackoverflow is to keep everything readable, so others won't have to ask the same question again. Instead of removing the question, please mark an answer as correct.


text:
Boolean Logic With Chars For Motor Input Selection
Context of the code:
I am trying to control 2 DC motors through an H-gate, this means there are 4 inputs in total:
For DC motor 1: Input 1 (VCC) and Input 2 (GND).
For DC motor 2: Input 3(VCC) and Input 2 (GND).
Summary of the code:
The global variables are motinpN which are the pins connected to the different inputs.
An array, which is where the different PWM for the motor speeds are stored.
Char x, which is the variable used for the boolean logic.
Then comes the actual loop which consists of 4 similar functions, the "input selector" function and then the statements that turn the integers stored in the inpSpeedS[] arrays into motor speeds.
The issue:
The code won't enter the first loop, i.e it won't advance past
Serial.println("X equals:");
  Serial.print(x);"
I would like to know then, what I am doing wrong in order for this not to work?
   int Speed = 0;
const int motinp1 = 2;
const int motinp2 = 3;
const int motinp3 = 4;
const int motinp4 = 5;

char  x = '0';

int inpSpeedS[4]; // An array to determine the speed of each individual input

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

void loop() {
  Serial.println("X equals:");
  Serial.print(x);

  if (Serial.available () && (x == '0')) {
    Serial.print("Which input?");
    x = Serial.read();
    Serial.println(x);
  }
  if (Serial.available () && (x == 'a'))
  {
    Serial.println("Input 1 selected");
    inpSpeedS[0] = Serial.parseInt();
    Serial.print("Input 1: ");
    Serial.println(inpSpeedS[0]);
   x = '0'; //reset x, goes back to input selection
  } if (Serial.available () && (x == 'b'))
  {
    Serial.println("Input 2 selected");
    inpSpeedS[1] = Serial.parseInt();
    Serial.print("Input 2: ");
    Serial.println(inpSpeedS[1]);
   x = '0';
  }
  if (Serial.available () && (x == 'c'))
  {
    Serial.println("Input 3 selected");
    inpSpeedS[2] = Serial.parseInt();
    Serial.println("Input 3: ");
    Serial.print(inpSpeedS[2]);
   x = '0';
  }
  if (Serial.available () && (x == 'd'))
  {
    Serial.println("Input 4 selected");
    inpSpeedS[3] = Serial.parseInt();
    Serial.print("Input 4: ");
    Serial.println(inpSpeedS[3]);
   x = '0';
  }
  analogWrite(motinp1, inpSpeedS[0]);
  analogWrite(motinp2, inpSpeedS[1]);
  analogWrite(motinp3, inpSpeedS[2]);
  analogWrite(motinp4, inpSpeedS[3]);
}

EDIT - I have turned the char 0 from a string literal null to an ASCII code for 0, and same for the other chars. It is still stuck outside of the function loops.

How it's possible that char  x = "0"; doesn't yeld on you that you are assigning pointer to C string into char variable?

@KIIV I haven't read any books on C yet, only done Udemy courses, so I unfortunately do not know what you're talking about, other than the most superficial I can google myself to in 10 minutes.
Could you please elaborate?

There is a huge difference between '0' and "0". First one is ASCII value of character zero, second one is pointer to memory, where the string containing {'0', '\0'}  is stored

Also note you have a shadow x variable in loop.  Probably not a good idea.

@Delta_G Maybe that edit should be removed anyway

Or just lose the "int" in front of x='0';

It's screaming on you:
sketch_jun13a.ino:7:11: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

 char  x = "0";

           ^~~

sketch_jun13a.ino: In function 'void loop()':

sketch_jun13a.ino:21:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "0")) {

                                    ^~~

sketch_jun13a.ino:21:36: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]

sketch_jun13a.ino:26:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "a"))

                                    ^~~

sketch_jun13a.ino:33:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0"; //reset x, goes back to input selection

         ^~~

sketch_jun13a.ino:34:38: warning: comparison with string literal results in unspecified behavior [-Waddress]

   } if (Serial.available () && (x == "b"))

                                      ^~~

sketch_jun13a.ino:41:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

sketch_jun13a.ino:43:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "c"))

                                    ^~~

sketch_jun13a.ino:50:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

sketch_jun13a.ino:52:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "d"))

                                    ^~~

sketch_jun13a.ino:52:36: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]

sketch_jun13a.ino:58:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

Basically this is char variable with assigned character literal: char x = '0';
And this is C string: char str[] = "0"; or its equivalent: char str[] = {'0', '\0'};. Where '\0' is so called NUL Terminal character.
Everything about C strings you need to know
EDIT:
Simple demo for the "parser" - it's not perfect but should be enough:
char  x = '0';

int inpSpeedS[4]; // An array to determine the speed of each individual input

void setup() {
  Serial.begin(9600);
  Serial.println("Select channel [a..d] and speed [0..255]: ");
}

void loop() {

  if (Serial.available() > 1) { // wait for more characters in buffer
    switch (Serial.read()) {
      case 'a': inpSpeedS[0] = Serial.parseInt(); break;
      case 'b': inpSpeedS[1] = Serial.parseInt(); break;
      case 'c': inpSpeedS[2] = Serial.parseInt(); break;
      case 'd': inpSpeedS[3] = Serial.parseInt(); break;
      default : return; // skip invalid characters like line endings
    }

    Serial.print("Speeds: ");
    for (auto spd : inpSpeedS) {
      Serial.print(' ');
      Serial.print(spd);
    }
    Serial.println();
    Serial.println("Select channel [a..d] and speed [0..255]: ");

    /*
      analogWrite(motinp1, inpSpeedS[0]);
      analogWrite(motinp2, inpSpeedS[1]);
      analogWrite(motinp3, inpSpeedS[2]);
      analogWrite(motinp4, inpSpeedS[3]);
    */

  }
}

And the result:
-> Select channel [a..d] and speed [0..255]:
<- a547
-> Speeds:  547 0 0 0
-> Select channel [a..d] and speed [0..255]:

Ah thank you,
But by this logic, shouldn't turning [code]char x = "0"[/code]  into [code]char x = '0'[/code] then fix the loop?
If yes, then something else was also wrong with the loop, since it still is stuck at [code] Serial.println("X Equals:"); Serial.print(x);[/code]

You have to fix all of it including 'a', 'b', 'c', 'd'. But there might be another mistake, as the code cannot be compiled due to missing variables I was lazy to add up

Well, if you would like to help further, I have edited the code so that it should follow the reccomendation you gave.

Btw, it's not stucked, if you send for example  a154, it'll set the first channel to 154, but it should be set once, you don't want to send it each loop. The same as you don't want to send output every loop interation

@GeorgeWTrump I've added little bit simplified example but somehow working

This is strange, I am not getting the same results as you, using your code?
Are you using the Arduino IDE? Also, come to think of it, doesn't Arduino IDE use c++?

Let us continue this discussion in chat.


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:
unexpected primary-expression before ';' token
I'm new to the Arduino world and am working on a sketch to run a servo up and down with a spdt switch.
 My code is :
include #include<Servo.h>
int pos = 0;

Servo myservo;
void setup() {
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  myservo.attach(9);
}
void loop() {
  if (digitalRead(2) == HIGH && pos < 180) {
    pos++;
    servo.write(pos);
    delay(15);
  }
  if (digitalRead(3) == HIGH && pos > 0) {
    pos--;
    servo.write(pos);
    delay(15);
  }
}

When I compile I get the "unexpected primary-expression before ';' token" error with exit status 1.
What am I doing wrong???

Use myservo instead of servo in the blocks (to start with :).

include #include<Servo.h> looks a bit screwy to me... ;)

You are looking at the last compiler error, but the first one is the most important. You can scroll up in that output window to find the first compiler error. Are you using Arduino IDE 1.8.2 with an Arduino Uno ? because I get a different compiler error.

1) You should be using:
myservo.write(pos);

instead of
servo.write(pos);

for all of your  methods.
2) Change:
include #include<Servo.h>

to
#include <Servo.h>

This code only verifies when it is run on certain boards*, so make sure you are using one of those boards.Good luck and welcome to the Arduino world!:)
*Verify that your board will work, I know Mega, Uno and Nano will function properly.
P.s. Here is the whole code in correct format:
#include <Servo.h>

int pos = 0;

Servo myservo;
void setup() {
 pinMode(2, INPUT);
 pinMode(3, INPUT);
 myservo.attach(9);
}
void loop()
{
  if ( (digitalRead(2) == HIGH) && (pos < 180)) {
    pos++;
    myservo.write(pos);
    delay(15);
  }
  if ( (digitalRead(3) == HIGH) && (pos > 0)) {
    pos--;
    myservo.write(pos);
    delay(15);
  }
}

I got it working on a NANO without the stacked parenthesis. My problem was I was trying to use an external servo library (not needed) and my USB cable was no good (power only)

@CSnyder okay! Glad to hear it ran on Nano, I will correct my answer, and overall that you got your project working. Good luck!


text:
My code is stuck in a loop involving Serial.read. How can I break this?
So I'm running a program that involves both Arduino and a Raspberry PI and they are communicating between the Serial port. As you can see below when my an emergency stop door, involving a magnetic switch, is opened then the PI sends a message to the Arduino. When the door is closed the PI sends a different value telling the Arduino to continue with the program. The Arduino is receiving and reading the messages correctly as I have ran a few tests with the serial monitor.
When the door is open the PI is printing '1' which shuts down the Arduino correctly. My problem is that when I close the doors nothing happens when in theory it should break the loop and continue to run the main Arduino code. The raspberry PI is correctly printing '2' and the Arduino is correctly reading this value as it prints "Logoff" in the serial monitor.
If anyone can help or lead me to correctly breaking this loop and returning to the main code that would be great.
Thanks.
Below is the emergency part of the code that continues to run. If the full code is needed I will gladly edit it into this post. Also if the PI code is needed I will post that too, I don't believe is necessary because there are no problems on that side.
void Estop() {
    if (Serial.available()) {
        int d = Serial.read() - '0';

        while (d == 1) {
            digitalWrite(green, HIGH);
            digitalWrite(red, LOW);
            digitalWrite(blue, HIGH);
            digitalWrite(estopout, HIGH);
            digitalWrite(piston, LOW);
            digitalWrite(belt, HIGH);
            Serial.read() - '0';
            Serial.print(d);
            delay(2000);
            break;

            if (d == 0) {
                Serial.print("Logoff");
                delay(2000);
            } else {
                break;
            }
        }
    }
}

`

I have reformatted your code so it indents properly. It then becomes much easier to see the flow of logic. I have a feeling the whole way you are doing what you are wanting to do is flawed. A proper description of what exactly it is you are trying to achieve would help.

What does this line prints? Serial.print(d);

You never reassigned the variable d anywhere within the loop. The while breaks after a 2 seconds delay after printing what is the value of d. That means that your if (d == 0) [...] never gets hit. I presume that you expect to read 'logoff' on your code?
void Estop() {
    if (Serial.available()) {
        int d = Serial.read() - '0';

        while (d == 1) {
            digitalWrite(green, HIGH);
            digitalWrite(red, LOW);
            digitalWrite(blue, HIGH);
            digitalWrite(estopout, HIGH);
            digitalWrite(piston, LOW);
            digitalWrite(belt, HIGH);
            d = Serial.read() - '0';
            Serial.print(d);
            delay(2000);
            #break;

            if (d == 0) {
                Serial.print("Logoff");
                delay(2000);
            } else {
                break;
            }
        }
    }
}

Inside your while loop, you never change the condition, running into an infinite while loop.
Further: Your program does not delay until d equals 0 or 1. This can be problematic as d can have other values. It is an int.
Plus, you do a while loop while d equals 1 and ask, if d equals 0 without changing the value of d in between. Your if would never be true.
I also don't know, what this line should do:
int d = Serial.read() - '0';

did you mean:
int d = Serial.read();

I dont't see any sense, to subtract 0 from your the value you read.

The line that subtracts '0' converts the script coming form the PI into a value that the Arduino can read. So should i change the while to an if statement?

'0' is the ASCII value, so subtracting turns a ASCII number into its corresponding integer.  It is basically atoi(Serial.read()) that is only valid for the characters 0-.


text:
Serial.print array displays nothing
I tried Serial.print an array I had made, but the Arduino displays nothing in the monitor.
I tried doing Serial.print("Hehehe"); as a test, but it just displayed "h?h?h?".
The monitor works fine with other sketches than this one.
Anyone knows why?
int my_array[10];

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  for (int i = 0; i < 10; i++){
    my_array[i] = i * 5;

  }
}

void loop() {
  // put your main code here, to run repeatedly:
    for (int i = 0; i < 10; i++){
      Serial.print(my_array[i]);
      Serial.print(" ");
    }
    Serial.println();
    delay(1000);
}

do you have 9600 baud set in Serial Monitor?

@Juraj I have set it to 9600.

In setup() you write to undefined memory my_array[10]. It's undefined if that hurts or not.

@DataFiddler I don't quite understand.
The sequence is filled in the function that takes i + 5.

i < 11 it should be 10

Test on my Arduino Uno, your code works fine with a simple copy-paste. Remember to set the proper baud rate.

Must be something faulty with my own Arduino then. Thank you for the answer though :)

Load a blink sketch and check if the blink speed is correct. (Should have accuracy of at least 1/1000).


text:
Arduino Won't Work With Sensors - Pulsates 1/HIGH when not plugged in, constant HIGH/1 when plugged in

simulate this circuit – Schematic created using CircuitLab
I tried to do a simple project where a 8x8 matrix lamp would display something different depending on whether or not a sensor outputted high/low.
There was no trouble getting the matrix lamp to work, as I wanted, but the sensor kept outputting 1, regardless if it was plugged in or not.
This is the code I used, but when I plugged in the sensor it would display 1/high continuously, and when I removed all wires from the sensor, the lamp would light occasionally and the monitor would display 1 as the movStat value.
The LED lamp is connected directly to the breadboard via. digital pin 4.
I am considering buying a new Arduino, but I would like to get a second hand opinion before I spend money on it.
I am using a PIR sensor model HC SR501:

int movSens = 3;
int ledPin = 4;
int movStat = 0;

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    //Sensor Setup
    pinMode(movSens, INPUT);
    //LED Setup
    pinMode(ledPin, OUTPUT);
}

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

    Serial.println(movSens);

    movStat = digitalRead(movSens);

    if (movStat == HIGH) { //If motion is detected, activate LED
        digitalWrite(ledPin, HIGH);
    }
    else {
        digitalWrite(ledPin, LOW);
    }

    Serial.println(movStat);
}

Please show your schematic and code if you want any help.

Alternatively request that your existing SO question be migrated to here.

@Majenko I have added the original question now :)

Do you have a resistor with your LED?

@Majenko yes, but the LED isn't the problem.
The problem is, that the Arduino randomly outputs a value such that movSens becomes 1/HIGH, activating the LED, even though there is absolutely no sensor or anything connected to the Arduino.
And if I connect the sensor, even with 15 seconds of calibration, it will just remain on HIGH/1. This also happened with another sensor I had.

With no sensor you can expect a random value - you have a floating input. That tells you the Arduino is fine. It sounds more like the sensor is bad or not wired correctly.

@Majenko THat is good to hear. But, the sensor will still activate, and then remain at 1.
This has nothing to do with my code, but has something to do with the sensor itself? It is wired such, that looking at the pins, the right hand pin is wired to 5V, middle output and left GND, i.e according to the schmeatics.

Sounds likely. Can you show your actual wiring (photograph will do)?

@Majenko I have added schematics.

the documentation states that the output is 3.3 V when motion is detected and 0 V otherwise .... if you are using a 5 V arduino, then use the analog input for the sensor

@jsotola, Mega will read 3.3 V as HIGH

@jsotola Tried using A1, nothing changed.

use a voltmeter to verify the output of the sensor

Could it have something to do with the trigger or not trigger jumper setting.


text:
I2C 16x2 LCD - Will Initialize (sometimes) - Holds Up The Code
Basically I have a keypad, that when a certain code is entered, it will write either "Wrong code" or "Good code" on the LCD.
At the same time a timer will count down until 0 is reached, in which case the whole LCD will display something (undecided/irrelevant).
I have tested the keypad module/part of the file, and it works exactly as expected. Each loop is entered correctly, and I have tested this part several times.
The problem, I believe, lies with the LCD. It will initialize, i.e It will display
"Time:
Code:"
But then, what comes after feels like it is randomly decided.
Sometimes I can press 1 button, and it will be printed to the serial. Other times I can press more. Sometimes it will lag for every button press, sometimes it will only be the first button press that is slow.
Secondly, if I try to re-run the script nothing will happen. I have another script (see the 2nd code,) that will usually do the trick.
But all of this takes forever. My code is suppossed to run independently, such that I can play multiple code games, will this obstruct it? Any ways to fix it?
Main code:
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>

//LCD Setup
LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

//Keypad Setting

  char resetTrigger = '*';

//KeypadCodes

  String goodCode1 = "3569";
  String goodCode2 = "69696969";
  String enteredCode = "";
  //Len has to be declared before the "checker" loop
  int len = enteredCode.length();

const byte ROWS = 4; /* four rows */
const byte COLS = 4; /* four columns */
/* define the symbols on the buttons of the keypads */
char hexaKeys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {10, 9, 8, 7}; /* connect to the row pinouts of the keypad */
byte colPins[COLS] = {6, 5, 4, 3}; /* connect to the column pinouts of the keypad */

/* initialize an instance of class NewKeypad */
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

void setup(){
Serial.begin(9600);
lcd.init();
lcd.backlight();
lcd.clear();
//Sets "Timer: " in the top and "Code: " in the bottom
lcd.setCursor(0,0);
lcd.print("Time:");
lcd.setCursor(0,1);
lcd.print("Code: ");
}

void loop(){
  char customKey = customKeypad.getKey();
  len = enteredCode.length();

  if (customKey){
    //Reset Trigger
  if (customKey == resetTrigger){
    //LCD clear code
    enteredCode = "";
    Serial.println(enteredCode);
    Serial.println("Reset trigger");
    len = enteredCode.length();
  }

  //Char added to code
  else{
    enteredCode.concat(customKey);
    Serial.println(enteredCode);
    Serial.println("Char added to code");
    lcd.setCursor(5,1);
    lcd.print(enteredCode);
    len = enteredCode.length();
  }
    //Correct code
  if ((enteredCode == goodCode1) or (enteredCode == goodCode2)){
    //LCD Correct Code
    //Good sound
    //Door open
    lcd.setCursor(2,0);
    lcd.print("Correct code");
    delay(1);
    Serial.println("Correct code");
  }
  //Wrong code
  if ((len==8) && (enteredCode != goodCode1) && (enteredCode != goodCode2)){
    //LCD clear code
    //Bad sound
    enteredCode = "";
    Serial.println(enteredCode);
    Serial.println("Wrong code");
    //Changes the LCD to wrong code, waits 2 secs and then back to code
    lcd.setCursor(2,0);
    lcd.print("Wrong code!");
    len = 0;
    delay(2);
    lcd.setCursor(2,0);
    lcd.print("Code:");
  }}

}

2nd code (reset code):
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd
  // Print a message to the LCD.
  lcd.backlight();
  lcd.clear();
}

void loop()
{
}

EDIT:
So now it will work more regularly after changing it from (LiquidCrystal_I2C lcd(0x27,16,2)) -> LiquidCrystal_I2C lcd(0x27,20,4).
I am still having problems with it though.
I have noticed, that sometimes it won't update the screen unless I physically nudge the LCD-screen, which is weird.
Also if it runs for "too long," the screen will stop updating at all.
Maybe a hardware issue?

If nudging helps, it is a clear sign of a hardware issue. Check your wiring and make sure you have a certain quality of components.


text:
Syncing/taking external clock for SPI on Arduino Due
I have an Arduino Due with a SAM3X8E chip and am trying to read SPI data from an external source that is communicating in SPI. I was able to get data by identifying specific bytes that are identifiers but realized that the clock for my board is not synced with the source coming in. I print out the bytes in hexadecimal format (08 00 FF AB etc) and each message is 128 bytes long.
To be clear, the source is an SPI master that is sending out data on its own MOSI line, but I am currently treating my board as a master as well since I do not know how to do Slave mode on Due. I connect the Slaves MOSI line to my boards MISO line, and just transfer data and read 128 bytes but it would appear that I am not getting the same data. Is there a way for my to take in the clock from the external clock and synchronize my board with that clock to make sure? My source code is below. The only methods I can think of are to either figure out how to implement the board in slave mode (i'm not familiar enough with the registers and how to change this, or read data in slave mode) or synchronize the clocks so my board is reading and sampling the source data correctly.
Could someone check if my thinking is correct, or do I not need to make any changes since the data is in a shift register?
Thanks

void setup(){
Serial.begin(9600);
SPI.begin();
SPISettings settings (50000000, LSBFIRST, SPI_MODE1); //Sampling rate    50Mhz, source's max speed
SPI.beginTransaction(settings);
}

void loop(){
  int i = 0;
  uint8_t value;
  value = SPI.transfer(0x00);
  while (value != 8){//searching for identifier 0x08
    value = SPI.transfer(0x00);
  }
  SPI.transfer(buffer, 127);//get the rest of the 127 bytes
  Serial.print(value, HEX);
  Serial.print(" ");
  for (i = 0; i < 127; i++){
    if (buffer[i] == 0){
      Serial.print(buffer[i],HEX);
      Serial.print(0, HEX);
    }
    else{
      Serial.print(buffer[i], HEX);
    }
    Serial.print(" ");
  }
  Serial.println("\n");
}

For your external source to be an SPI bus master, it has to be the only one generating the clock signal. Yet, calling SPI.transfer() also generates a clock signal from the Arduino; both devices are attempting to drive the clock line simultaneously, hence your problems.
You have to bit-bang this or manipulate the SAM registers yourself to configure it as a slave; the SPI library doesn't support slave mode.
In order to bit-bang, you'll have to define your own MOSI, SCK, SS (and MISO, if you'll be writing to the master) pins and do all the sampling yourself with digitalRead(); there are no registers to be read from since you aren't using the SAM's SPI peripheral.
Since your SPI mode is MODE 1, it means the clock idle polarity is LOW, and that data is sampled on the falling edge. To bit-bang with digitalRead(), it is necessary that the SCK frequency be below 50 kHz (digitalRead() takes about 4us), taking overhead into account. You should use direct port manipulation, if you need a higher frequency. If you'll be blocking till you've read data, and assuming that the external source always sends data in byte units, then a basic algorithm:

Create a byte array to hold all the expected bytes
Define a byte variable (curr_byte, maybe) for holding each byte received
Wait till the SS pin goes LOW
Clear curr_byte to zero
Wait till SCK goes HIGH
Wait till SCK goes LOW
Read the bit on the MOSI line and shift it into curr_byte
If you've received up to 8 bits so far, save curr_byte to the byte array; if SS is still LOW, go to step 4, else exit this loop. But if you haven't received a complete byte yet, go to step 5.

After you leave the loop, you can then confirm the bytes you've received with Serial. If the external device can send data with any number of bits, then you should always check the SS line after you shift in a bit, to determine if the Due has been deselected or not i.e. if there are any more incoming bits.

Thanks, that seems to make sense. I think I understand bit-banging but am confused as to how I should sample accordingly since I can't call SPI.transfer(). Is it reading from SPDR or the data register? Because on Arduinho Due, I don't think it recognizes SPDR, but the objective should be to just wait until SCK is high and then read from the respective data register. I'm just not sure how to or which register the incoming external MOSI data will be found.

@wallenut I've edited my answer.

That clears it up a lot. Thank you, I just have to deal with the locating where MOSI data is shifted into registers and read those and it should be fine.

Your help answers my question. I just do not think it will work for the high clock rate at which this sends data (50 Mhz). I'm going to mess around and try to change the registers and operate it in slave mode, but there is not much Arduino due documentation for slave mode. Any tips on how to use the Atmel Data sheet? This is my first real Arduino project.

@wallenut You won't be able to achieve 50 MHz; the Due has an 84 MHz clock and the lowest SPI prescaler is 2, giving you a maximum SCK frequency of 42 MHz. Is it possible for you to get the master to send data at lower speeds? For a sample Due slave sketch, check this out: https://github.com/manitou48/DUEZoo/blob/master/spislave.ino. You'll have to change the SPI mode to MODE1 in the sketch, set the clock speed with SPI.setClckDivider(SPI_CLOCK_DIV2) and adapt the loop() for your purposes. I haven't used a Due before though, so I may not be much help.


text:
Meaning of part number suffix on top of atmega2560 chip
I have been working on creating a stand alone atmega2560 arduino. When trying to program it with a serial adapter using the rx and tx pins nothing was happening. After a lot of debugging I found the problem was with the chip.
I found that the ones that worked said atmega2560 16AU 0721, the ones that did not work said Atmega2560 16AU 1241. When looking on eBay, i noted that the Atmega2560 16AU comes with many different versions of those last four numerals, does anyone know what the last four digits on top of the atmega2560 16AU mean?

Since you have an ICSP header please use my chip detector sketch to report on the chip. It will tell you if it responds (thus proving the chip is more-or-less OK) plus the fuse settings, and what bootloader is installed. You can edit this information into the question.

1241 = 41st week of 2012. 0721 is 21st week of 2007.

indeed the problem was with the Bootloader. I was using the default one available in the Arduino IDE. I changed to use the one create by Nick Gamon, https://github.com/nickgammon/arduino_sketches , and problem solved. I can now program the ATMEGA2560 via serial.

The last four digits are a date code - the date of manufacture.
It's in the form YYWW where YY is the last two digits of the year, and WW is the week number.
So 0721 is the 21st week of 2007, and 1241 is the 41st week of 2012.

The data sheet (or supplemental product-line documentation) will specify the formal package marking codes, but for an ATmega, the 16AU is part of the variant specification but the following would appear to be date or lot codes.
These are probably not your problem.
More likely, the chip you are trying to interact with via the serial port

does not have a bootloader flashed (normally they are sold blank)
has a bootloader which requires a different baud rate
is fused for a clock source you are not providing
has the brownout detector set lower than the supply you are providing
is improperly or incompletely soldered
is damaged

While there was the infamous case of Sparkfun being sold a reel of power supply chips falsely marked as ATmega328's, this is still a relatively unlikely possibility compared to the more likely ones above, especially the simple lack of a bootloader.  And a date code is no proof of authenticity - though if you ended up co-mingly inventory from various sources/purchases, it might help you with preliminary sorting them.

Thanks Chris...I used the iCSP header to install the same bootloader in both chips. I have several chips of the one that do not work, and it is the same problem with all of them, so I do not think it is a defective chip. I also checked all connections and soldering. I will check the baud and clock.

That information belongs in the body of your question - use the edit button.

You should use the ISP to load a sketch which tries the other serial ports and produces output without needing input.  Also which toggles pins at a known rate, and then measure that rate and see if it is correct...

I think Chris is very likely right about the clock source. The default for the low fuse byte is for the "divide clock by 8" bit to be programmed, which means that you would be able to interface via ICSP, but to use the bootloader the baud rate would be 8 times too slow.

Any suggestion to  fix this problem? I have installed the bootloader available in the arduino IDE in both chips.


text:
Interfacing Aduino Nano and RDM8800
I'm attempting to use an Arduino Nano with the RDM8800 to read data from NFC tags. After soldering wires between the Nano and the RDM8800, I attempted to test these devices using code similar to what has been used successfully on other serial devices similar to the RDM8800. Below is the code I used to test.
Wiring:
Nano - RDM8800
--------------
 5V  -  5V
GND  -  GND
 D3  -  TX
 D2  -  RX

Tags Tested:

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

Code:
#include <SoftwareSerial.h>

SoftwareSerial soft(2,3);

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

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

}

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

I watched the serial monitor and attempted to scan two different NFC tags that matched the ISO14443A compatibility that should ship with the RDM8800, according to this article. I got no information returned on the serial monitor.
After, assuming the issue is with the firmware, I attempted to upload the firmware to the RDM8800, with no success. I installed the needed board support to the Arduino IDE, as outlined in the intro article. Not having a USB to serial tool, I used another Nano and simply bridged the connection between the GND and RST pins. I was unable to upload the firmware to the RDM8800, getting the error below each time I tried.
Error:
avrdude: stk500_recv(): programmer is not responding

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

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

your code is set to communicate to pins that are different than your actual connection

SoftwareSerial constructor is rx pin first then tx pin.
You have SoftwareSerial soft(2,3); But you said that
D3 - TX
D2 - RX

Which means soft rx is going to its rx and soft tx is going to its tx. These need to be swapped. Either swap the wires or change it to:
SoftwareSerial soft(3,2);


text:
Why are my motors attached to an Arduino MEGA not running?
I verified my code and uploaded it to the board and that was successful.
Info:
  - Using Mega 2560 Arduino Board with Adafruit V1
  - 3 DC 12 volt motors
  - on HP computer
Here is my code:
#include <AFMotor.h>

AF_DCMotor motor(1, MOTOR12_8KHZ);
AF_DCMotor motor2(2, MOTOR12_8KHZ);
AF_DCMotor motor3(2, MOTOR12_1KHZ);

void setup()  {
  Serial.begin(9600);
  Serial.println("Motor Test!");
  motor.setSpeed(20); //set speed of motor
  motor2.setSpeed(20); //set speed of motor
  motor3.setSpeed(25); //set speed of motor
}

void loop() {
  Serial.print("tick");
  motor.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor.run(RELEASE);
  delay(5000);

  Serial.print("tack"); //first song starts
  motor.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor.run(RELEASE);
  delay(14000);

  Serial.print("tack");
  motor.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song ends
  motor.run(RELEASE);
  delay(13000);

  Serial.print("tick");
  motor.run(FORWARD);
  delay(2000);

  Serial.print("tock"); //second song starts
  motor.run(RELEASE);
  delay(24000);

  Serial.print("tick");
  motor.run(FORWARD);
  delay(2000);

  Serial.print("tock"); //second song ends
  motor.run(RELEASE);
  delay(17000);

   Serial.print("tick");
  motor.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //third song starts
  motor.run(RELEASE);
  delay(23000);

  Serial.print("tick");
  motor.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //third song ends
  motor.run(RELEASE);
  delay(21000);

  Serial.print("tick");
  motor.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor.run(RELEASE);
  delay(5000);

  Serial.print("tick");
  motor.run(FORWARD);
  delay(3000);

  Serial.print("tack"); //fourth song starts
  motor.run(RELEASE);
  delay(5000);

  Serial.print("tack");
  motor.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //fourth song ends
  motor.run(RELEASE);
  delay(21000);
   //waving motor
  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(5000);

  //Waving motor
  Serial.print("tick"); //first song starts
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song ends
  motor2.run(RELEASE);
  delay(14000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(5000);

  Serial.print("tack"); //SEcond song starts
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //second song ends
  motor2.run(RELEASE);
  delay(15000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(5000);

  Serial.print("tack"); //Third song starts
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tock"); //third song ends
  motor2.run(RELEASE);
  delay(14000);

  Serial.print("tick"); //fourth song starts
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //fourth song ends
  motor2.run(RELEASE);
  delay(7000);

  //dancing motor
  Serial.print("tock"); //first song starts
  motor3.run(RELEASE);
  delay(11000);

  Serial.print("tick");
  motor3.run(FORWARD);
  delay(22000);

  Serial.print("tock"); //first song stops //second song starts
  motor3.run(RELEASE);
  delay(16000);

    Serial.print("tick"); //Second song stops
  motor3.run(FORWARD);
  delay(28000);

  Serial.print("tock"); //Third song starts
  motor3.run(RELEASE);
  delay(15000);

  Serial.print("tick"); //Third song stops
  motor3.run(FORWARD);
  delay(33000);

  Serial.print("tock"); //fourth song starts
  motor3.run(RELEASE);
  delay(16000);

  Serial.print("tick");
  motor3.run(FORWARD);
  delay(5000);

  Serial.print("tock");
  motor3.run(RELEASE);
  delay(1000);

  Serial.print("tick"); //fourth song ends
  motor3.run(FORWARD);
  delay(16000);

  Serial.print("tock");
  motor3.run(RELEASE);
  delay(5000);
}

I hope you're not trying to drive the motors directly from the output pins ...

As you did not give details I assume the following:

You supply the MEGA via USB or external 5-12V power supply
the motors are supplied via an extra external 12V power supply with sufficiant amperage
All cabeling is checked and correct

Looks like this schematic (without 12V power supply attached to the motor shield)

To your code:

Get rid of the delay()s - they block processing so what happens:
 motor.run(FORWARD);  // => You give a command via lib
 delay(2000); // You stop your processing so the motor is not running

so you have two options both need the definition of a timeStamp var

working with a (blocking) while loops
or creating a finite state machine (search here on SO for details)

So I will for simplicity use the first approach
 // Copy this var before your setup
 unsigned long timeStamp = 0;
// use your complete setup
 void setup(){...}
 // Change your loop functions like thes first three converted lines
 void loop(){
  timeStamp = millis();
  Serial.print("tick");
  while(millis()-timeStamp < 2000){
     motor.run(FORWARD);
  }
  timeStamp = millis();   // resets the time to current
  Serial.print("tock");
  while(millis()-timeStamp < 5000){
     motor.run(RELEASE);
  }
  timeStamp = millis();   // resets the time to current
  Serial.print("tack"); //first song starts
  while(millis()-timeStamp < 2000){
     motor.run(BACKWARD);
  }
// .... AND SO ON .....
}

Be aware that the whiles are blocking but for your sequential processing its ok.

Comments are not for extended discussion; this conversation has been moved to chat.

Codebreaker, you are more patient than I.


text:
NodeMCU unable to connect to mobile hotspot when I include codes for reading the temperature sensor
Good day.
The NodeMCu successfully connected to mobile hotspot when i didn't put any others codes except the Wifibegin etc.
Howveer when I include some codes for temparature sensor, it keeps on connecting whereas the everything else including the SSID, password remain the same.
Below are my codes, I tried many, I mean I tried almost everything possible(that's stated in forums), read forums after forum. Please let me know if I missed something out here.
Thanks!
PS:  i attached my codes here
#include <ESP8266WiFi.h>
#include <WifiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

/* Wi-Fi setting connect to your smartphone Wi-Fi hotspot */
const char *ssid = "Thanks";
const char *password = "For reading";

/* Variable for taking out LM35 value */
String tempValue;
int analogValue;
int tempPin = A0;
float milliVolts;
float celcius;
/* Variable for sending data to server */
String postData;
int httpCode;
String payload;
void setup(){
//delay(1000);
Serial.begin(115200);
WiFi.begin(ssid,password);
Serial.println("");
Serial.println("Connecting");
/* If Wi-Fi hotspot is not found, show ..... in serial monitor */
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.println(".");
}
/* If Wi-Fi hotspot is found, show IP address in serial monitor */
Serial.println("");
Serial.println("Connected to ");
Serial.println(ssid);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop(){
/* Getting value from LM35 */
delay(1000);
analogValue = analogRead(tempPin);
milliVolts = (analogValue/1024.0)*3300;
celcius = milliVolts/10;
tempValue = String(celcius);
Serial.println(tempValue);
/* Sending LM35 value to server */
HTTPClient http;
postData = "tempValue=" + tempValue;
http.begin("http://xxx.xxx.xx.xxx/dbInsert.php");
http.addHeader("Content-Type","application/x-www-form-urlencoded");
httpCode = http.POST(postData);
payload = http.getString();
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end();
}

Your code is missing from the question. Also, what temperature sensor did you use and what pins did you use to connect your sensor?

@StarCat Hello. Thanks for replying..Edited. Codes as attached. 3.3V, GND,A0

Get rid of the delay - this STOPS processing for five seconds, not really what you want in a wifi scenario - some routers might disconnect you in this time if no pingbackis are comingIf you need a 5 second- non blocking break for your routines look at this example ArduinoIDE -> examples -> 2 Digital -> blinkwithoutdelay.
For further assistance copy and paste your code in code tags and not as a picture.

Hello . Thanks for your feedback. I  edited and pasted the code in text form. I tried omitting the delay(5000), but still doesn't work out... I reexamine the codes, and can't see the prob, please let me know you can detect the problem...thank you!!!

You still have delay in your loop, as long as you use delays debugging is useless /* Getting value from LM35 */
delay(1000); => get rid replace with something if(millis() - startTime < timeToWait)...  >> see blinkwithoutdelay example


text:
Car PA system enhancement
Hello i have one of these
My goal for this project is to have a higher quality mic and be able to play music through it
My question is how would i link a 3.5mm aux cable to the arduino as input and output to the rj9 line. I have prior knowlege on liking a aux as i have setup my Christmas lights as a vu meter using relays and a aux but the confusing part is the rj9 line
Are the speaker pins only to trigger a relay and allow power to flow from the car battery or am i completely wrong if im right i assume i could just solder the audio jacks positive negative to the rj9 mic positive negative and then find a method to triger the speaker relay

your question about modifying the PA device is not related to an Arduino

Well assuming that my bottom portion was true the arduino was going to trigger the speaker if audio was comming off the jack there could be a better way though that would not require a arduino

"how would i link a 3.5mm aux cable to the arduino as input and output to the rj9 line" - the arduino uno doesn't have a digital to analog converter, so without external hardware it's not possible to make him generate the audio signal. Also its ADCs are not fast enough to sample an audio signal coming from a microphone at a sufficient sample rate (I think the maximum are 1-2kHz). As you explicitly want to improve sound quality this is an issue.
When using an arduino uno you might be better off using an external audio circuit which only gets switched on and off by the arduino.
Controlling the siren's buttons will not be a big difficulty. You have to do some reverse engineering to find out the siren's logic level and how the buttons are used in the device. You can probably simply replace them with mosfets, but that is an electronic issue.

So even with a adc the standard sample rate being 44.1 khz i would need almost 30 times the current capabilities of a adc. I didnt realise that perspective thank you


text:
Adafruit 2.8 TFT LCD Touchscreen 4 wire pins - unclear instructions
Warning - Noob question
I am trying to follow the instructions provided by the vendor https://learn.adafruit.com/2-8-tft-touch-shield/touchscreen-paint-example to no avail. Specifically:

We connect the 4 pins as follows:
  Y+ is connected to Analog 1
  Y- is connected to Digital 7
  X+ is connected to Digital 6
  X- is connected to Analog 2

My board looks like this

and I cannot see any X/Y/+/- labelled pins. I then found the schematic of the board
https://github.com/adafruit/Adafruit_2.8_Inch_TFT_Shield_PCB/blob/master/schem.png
where these pins are labeled but what is the representation of the schematic on the board?
Finally, once I do find the pins, how do I connect them if they are already used? Do I have to use a breadboard?
Edit: After the helpful comments of jsotola, I got a photo:

Are these the 4 "pins"? If so, how on earth do I connect these to the arduino?

I thought the touch panel and the LCD are essentially the same thing because they are embedded to each other.

I did try the example, the colored boxes showed up fine but no touch input registers.

@jsotola do you know if I can detach the TFT from the board to inspect the connection of the touch panel? I inherited this arduino / TFT and I do not know the history of its touchscreen. Yes I am using the tftpaint_shield sketch

TFT touchscreen shield https://imgur.com/a/WSMifOu

looks like the touch panel has been removed

Seems really to be as jsotola wrote. The 4 line flat cable, that you marked, was cut. It should go to the touch panel in front of the TFT, but it seems to miss. So no touch detection

Thanks both - well that is the end then of any touchscreen plans. Will keep it as a screen only

buy another touch panel and stick it on the LCD .... https://www.instructables.com/id/Touch-Screen-Overlay-with-Arduino/


text:
Waiting for an AT command to complete
I'm looking for a way to wait for a response from an AT command to return OK or CONNECTED or whatever the command returns when it's true.
I can check if the serial is available, but that means I have to manually guess what time between commands to give them time to connect or start.
Function:
void ModemCommand(String command) {
  //Send command to modem
  mySerial.println(command);
  Serial.println(command);
  delay(100);
  while (!mySerial.available()) {
    //Wait for Response from modem
    Serial.println(F("No response yet"));
    delay(1000);
  }
  while (mySerial.available()) {
    Serial.write(mySerial.read());
    //Print response from modem
  }
  Serial.println("");
  //Linefeed after reponse
  delay(10);
}

Code example:
ModemCommand(F("ATE0"));
//Turn on echo
ModemCommand(F("AT+CFUN=1"));
//Turn modem functions on
waitSec(8,F("turning on Modem functions"));
ModemCommand(F("AT+CGREG?"));
//GSM attached?
ModemCommand(F("AT+CSQ"));
//Signal Quality
ModemCommand(F("AT+CSTT=\"internet\""));
//Set APN
ModemCommand(F("AT+CIICR"));
//Connect to APN GPRS
waitSec(8,F("connecting to APN GPRS"));
ModemCommand(F("AT+CIFSR"));
//Get IP

Does anybody know how to do this?

You first need to understand how serial on the Arduino works.  Read this first: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

The most you can do is define a certain amount of time between received characters, after which you can decide that there's nothing more to be read from the modem. Of course, the time taken for processing is longer for certain commands (and some provide no response at all, until you've completed entering their payload, like TCPSEND, in which case you should simply use mySerial.write() to send said payload, and not your function), but once a response is ready and its first character is available, a timeout of 1 second between characters should be sufficient, for any reasonable baud rate. Something like this:
#define TIMEOUT 1000

void modem_command(String command){
  mySerial.println(command);
  Serial.println(command);
  while (mySerial.available() == 0);  // wait for first char

  unsigned long lastRead = millis();   // last time a char was available
  while (millis() - lastRead < TIMEOUT){
    while (mySerial.available()){
      Serial.write(mySerial.read());
      lastRead = millis();   // update the lastRead timestamp
    }
  }
  // No need for extra line feed since most responses contain them anyways
}

Of course, you can always alter TIMEOUT based on your findings.

Just looking for a response, and not interpreting it seems like a fairly weak solution.

@ChrisStratton But thats what he's asking for: a way to send a command, wait 'efficiently' and view the response with minimum fuss. I assume he'll be monitoring the responses from the serial monitor (given his code example) so thats okay. Besides, anything extra would require a lot of parsing and there are whole libraries for that.

If the response is being monitored externally, there's no need to internally decide when it has been completely received.  Proxying between two serial devices can be entirely stateless.  Rather it sure looks like echoing back to the PC is only there for debug monitoring - the shown program automatically executes a lot of commands without waiting for any external confirmation that the echoed response is positive and not an error.  If this system is going to be actually useful, internal parsing will be required - an answer already posted last fall.

@ChrisStratton yeah...thats exactly what his code is doing. While its not the best practice, it does have a lot of simplicity especially for prototyping. If you want me to correct his mistakes though, thats something else...

Someone else already did address those mistakes, months before you posted, which is part of what makes an answer that perpetuates them less than satisfying.

@ChrisStratton I dont even know if they are mistakes. Look at his function; there are zero attempts to parse a response, though he knows its possible for a command to return an error. What does that say? He'll be monitoring everything with the serial monitor and if any errors result, he'll see them. I've used this simple sort of code for prototyping before, right before I implement a proper library when I'm done with proof-of-concept. All the other answer gives is a vague reference to a buffer and "just check whatever is the response" for parsing--not nearly enough for a beginner to work with.

You would need to create a buffer which will populate over each loop so you dont block the main loop while waiting the all string.
When you get the string or your buffer is full, just check whatever is the response, and based on that you can make your decision.

Yes - though it's not actually necessary to buffer the response, as one can also compare character by character as they are received and keep a persistent count of how many matching ones have been found.  Buffering may be best for short responses like this though.


text:
Bluetooth help with Arduino Due
I have been able to establish a successful connection between an RN-42 Bluetooth module and Arduino Uno, but I could not do the same with an Arduino Due. The module connects to the phone but whatever data I send is not registered. What is different on the Due in the context of Bluetooth connectivity? Baud-rate perhaps?

do you use hardwareserial or softserial? are you sure that you hooked up the rx tx as well as pwr and gnd correctly?

Please show your code and explain which pins the Bluetooth is connected to on both boards?

int ledPin = 13;
int state = 0;
int flag = 0;
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
Serial1.begin(115200); // Default connection rate for my BT module
}
void loop() {
if(Serial.available() > 0){
state = Serial.read();
flag=0;
}
if (state == '0') {
digitalWrite(ledPin, LOW);
if(flag == 0){
Serial.println("LED: off");
flag = 1;
}
}
else if (state == '1') {
digitalWrite(ledPin, HIGH);
if(flag == 0){
Serial.println("LED: on");
flag = 1;
}
}
}

The pins are:                                                                                5v(RN-42) -->  5v (Arduino due),                                                                       GND(RN-42) --> GND(Arduino due),                                                       RX(RN-42) --> TX(Arduino due),                                                                   TX(RN-42) --> RX(Arduino due),                                                                      these are the project details @VisualMicro

Lastly, when I had 9600 as my baud rate in the code it didn't work.

Please edit your question and put the code and additional details there, not in the comments.


text:
Arduino microphone
I have an arduino schematic from here
http://www.arduino-hacks.com/arduino-vu-meter-lm386electret-microphone-condenser/
I have a problem, the output of the circuit (the pin which is going to connect to the analog pin of the Arduino), from what I have measured has 4.5 V (I think it is a bit high). If I print on the serial it gives me something like 827, 826. However when I clap my hands near the microphone or put music on, the data that I get doesn't change a lot (like 1 -2 units). Should I worry about the schematic or about my microphone?
EDIT:
  After I rebuilt the circuit and when playing a song at a medium volume, I get values like this: 419-670. I think it is working, though I would like more opinions about these values (the output voltage is now around 3.20 V).

Have you tweaked the potentiometer?

yes I have tweaked the potentiometer.Now after I rebuilt the circuit(correctly hopefully) it shows an output of aprox .3 20 V and the values I get on the Serial monitor varies like this (when playing a song on a medium volume): 419 -656 .I think I got it working though I would like more opinions regarding these values.Thank you for your reply I will edit the post.

The schematic seems to have both inputs of the opamp at 0V (the one connected to the microphone would actually swing a small amount ±). The opamp also seems to be running open loop, with no feedback and would have a very high gain.
This is poor circuit design, ideally the inputs should be biassed at Vcc/2. At best the output would be severely distorted.
I suggest you search for a more suitable circuit.

Actually, the LM386 is an audio amplifier, not an op-amp.  It doesn't behave the same way.  It is perfectly valid to wire it as shown in the link above - indeed, that is pretty much identical to some of the example circuits in the datasheet from TI.  With minimum parts like that you get a gain of 20.

What I would be more concerned about is the lack of any current limiting resistors on the LEDs... Those poor IO pins...