text:
Can someone check my code? My Arduino isn't doing a consistent count cycle
I'm wondering if someone could have a look at my code and let me know if there's something wrong with it. I had the code done for me a while back and did a quick test and it seemed to work. I have now built a pneumatic machine for it to work on, and it's doing some strange things.
The first relay turns on and off a pneumatic solenoid, this is connected to a small pneumatic cylinder, it moves in and out. This cylinder causes a pneumatic feeder to activate and move back and forth also.
The feeder has a proximity sensor attached which lights up when the feeder is in its resting position.
The solenoid turns on for approx half a second and then back off again, this pushes the small cylinder out then back in. This sends the feeder forward, it then turns around and comes back toward its resting position.
The Arduino waits for the signal from the proximity sensor to tell it that the feeder is back in its resting position before doing it again.
It then repeats this sub cycle about 20 times.
After 20 sub cycles, the Arduino turns on the second relay for about a second, before turning it back off again.
It then does this whole complete cycle 20 times before stopping.
There's a momentary switch as well, which when pushed, is supposed to restart everything again.
It almost works, the closest i have had is where it was doing the cycles but counting them wrong. i changed the subcycle to 16 instead of 20 and it would count somewhere between 10 and 16. it seems to count different each time.
I just bought a new board and tried again, but now it counts to about five subcycles and then jumps the gun and doesn't wait for the signal from the proximity sensor before doing the next sub cycle. So once again the count ends up wrong.
Any ideas what I could try?
int Relay_1 = 10;           //first Relay
int Relay_2 = 11;           //second Relay
int Prox_Input = 12;        //input signal from proximity sensor
int Switch_Input = 13;      //the switch

int Cycle_Number = 20;      //number of repeating number of "complete" cycle
int Sub_Cycle_Number = 20;  //number of repeating number of "sub" cycle
int Delay_Cycle = 1000;     //delay of the "Complete" Cycle in milleseconds
int Delay_Sub_Cycle = 500;  //delay of the "Sub" Cycle  in milliseconds

bool Button_Pushed = true ; //the state required for the button
int i, j;

void setup() {
  /*configurate the output relays to be begin "low"*/
  pinMode(Relay_1 , OUTPUT);
  digitalWrite(Relay_1, LOW);

  pinMode(Relay_2 , OUTPUT);
  digitalWrite(Relay_2 , LOW);
  /*===========================================================*/
  /*configurate the input switch and sensor*/
  pinMode(Prox_Input , INPUT);
  pinMode(Switch_Input , INPUT_PULLUP);
  /*===========================================================*/
  /*configurate Serial port if you want it*/
  Serial.begin(9600);
  /*===========================================================*/
}

void loop() {
  if (Check_Button() == Button_Pushed) { //check the button
    for (i = 1 ; i <= Cycle_Number ; i++) { //the loop of the "complete" Cycle
      for (j = 1 ; j <= Sub_Cycle_Number ; j++) { //the loop of the "sub" Cycle
        digitalWrite(Relay_1 , HIGH);
        delay(Delay_Sub_Cycle);
        digitalWrite(Relay_1 , LOW);
        while (digitalRead(Prox_Input) == HIGH) {} // waiting the sensor signal
      }
      digitalWrite(Relay_2 , HIGH);
      delay(Delay_Sub_Cycle);
      digitalWrite(Relay_2 , LOW);
      delay(Delay_Cycle);
    }
  }
}

bool Check_Button()  {
  int Reading_1;
  int Reading_2;

  Reading_1 = digitalRead(Switch_Input);
  delay(20);
  Reading_2 = digitalRead(Switch_Input);
  if ((Reading_1 == 1) && (Reading_2 == 1))
    return true;
  else
    return false;
}

please be specific about the problem. try adding some delay in your sub cycle loop.

6V isn’t really enough to put on that barrel jack.  You really need at least 7.5V because of the voltage drop across the regulator.  If you want to use 6V battery then get a switching regulator to make 5V and feed it into the 5V pin instead.

Your fuzzy picture is missing a lot of critical information that would normally be on a schematic. Links to technical information on all the hardware devices would help, azon links are normally sales info and are useless for technical information. I agree with using Vin because of the extra filtering but you need to supply it with at 7.5 or more volts as mentioned by Delta_G If I were to take a SWAG you either have input bounce and/or power supply instability and or failure.

The only reason it might "jump the gun" would be this line:

         while(digitalRead(Prox_Input) == HIGH){}          // waiting the sensor signal

I suggest you check for a transition, that is, make sure the proximity switch has become LOW, and then wait for it to become HIGH again. So for example, if sending HIGH to the relay should make the proximity sensor read LOW, then put a loop in to make sure it does that, before proceeding.


text:
Why is IF statement executing on itself
x = 5;
Serial.println (x);

if (x == 0);
    {
      //stuff in this IF keeps happening why ?
      //Iam too stupid ?
    }

the if statement must be executed to evaluate the condition. if the condition is true the following command or block of commands is executed. your command after the if is ; (empty command)

You have a rogue semi-colon.
Splitting your code up on the end of statements you get:
1. x = 5;
2. Serial.println (x);
3. if (x == 0);
4. { // stuff }

With the semi-colon after the if it terminates the if before the opening block {, and that block becomes a completely separate statement detached from the if.

Yeah, most of us have been bitten by this one. I wish C/C++ compilers would flag this if (condition); form with a warning as it is very likely a mistake, and is certainly bad coding practice even if intentional. (Same for if (a=b). Valid, but bad practice.)

@DuncanC They can. GCC has the flag -Wempty-body: "Warn if an empty body occurs in an "if", "else" or "do while" statement.  This warning is also enabled by -Wextra."

It should be on by default.

Hell, I'd even argue it should be flagged as an error. Anybody who deliberately writes a "side-effect only" if statement should be shot. :)

You can turn it on in preferences in the Aduino IDE.  /home/matt/Arduino/sketch_mar30a/sketch_mar30a.ino:5:14: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]

source: Stack Exchange

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

sort: votes


text:
Problem using 74HC595 with ULN2803A as LED driver
For a final project I'm making a word clock using three 74HC595 registers and three ULN2803A transistor arrays as led drivers, as well as a DS1307 RTC.
The program works great, except for one large problem. While chips 2 and 3 work correctly, the outputs of the first chip are always lit.
I've tried several different programs online, I've done a lot of research and I just couldn't find the answer.

The code:
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>

#define BUTTON_HOUR 8
#define BUTTON_MINUTE 7
#define DATA 2                    // digital 2 to pin 14 on the 74HC595
#define LATCH 3                   // digital 3 to pin 12 on the 74HC595
#define CLOCK 4                   // digital 4 to pin 11 on the 74HC595

// Variables will change:
int buttonStateHOUR = 0;          // current state of the button
int buttonStateMINUTE = 0;        // current state of the button
int lastButtonStateHOUR = 0;      // previous state of the button
int lastButtonStateMINUTE = 0;    // previous state of the button

byte registerByte1 = 0;           // 0 IT IS | 1 FIVE  | 2 EIGHT | 3 QUARTER | 4 THREE  | 5 TEN | 6 MINUTES  | 7 TWENTY
byte registerByte2 = 0;           // 0 TO    | 1 PAST  | 2 HALF | 3 FIVE    | 4 ONE   | 5 NINE | 6 TWO | 7 THREE
byte registerByte3 = 0;           // 0 FOUR   | 1 SIX | 2 EIGHT| 3 SEVEN  | 4 TWELVE | 5 TEN | 6 ELEVEN  | 7 O'CLOCK

tmElements_t tm;

void setup()
{
  // ***********************************
  Serial.begin(9600);
  while (!Serial) ; // wait for serial
  delay(200);
  Serial.println("DS1307RTC Read Test");
  Serial.println("-------------------");
  // ***********************************

  // Buttons
  pinMode(BUTTON_HOUR, INPUT);
  pinMode(BUTTON_MINUTE, INPUT);

  // Shift Register
  pinMode(LATCH, OUTPUT);
  pinMode(CLOCK, OUTPUT);
  pinMode(DATA, OUTPUT);
}

void loop()
{
  // read the pushbutton input pin:
  buttonStateHOUR = digitalRead(BUTTON_HOUR);
  buttonStateMINUTE  = digitalRead(BUTTON_MINUTE);

  // Detect HOUR Button
  if (buttonStateHOUR != lastButtonStateHOUR) {
    if (buttonStateHOUR == HIGH) {
      addTime(1,0);
    }
    lastButtonStateHOUR = buttonStateHOUR;
  }
  // Detect MINUTE Button
  if (buttonStateMINUTE != lastButtonStateMINUTE) {
    if (buttonStateMINUTE == HIGH) {
      addTime(0,1);
    }
    lastButtonStateMINUTE = buttonStateMINUTE;
  }

  // Generate time and shiftOut
  timeToBytes();
  updateShiftRegisters();
  printTime();
}

void timeToBytes()
{
  if (RTC.read(tm)) {
    int deutschHour = shortHour(tm.Hour);
    int halb = 0;
    registerByte1 = 0;
    registerByte2 = 0;
    registerByte3 = 0;
    bitSet(registerByte1,0);    // "ES IST"

    if (tm.Minute >= 0 && tm.Minute <= 5) {
      bitSet(registerByte1,1);    // "FIVE"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,1);    // "PAST"
    } else if (tm.Minute >= 10 && tm.Minute <= 19) {
      bitSet(registerByte1,5);    // "TEN"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,1);    // "PAST"
    } else if (tm.Minute >= 20 && tm.Minute <= 24) {
      bitSet(registerByte1,7);    // "TWENTY"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,1);    // "PAST"
    } else if (tm.Minute >= 25 && tm.Minute <= 29) {
      bitSet(registerByte1,7);    // "TWENTY"
      bitSet(registerByte1,1);    // "FIVE"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,1);    // "PAST"
      halb = 1;
    } else if (tm.Minute >= 30 && tm.Minute <= 34) {
      bitSet(registerByte2,2);    // "HALF"
      bitSet(registerByte2,1);    // "PAST"
      halb = 1;
    } else if (tm.Minute >= 35 && tm.Minute <= 39) {
      bitSet(registerByte1,7);    // "TWENTY"
      bitSet(registerByte1,1);    // "FIVE"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,0);    // "TO"
      halb = 1;
    } else if (tm.Minute >= 40 && tm.Minute <= 49)  {
      bitSet(registerByte1,3);    // "QUARTER"
      bitSet(registerByte2,0);    // "TO"
      halb = 1;
    } else if (tm.Minute >= 50 && tm.Minute <= 54) {
      bitSet(registerByte1,5);    // "TEN"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,0);    // "TO"
      halb = 1;
    } else if (tm.Minute >= 55 && tm.Minute <= 59) {
      bitSet(registerByte1,1);    // "FIVE"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,0);    // "TO"
      halb = 1;
    }

    deutschHour = shortHour( deutschHour + halb);
    if ( deutschHour == 1 ) {
      bitSet(registerByte2,4);    // "ONE"
    } else if ( deutschHour == 2 ) {
      bitSet(registerByte2,6);    // "TWO"
    } else if ( deutschHour == 3 ) {
      bitSet(registerByte2,7);    // "THREE"
    } else if ( deutschHour == 4 ) {
      bitSet(registerByte3,0);    // "FOUR"
    } else if ( deutschHour == 5 ) {
      bitSet(registerByte2,3);    // "FIVE"
    } else if ( deutschHour == 6 ) {
      bitSet(registerByte3,1);    // "SIX"
    } else if ( deutschHour == 7 ) {
      bitSet(registerByte3,3);    // "SEVEN"
    } else if ( deutschHour == 8 ) {
      bitSet(registerByte3,2);    // "EIGHT"
    } else if ( deutschHour == 9 ) {
      bitSet(registerByte2,5);    // "NINE"
    } else if ( deutschHour == 10 ) {
      bitSet(registerByte3,5);    // "TEN"
    } else if ( deutschHour == 11 ) {
      bitSet(registerByte3,6);    // "ELEVEN"
    } else if ( deutschHour == 12 ) {
      bitSet(registerByte3,4);    // "TWELVE"
    }
    bitSet(registerByte3,7);    // "UHR"
  }
}

void updateShiftRegisters()
{
   digitalWrite(LATCH, LOW);
   shiftOut(DATA, CLOCK, MSBFIRST, registerByte3);
   shiftOut(DATA, CLOCK, MSBFIRST, registerByte2);
   shiftOut(DATA, CLOCK, MSBFIRST, registerByte1);
   digitalWrite(LATCH, HIGH);
}

void addTime(int addHour, int addMinute)
{
  // get time from RTC
  if (RTC.read(tm)) {

    if (addHour > 0) {
      tm.Hour = tm.Hour + addHour;
      if (tm.Hour > 12) {
        tm.Hour = tm.Hour - 12;
      }
    }

    if (addMinute > 0) {
      tm.Minute = tm.Minute + addMinute;
      if (tm.Minute > 59) {
        tm.Minute = tm.Minute - 60;
        addTime(1,0);
      }
    }

    tm.Second = 0;
    RTC.write(tm);
  }
}

int shortHour(int tempHour)
{
  tempHour = tempHour % 12;
  return tempHour == 0 ? 12 : tempHour;
}

void printTime() {

  if (RTC.read(tm)) {
    Serial.print("Ok, Time = ");
    print2digits(tm.Hour);
    Serial.write(':');
    print2digits(tm.Minute);
    Serial.write(':');
    print2digits(tm.Second);
    Serial.print(", Date (D/M/Y) = ");
    Serial.print(tm.Day);
    Serial.write('/');
    Serial.print(tm.Month);
    Serial.write('/');
    Serial.print(tmYearToCalendar(tm.Year));
    Serial.println();
    Serial.print("registerByte3 = ");
    Serial.print(registerByte3, BIN);
    Serial.println();
    Serial.print("registerByte2 = ");
    Serial.print(registerByte2, BIN);
    Serial.println();
    Serial.print("registerByte1 = ");
    Serial.print(registerByte1, BIN);
    Serial.println();
  } else {
    if (RTC.chipPresent()) {
      Serial.println("The DS1307 is stopped.  Please run the SetTime");
      Serial.println("example to initialize the time and begin running.");
      Serial.println();
    } else {
      Serial.println("DS1307 read error!  Please check the circuitry.");
      Serial.println();
    }
    delay(9000);
  }
  delay(1000);
}

void print2digits(int number) {
  if (number >= 0 && number < 10) {
    Serial.write('0');
  }
  Serial.print(number);
}

Do you use a breadboard? Perhaps it is a bad connection. Did you solder it? perhaps there is a solder splat between two pins. Check the wiring, and try to  replace the bad 74hc595. Do you have a logic analyzer? If not, you can try to add delays and measure the signals with a voltagemeter.

I'm using a breadboard. I did try switching them around, and the problem is still there. I actually did buy three new registers, and I switched them around, the problem is still there. Sadly I'm not knowledgeable enough for the last 2 steps you mentioned. One thing to add is, on that first chip, the pins which are supposed to light up are brighter than the ones that arent supposed to.

Check the gnd of that 74hc595. Try to add another gnd wire or move that 74hc595 to a different location on the breadboard. Could you make a photo of it? This site is for questions and answers, you mention that the pins that are supposed to light up are brighter, please add that to your question, it is important information.

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


text:
Arduino WiFi Rev2 JSON String
I have been trying to use the WifiNINA library to access the JSON output from the following API using the WifiNINA library and the Arduino Wifi Rev2.
This is the code that I have been using (it is an edited example form the library):
/*
  Web client

 This sketch connects to a website (https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo)
 using the WiFi module.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 Circuit:
 * Board with NINA module (Arduino MKR WiFi 1010, MKR VIDOR 4000 and UNO WiFi Rev.2)

 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 */

#include <SPI.h>
#include <WiFiNINA.h>

#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.alphavantage.co";    // name address for Google (using DNS)

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();

  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET /query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo HTTP/1.1");
    client.println("Host: https://www.alphavantage.co");
    client.println("Connection: close");
    client.println();
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

However, when I run the library, all that the serial monitor returns is:
Attempting to connect to SSID: HIDDEN
Connected to wifi
SSID: HIDDEN
IP Address: HIDDEN
signal strength (RSSI):-40 dBm

Starting connection to server...
connected to server
HTTP/1.1 301 Moved Permanently
Connection: close
Server: gunicorn/19.7.0
Date: Sun, 07 Apr 2019 15:02:16 GMT
Transfer-Encoding: chunked
Location: https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&outputsize=full&datatype=json&apikey=8UV48KKJJM1JW700
Content-Type: text/html; charset=utf-8
Via: 1.1 vegur

0

disconnecting from server.

I would like the code to return the string from the link. The output should like this (instead of just the 0). I had to shorten the example output below because of size restraints, but it should be the full webpage.
{
    "Meta Data": {
        "1. Information": "Intraday (5min) open, high, low, close prices and volume",
        "2. Symbol": "MSFT",
        "3. Last Refreshed": "2019-04-05 16:00:00",
        "4. Interval": "5min",
        "5. Output Size": "Compact",
        "6. Time Zone": "US/Eastern"
    },
    "Time Series (5min)": {
        "2019-04-05 16:00:00": {
            "1. open": "119.8100",
            "2. high": "119.9100",
            "3. low": "119.7350",
            "4. close": "119.8800",
            "5. volume": "728814"
        },
        "2019-04-05 15:55:00": {
            "1. open": "119.9200",
            "2. high": "119.9200",
            "3. low": "119.7800",
            "4. close": "119.8000",
            "5. volume": "307126"
        },
        "2019-04-05 15:50:00": {
            "1. open": "119.9300",
            "2. high": "119.9300",
            "3. low": "119.8800",
            "4. close": "119.9200",
            "5. volume": "235238"
        }
    }
}

And if you use the redirected URL instead...?

@Majenko Thanks for your your suggestion. I just checked, and the url that is claimed as the destination (https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&outputsize=full&datatype=json&apikey=8UV48KKJJM1JW700) is the final destination. It does not redirect.

But that is not the URL you are using. You use URL A. The website sends you a redirect message (301) with URL B. You then need to take the Location: header and do a GET of that new URL. Basically it's filling in the missing default parameters for you and handing you a full URL to use. If you just use that new URL instead of your current one (i.e., add all the missing parameters) then it should work.

Thank you again. I just edited the URL that the Arduino uses to (https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&outputsize=compact&datatype=json&apikey=8UV48KKJJM1JW700), and it is coming up with the same output on the serial monitor (with the new destination).

It's not that the API is incompatible with the Arduino, it's that the Arduino Firmware update tool used to add the required SSL certificate to the wifi module fails to do so because the SSL certificate for www.alphavantage.co does not exist at their domain.
This can be verified by:
openssl s_client -showcerts -connect www.alphavantage.co:443

I don't understand your answer. Web browsers don't have a security problem with this site. and your command returns public certificates of the site

The target site uses HTTPS. If you connect to port 80, it redirects to HTTPS on port 443.
Use the WiFiSSLClient of the library. See the WiFiSSLClient example. Basically it is same as the example you used. There are two differences. It uses WiFiSSLClient instead of WiFiClient and connects to standard https port 443.

Thanks for the suggestion. I just tried making the edit, and this is what came up in the serial monitor:               Attempting to connect to SSID: BLOCKED
Connected to wifi
SSID: BLOCKED
IP Address: BLOCKED
signal strength (RSSI):-46 dBm
        Starting connection to server...

        disconnecting from server.

not a problem until it doesn't connect, but it should be client.println("Host: www.alphavantage.co"); without https://

I just made that change too, and it still does not work.

do you have the latest version of the firmware and library?

Thank you for the help, but after further investigation, I have discovered that this specific API is not compatible with Arduino.

Arduino can process JSON


text:
Error Downloading http://downloads.arduino.cc/packages/packages_index.json
I managed to update the library but getting error "Error Downloading http://downloads.arduino.cc/packages/packages_index.json" when updating the Board Manager. I switched the proxy to no proxy instead of automatic. Anyone can help me?

use your computer web browser to see if the URL is valid

The URL is wrong, and should read:
https://downloads.arduino.cc/packages/package_index.json

Note that "package_index" is in the singular, not the plural.
Check what you have in the "Additional Boards Manager URLs:" section of Preferences.

I had the same issue and the fix that worked for me is to directing the jvm to use the Windows Certificate Store instead of the ancient cacerts file that comes with java 1.8. This may also help people behind a Cisco Umbrella filter.
One does this by adding the following lines to "C:\Program Files (x86)\Arduino\arduino.l4j.ini" (note, you will need to open a text editor as an administrator, then open the file in question, in order to edit it):
-Djavax.net.ssl.trustStore=NUL
-Djavax.net.ssl.trustStoreType=Windows-ROOT

I found this answer here


text:
Slow speed with stepping motor
I am currently working on a project where I need a stepping motor and a servo running at the same time, the servo turns fine and the speed is ok, but the stepping motors speed is very slow and as a result it is loud. I tried the code for the stepping motor on its own and it runs faster, but when it is ran with the servo it is slow. I have follwed a few tutorials to get this to the stage it is at currently, I have removed any delays that i could find which did help a little, but it is still not enough.
The servo is powered from the arduino and the stepping motor is powered by a 12v plug. I am just not sure if there is something within this code that is causing it to slow down? Thank you for you time! The code that it is running slow from is here:

#include <Servo.h>

Servo myservo;

// Configurable Variables
int MaxServoTurn = 20;

// Spooky Variables
int pos = 0;
int customDelay;
int customDelayMapped;
const int pin_LED = 10;
const int pin_switch = 8;
const int stepPin = 3;
const int dirPin = 4;
boolean oldSwitchState = LOW;
boolean newSwitchState1 = LOW;
boolean newSwitchState2 = LOW;
boolean newSwitchState3 = LOW;
unsigned long timeNow = 0;
unsigned long timePrev = 0;
unsigned int timeWait = 100;
boolean flashingLEDisON = false;
boolean LEDstatus = LOW;
boolean keyPressed = false;
boolean buttonToggle = false;

// Setup only, call functions in here
void setup() {
  myservo.attach(9);
  //Sets the two pins as Outputs
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  //Enables the motor to move in a particular direction
  digitalWrite(dirPin, HIGH);
  pinMode(pin_LED, OUTPUT);
  digitalWrite(pin_LED, LOW);
  pinMode(pin_switch, INPUT);
}

// This is the main controller for the application
void loop() {
  for (pos = 0; pos <= MaxServoTurn; pos += 1) {
    buttonLoop();
    if (buttonToggle == true) {
      myservo.write(pos);
      setupPotentiometer();
    }
  }
  for (pos = MaxServoTurn; pos >= 0; pos -= 1) {
    buttonLoop();
    if (buttonToggle == true) {
      myservo.write(pos);
      setupPotentiometer();
    }
  }
}

void buttonLoop() {
  newSwitchState1 = digitalRead(pin_switch);
  newSwitchState2 = digitalRead(pin_switch);

  newSwitchState3 = digitalRead(pin_switch);

  if (  (newSwitchState1 == newSwitchState2) && (newSwitchState1 == newSwitchState3) )
  {
    if ( newSwitchState1 != oldSwitchState )
    {
      if ( newSwitchState1 == HIGH ) {
        keyPressed = true;
        buttonToggle = true;
      } else {
        keyPressed =  false;
        buttonToggle = false;
      }
      oldSwitchState = newSwitchState1;
    }
  }

  if ( keyPressed )
  {
    // turn on or turn off the blinking LED
    if ( flashingLEDisON == false)
    {
      flashingLEDisON = true;
    }
    else
    {
      flashingLEDisON = false;
      // the LED may be on so to be safe we turn it off. If you wished you could check LEDstatus
      LEDstatus = LOW;  digitalWrite(pin_LED, LEDstatus);
    }
    keyPressed = false;
  }

  // if the blinking LED is on. See if it is time to blink it
  if ( flashingLEDisON == true )
  {
    timeNow = millis();
    if (timeNow - timePrev >= timeWait )
    {
      timePrev = timeNow;
      if (LEDstatus == LOW) {
        LEDstatus = HIGH;
      } else {
        LEDstatus = LOW;
      }
      digitalWrite(pin_LED, LEDstatus);
    }
  }
}

void setupPotentiometer() {
  customDelayMapped = speedUp(); // Gets custom delay values from the custom speedUp function
  // Makes pules with custom delay, depending on the Potentiometer, from which the speed of the motor depends
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(customDelayMapped);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(customDelayMapped);
}

// Function for reading the Potentiometer
int speedUp() {
  int customDelay = analogRead(A0); // Reads the potentiometer
  int newCustom = map(customDelay, 0, 1023, 300, 4000); // Convrests the read values of the potentiometer from 0 to 1023 into desireded delay values (300 to 4000)
  return newCustom;
}

I had a project where I needed to run two steppers at the same time as they were moving a heavy load and were moving the same piece.
While a servo is going to move the desired spot, a stepper will not.
In the process of setting up the stepper you designated steps per rev and amount of steps to take at a time.
The stepper is only going to move the "amount of steps" at a time for each run of the code. I ran into a similar  problem and I had to put in a 2ms delay after the servo run command to make the motors run smoother and faster, other wise it sounded like a bunch of gears gnashing and skipping.  These steppers were facing each other that is why they move opposite directions.

if (down==true){
  TLstep.step(-step1);
  TRstep.step(step1);
  delay(2);
}

I know it been a year since this was looked at. Hope you got your issue figured out.

A stepper motor requires that you send pulsed control signals to it for each step. If you want it to run at a given number of steps/second, you have to send the controlling pulses at the correct time intervals.
If you have delays in your code, it will slow down the timing of the control pulses, and slow down your steppers. You need to rewrite your code to use millis() to calculate the timing of your control signals instead of using delay() or delayMicroseconds()

Thank you for your reply Duncan, do I just change the two delayMicroseconds(customDelayMapped); to millis() as you mentioned? I’m pretty new to the arduino so I’m sorry if I’m misunderstanding this!

no, you need to refactor your code to keep track of elapsed time and change states when the desired time interval has passed. Do a search on "Arduino Blink Without Delay" and study the sketches you find. It won't be a copy/paste change but rather a refactoring of your code. You might be able to find sample code for steppers and servos that doesn't use delays, which would make your job easier.


text:
Arduino HTTP post image to external server
I'm trying to send an image from SPIFFS to my external server. When pictures are taken, they are saved into "/pics/" directory within SPIFFS. Ultimately, I'd like to post all the images saved onto "/pics/x.jpg" (x is the a number in increasing order - 7.jpg, 8.jpg, 9.jpg, etc...) to my external server as they come in. Currently, I can access all the images within the internal esp server. Right now, I'm trying to send a single image, "6.jpg" from "/pics/" to my external server. Unfortunately, I'm not seeing anything on the external server side. The http post code occurs in "void setup()".
The complete Arduino code is below:

// Program header files
#include <Wire.h>
#include <WiFi.h>
#include <WebServer.h>
#include <ArduCAM.h>
#include <SPI.h>
#include "FS.h"
#include "SPIFFS.h"
#include "memorysaver.h"

#define AP_SSID "apssid"
#define AP_PASSWORD "password"

#define WIFI_SSID "wifissid"
#define WIFI_PASSWORD "password"

#if !(defined (OV2640_MINI_2MP)||defined (OV5640_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP_PLUS) \
    || defined (OV5642_MINI_5MP) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) \
    ||(defined (ARDUCAM_SHIELD_V2) && (defined (OV2640_CAM) || defined (OV5640_CAM) || defined (OV5642_CAM))))
#error Please select the hardware platform and camera module in the ../libraries/ArduCAM/memorysaver.h file
#endif

const int ArduCAM_Power = 32; // Controls power for ArduCAM

const int CS = 5; // GPIO5 as Slave Select for ArduCAM
int wifiType = 0; // 0: Station    1: AP

static const size_t bufferSize = 2048;
static uint8_t buffer[bufferSize] = {0xFF};
static const int fileSpaceOffset = 700000;

byte buf[256];
static int i = 0;
static int k = 0;
uint8_t temp = 0, temp_last = 0;
uint32_t len = 0;
bool is_header = false;

const String fName = "/res.txt"; // Whatever last resolution that was submitted, will be stored in the file
                                // If power goes out, it will use the last setting stored onto that file
int fileTotalKB = 0;
int fileUsedKB = 0;
int fileCount = 0;
String errMsg = "";
int imgMode = 1; // 0: stream    1: capture
int resolution = 3;
// resolutions:
// 0 = 160x120
// 1 = 176x144
// 2 = 320x240
// 3 = 352x288
// 4 = 640x480
// 5 = 800x600
// 6 = 1024x768
// 7 = 1280x1024
// 8 = 1600x1200

WiFiClient client;

WebServer server(80);

#if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
ArduCAM myCAM(OV2640, CS);
#endif

void start_capture()
{
  myCAM.clear_fifo_flag();
  myCAM.start_capture();
}

// Updates properties file with resolution
void updateDataFile()
{

  File f = SPIFFS.open(fName, FILE_WRITE);
  if(!f)
  {
    Serial.println("Property file failed to open");
  }
  else
  {
    Serial.println("========= Writing to Property file =========");

    f.println(resolution);
    Serial.println("Data file updated");
    f.close();
  }

}

void myCAMsaveToSPIFFS()
{
  // Reserves space when memory is full
  if((fileTotalKB - fileUsedKB) < fileSpaceOffset)
  {
    String maxStr = "========= Maximum Data Storage Reached =========";
    Serial.println(maxStr);
    errMsg = maxStr;
    return;
  }

  String str;

  // Flush the FIFO
  myCAM.flush_fifo();
  // Clear capture done flag
  myCAM.clear_fifo_flag();
  // Start capture
  myCAM.start_capture();

  Serial.println("Start capture.");
  while(!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));
  Serial.println("Capture done!");

  // Increase file count since a capture was done
  fileCount++;

  len = myCAM.read_fifo_length();
  Serial.print("The FIFO length is: ");
  Serial.println(len, DEC);

  if(len >= MAX_FIFO_SIZE) // 8M
  {
    Serial.println("Over size!");
  }
  if(len == 0) // 0 KB
  {
    Serial.println("Size is 0 KB.");
  }

  str = "/pics/" + String(fileCount) + ".jpg";

  File f = SPIFFS.open(str, FILE_WRITE);
  if(!f)
  {
    Serial.println("Property file failed to open");
  }
  else
  {
    Serial.println(str);
  }

  i = 0;
  myCAM.CS_LOW();
  myCAM.set_fifo_burst();
  while (len--)
  {
    temp_last = temp;
    temp =  SPI.transfer(0x00);
    //Read JPEG data from FIFO
    if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
    {
      buf[i++] = temp;  //save the last  0XD9
      //Write the remain bytes in the buffer
      myCAM.CS_HIGH();
      f.write(buf, i);
      //Close the file
      f.close();
      Serial.println("CAM Save done!");
      is_header = false;
      i = 0;
    }
    if (is_header == true)
    {
      //Write image data to buffer if not full
      if (i < 256)
        buf[i++] = temp;
      else
      {
        //Write 256 bytes image data to file
        myCAM.CS_HIGH();
        f.write(buf, 256);
        i = 0;
        buf[i++] = temp;
        myCAM.CS_LOW();
        myCAM.set_fifo_burst();
      }
    }
    else if ((temp == 0xD8) & (temp_last == 0xFF))
    {
      is_header = true;
      buf[i++] = temp_last;
      buf[i++] = temp;
    }
  }

}

//////////////////////////////////////////////////////////////////////////////////////////////////
//    Retrieves a stored jpg file and sends to browser based on url: http://IPaddress/1.jpg     //
//////////////////////////////////////////////////////////////////////////////////////////////////
bool loadFromSPIFFS(String path)
{
  String dataType = "text/plain";
  if(path.endsWith("/"))
  {
    path += "index.htm";
  }

  if(path.endsWith(".src"))
  {
    path = path.substring(0, path.lastIndexOf("."));
  }
  else if(path.endsWith(".jpg"))
  {
    dataType = "image/jpeg";
  }

  File dataFile = SPIFFS.open(path.c_str(), FILE_READ);
  if(server.hasArg("download"))
  {
    dataType = "application/octect-stream";
  }

  if(server.streamFile(dataFile, dataType) != dataFile.size())
  {

  }

  dataFile.close();
  return true;
}

/////////////////////////////////////////////////////////////
//  sets the HTML used for the resoultions drop down       //
/////////////////////////////////////////////////////////////
String getDropDown()
{
  String webString = "";
  webString += "<select name=\"rez\">\n";
  webString += "   <option value\"0\"  ";

  if (resolution == 0)
    webString += " selected=\"seleted\" ";
  webString += ">160x120</option>\n";

  webString += "   <option value=\"1\" ";
  if (resolution == 1)
    webString += " selected=\"seleted\" ";
  webString += ">176x144</option>\n";

  webString += "   <option value=\"2\" ";
  if (resolution == 2)
    webString += " selected=\"seleted\" ";
  webString += ">320x240</option>\n";

  webString += "   <option value=\"3\" ";
  if (resolution == 3)
    webString += " selected=\"seleted\" ";
  webString += ">352x288</option>\n";

  webString += "   <option value=\"4\" ";
  if (resolution == 4)
    webString += " selected=\"seleted\" ";
  webString += ">640x480</option>\n";

  webString += "   <option value=\"5\" ";
  if (resolution == 5)
    webString += " selected=\"seleted\" ";
  webString += ">800x600</option>\n";

  webString += "   <option value=\"6\" ";
  if (resolution == 6)
    webString += " selected=\"seleted\" ";
  webString += ">1024x768</option>\n";

  webString += "   <option value=\"7\" ";
  if (resolution == 7)
    webString += " selected=\"seleted\" ";
  webString += ">1280x1024</option>\n";

  webString += "   <option value=\"8\" ";
  if (resolution == 8)
    webString += " selected=\"seleted\" ";
  webString += ">1600x1200</option>\n";

  webString += "  </select>\n";

  return webString;
}

void camCapture(ArduCAM myCAM)
{
  WiFiClient client = server.client();

  len  = myCAM.read_fifo_length();
  if (len >= MAX_FIFO_SIZE) // 8M
  {
    Serial.println("Over size.");
  }
  if (len == 0 ) // 0KB
  {
    Serial.println("Size is 0.");
  }

  myCAM.CS_LOW();
  myCAM.set_fifo_burst();

  if (!client.connected()) return;

  i = 0;
  while ( len-- )
  {
    temp_last = temp;
    temp =  SPI.transfer(0x00);
    //Read JPEG data from FIFO
    if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
    {
      buffer[i++] = temp;  //save the last  0XD9
      //Write the remain bytes in the buffer
      if (!client.connected()) break;
      client.write(&buffer[0], i);
      is_header = false;
      i = 0;
      myCAM.CS_HIGH();
      break;
    }
    if (is_header == true)
    {
      //Write image data to buffer if not full
      if (i < bufferSize)
      {
      buffer[i++] = temp;
      }
    else
    {
      //Write bufferSize bytes image data to file
      if (!client.connected()) break;
      client.write(&buffer[0], bufferSize);
      i = 0;
      buffer[i++] = temp;
    }
    }
    else if ((temp == 0xD8) & (temp_last == 0xFF))
    {
      is_header = true;
      buffer[i++] = temp_last;
      buffer[i++] = temp;
    }
  }
}

void serverCapture()
{
  delay(1000);
  start_capture();
  Serial.println("CAM Capturing");

  int total_time = 0;

  total_time = millis();
  while (!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));
  total_time = millis() - total_time;
  Serial.print("capture total_time used (in miliseconds):");
  Serial.println(total_time, DEC);

  total_time = 0;

  Serial.println(F("CAM Capture Done."));
  total_time = millis();
  camCapture(myCAM);
  total_time = millis() - total_time;
  Serial.print("send total_time used (in milliseconds): ");
  Serial.println(total_time, DEC);
  Serial.println("CAM send Done!");
}

void serverStream()
{
  WiFiClient client = server.client();

  String response = "HTTP/1.1 200 OK\r\n";
  response += "Content-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n";
  server.sendContent(response);

  while (1)
  {
    start_capture();
    while (!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));
    size_t len = myCAM.read_fifo_length();
    if (len >= MAX_FIFO_SIZE) // 8M
    {
      Serial.println(F("Over size."));
      continue;
    }
    if (len == 0 ) // 0 KB
    {
      Serial.println(F("Size is 0."));
      continue;
    }

    myCAM.CS_LOW();
    myCAM.set_fifo_burst();

    if (!client.connected()) break;
    response = "--frame\r\n";
    response += "Content-Type: image/jpeg\r\n\r\n";
    server.sendContent(response);

    while (len--)
    {
      temp_last = temp;
      temp =  SPI.transfer(0x00);

      //Read JPEG data from FIFO
      if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
      {
        buffer[i++] = temp;  //save the last  0XD9
        //Write the remain bytes in the buffer
        myCAM.CS_HIGH();;
        if (!client.connected()) break;
        client.write(&buffer[0], i);
        is_header = false;
        i = 0;
      }
      if (is_header == true)
      {
        //Write image data to buffer if not full
        if (i < bufferSize)
        {
          buffer[i++] = temp;
        }
        else
        {
          //Write bufferSize bytes image data to file
          myCAM.CS_HIGH();
          if (!client.connected()) break;
          client.write(&buffer[0], bufferSize);
          i = 0;
          buffer[i++] = temp;
          myCAM.CS_LOW();
          myCAM.set_fifo_burst();
        }
      }
      else if ((temp == 0xD8) & (temp_last == 0xFF))
      {
        is_header = true;
        buffer[i++] = temp_last;
        buffer[i++] = temp;
      }
    }
    if (!client.connected()) break;
  }
}

void handleNotFound()
{
  String ipAddr = WiFi.localIP().toString();
  if(wifiType == 1)
  {
    ipAddr = WiFi.softAPIP().toString();
  }

  Serial.print("Server URI: ");
  Serial.println(server.uri());

  if(server.uri().indexOf(".jpg") != -1)
  {
    loadFromSPIFFS(server.uri());
    return;
  }

  //// Default HTML
  String message = "\n";
  message += "\n";
  message += "<form action=\"http://" + ipAddr + "/submit\" method=\"POST\">";
  message += "
ESP32 Arducam Mini
\n";
  if (errMsg != "")
  {
    message += "
" + errMsg + "
";
  }

  if (imgMode == 0) // stream mode
  {
    message += "

Video Streaming

 \n";
    message += "

\n";
    imgMode = 1; // set back to capture mode so it doesn't get stuck in streaming mode

  }
  else
  {
    message += "
";
    message += getDropDown();

    message += " <input type=\"radio\" id=\"strm\" name=\"imgMode\" value=\"stream\" ";

    if (imgMode == 0)
    {
      message += " checked ";
    }
    message += "> Stream \n";

    message += " <input type=\"radio\" id=\"capt\" name=\"imgMode\" value=\"capture\"  ";
    if (imgMode == 1)
      message += " checked ";
    message += "> Capture \n";

    message += "  <input type='submit' value='Submit'  >\n";
    message += "    Refresh";
    message += "     Clear Data\n";

    message += "
\n";

    fileTotalKB = (int)SPIFFS.totalBytes();
    fileUsedKB = (int)SPIFFS.usedBytes();

    if (fileCount > 0)
    {
      int percentUsed = ((float)fileUsedKB / (float)(fileTotalKB - fileSpaceOffset)) * 100;
      String colorStr = "green";
      if (percentUsed > 90)
        colorStr = "red";

      message += "
";
      message += "
   space used: " + String(percentUsed) + "%
";
      message += "

\n";

    }

    message += "

";
    int colCnt = 0;
    for (int i = 1; i <= fileCount; i++)
    {
      message += "" + i + ".jpg	\n";

      colCnt++;
      if (colCnt >= 10) //  columns
      {
        message += "

";
        colCnt = 0;
      }
    }
    message += "

\n";

    //useful for debugging max data storage
      /*
        message += "

Total Bytes: 	";
        message += fileTotalKB;
        message += "

Used Bytes: 	";
        message += fileUsedKB;
        message += "

Remaing Bytes: 	";
        message += (fileTotalKB - fileUsedKB);
        message += "

\n";
      */
      /*
        float flashChipSize = (float)ESP.getFlashChipSize() / 1024.0 / 1024.0;
        message += "
chipSize: ";
        message += flashChipSize;
      */

      message += "

\n";

  }

  message += "</form> \n";
  message += "\n";

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

void setCamResolution(int reso)
{
  switch (reso)
  {
    case 0:
      myCAM.OV2640_set_JPEG_size(OV2640_160x120);
      resolution = 0;
      break;

    case 1:
      myCAM.OV2640_set_JPEG_size(OV2640_176x144);
      resolution = 1;
      break;

    case 2:
      myCAM.OV2640_set_JPEG_size(OV2640_320x240);
      resolution = 2;
      break;

    case 3:
      myCAM.OV2640_set_JPEG_size(OV2640_352x288);
      resolution = 3;
      break;

    case 4:
      myCAM.OV2640_set_JPEG_size(OV2640_640x480);
      resolution = 4;
      break;

    case 5:
      myCAM.OV2640_set_JPEG_size(OV2640_800x600);
      resolution = 5;
      break;

    case 6:
      myCAM.OV2640_set_JPEG_size(OV2640_1024x768);
      resolution = 6;
      break;

    case 7:
      myCAM.OV2640_set_JPEG_size(OV2640_1280x1024);
      resolution = 7;
      break;

    case 8:
      myCAM.OV2640_set_JPEG_size(OV2640_1600x1200);
      resolution = 8;
      break;

  }
}

void clearData()
{
  errMsg = "======  Data Storage Cleared =========";
  File dir = SPIFFS.open("/pics");
  while (dir.openNextFile())
  {
    SPIFFS.remove(dir.name());
  }

  fileCount = 0;
  fileTotalKB = 0;
  fileUsedKB = 0;

  handleNotFound();
}

void handleSubmit()
{
  errMsg = "";
  Serial.println( "--- Form Submited ---");
  Serial.println( "Server args " + server.args());

  if (server.args() > 0 )
  {
    for ( uint8_t i = 0; i < server.args(); i++ )
    {

      // can be useful to determine the values from a form post.
      Serial.println( "Server arg " + server.arg(i));
      Serial.println( "Server argName " + server.argName(i) );
      if (server.argName(i) == "imgMode")
      {
        Serial.println(" Image Mode: " + server.arg(i));

        if (server.arg(i) == "stream")
        {
          imgMode = 0;
        }
        else
        {
          imgMode = 1; // capture mode
        }
      }

      if (server.argName(i) == "rez")
      {

        if (server.arg(i).toInt() != resolution)
        {

          setCamResolution(server.arg(i).toInt());

          updateDataFile();

          //// IMPORTANT: removing or reducing the delay can result in dark images
          delay(1500); // add a delay to allow the white balance to adjust to new resolution
        }
      }
    }
  }

  if (imgMode == 1) // capture
  {
    myCAMsaveToSPIFFS();
  }

  handleNotFound();

}

void setup()
{
  SPIFFS.begin();
  delay(10);

  Wire.begin();
  Serial.begin(115200);
  SPI.begin();
  SPI.setFrequency(4000000); //4MHz
  pinMode(CS, OUTPUT);

  pinMode(ArduCAM_Power, OUTPUT);
  digitalWrite(ArduCAM_Power, HIGH);

  Serial.println();

  // Check for properties file
  File f = SPIFFS.open(fName, FILE_READ);

  if(!f)
  {
    // No file exists. Format and create properties file.
    Serial.println("Please wait for SPIFFS to be formatted.");

    SPIFFS.format();
    Serial.println("SPIFFS Formatted!");

    f = SPIFFS.open(fName, FILE_WRITE);
    if(!f)
    {
      Serial.println("Properties file failed to open.");
    }
    else
    {
      Serial.println("========= Writing to Property file =========");

      f.println(resolution);
      f.close();
    }
  }
  else
  {
    Serial.println("Properties file exists! Reading...");

    while(f.available())
    {
      String str = f.readStringUntil('\n');

      Serial.println(str);

      resolution = str.toInt();
    }

    f.close();
  }

  uint8_t vid, pid;
  uint8_t temp;

  while(1)
  {
    //Check if the ArduCAM SPI bus is OK
    myCAM.write_reg(ARDUCHIP_TEST1, 0x55);
    temp = myCAM.read_reg(ARDUCHIP_TEST1);
    if (temp != 0x55) {
      Serial.println(F("SPI interface Error!"));
      delay(2);
      continue;
    }
    else
      break;
  }

  #if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
  //Check if the camera module type is OV2640
  myCAM.wrSensorReg8_8(0xff, 0x01);
  myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
  myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
  if ((vid != 0x26 ) && (( pid != 0x41 ) || ( pid != 0x42 )))
    Serial.println(F("Can't find OV2640 module!"));
  else
    Serial.println(F("OV2640 detected."));
  #endif

  //Change to JPEG capture mode and initialize the OV2640 module
  myCAM.set_format(JPEG);
  myCAM.InitCAM();

  setCamResolution(resolution);
  myCAM.clear_fifo_flag();

  if (wifiType == 0)
  {
    if(!strcmp(WIFI_SSID,"SSID"))
    {
      Serial.println(F("Please set your SSID"));
      while(1);
    }
    if(!strcmp(WIFI_PASSWORD,"PASSWORD"))
    {
      Serial.println(F("Please set your PASSWORD"));
      while(1);
    }
    // Connect to WiFi network
    Serial.println();
    Serial.println();
    Serial.print(F("Connecting to "));
    Serial.println(WIFI_SSID);

    WiFi.mode(WIFI_STA);

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

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

    Serial.println(F("WiFi connected"));
    Serial.println("");
    Serial.println(WiFi.localIP());
  }
  else if (wifiType == 1)
  {
    Serial.println();
    Serial.println();
    Serial.print(F("Shared AP: "));
    Serial.println(AP_SSID);
    Serial.print(F("The password is: "));
    Serial.println(AP_PASSWORD);

    WiFi.mode(WIFI_AP);

    WiFi.softAP(AP_SSID, AP_PASSWORD);

    Serial.println();
    Serial.print("AP IP Address is: ");
    Serial.println(WiFi.softAPIP());
  }

  File normPicture = SPIFFS.open("/pics/6.jpg", FILE_READ);
  uint32_t jpgLen = normPicture.size();

  Serial.print("Sending image of ");
  Serial.print(jpgLen, DEC);
  Serial.println("bytes");

  // Prepare request
  String start_request = "";
  String end_request = "";
  start_request = start_request + "\n" + "--AaB03x" + "\n" + "Content-Type: image/jpeg" + "\n" + "Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"6.jpg\"\n" + "Content-Transfer-Encoding: binary\n\n";
  end_request = end_request + "\n--AaB03x--\n";
  uint32_t extra_length;
  extra_length = start_request.length() + normPicture.size() + end_request.length();
  //Serial.println("Extra length:");
  //Serial.println(extra_length);
  long leng = jpgLen + extra_length;

  // Connect to server
  Serial.println("Starting connection to external server!");
  if (client.connect("172.xx.xx.x", 80))
  {
    Serial.println("Connected");
    client.print("POST /www/upload.php HTTP/1.1");
    client.println("Host: 172.xx.xx.x" );
    client.println("Content-Type: multipart/form-data; boundary=AaB03x");
    client.print("Content-Length: ");
    client.println(extra_length);
    client.println();
    client.print(start_request);
    Serial.println("Connected1");

    while(normPicture.available())
    {
      client.write(normPicture.read());
    }

    Serial.println("END REQUEST");
    client.println(end_request);

  }
  else
  {
    Serial.println("Connection failed!");
  }

  // Setup handlers for internal server
  server.on("/capture", HTTP_GET, serverCapture);
  server.on("/stream", HTTP_GET, serverStream);
  server.on("/submit", handleSubmit);
  server.on("/clear", clearData);
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("Internal Server started");

  File dir = SPIFFS.open("/pics");
  while(dir.openNextFile())
  {
    fileCount++;
  }

  fileTotalKB = (int)SPIFFS.totalBytes();
  fileUsedKB = (int)SPIFFS.usedBytes();

}

void loop()
{
  server.handleClient();

  //delay(15000);
}

My php code (upload.php) is below:
<?php
if (!empty($_FILES) && isset($_FILES['fileToUpload'])) {
    switch ($_FILES['fileToUpload']["error"]) {
        case UPLOAD_ERR_OK:
            $target = "upload/";
            $target = $target . basename($_FILES['fileToUpload']['name']);

            if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target)) {
                $status = "The file " . basename($_FILES['fileToUpload']['name']) . " has been uploaded";
                $imageFileType = pathinfo($target, PATHINFO_EXTENSION);
                $check = getimagesize($target);
                if ($check !== false) {
                    echo "File is an image - " . $check["mime"] . ".
";
                    $uploadOk = 1;
                } else {
                    echo "File is not an image.
";
                    $uploadOk = 0;
                }

            } else {
                $status = "Sorry, there was a problem uploading your file.";
            }
            break;

    }

    echo "Status: {$status}
\n";

}
?>

I don't believe that I need any html code, since the php file receives the image and sends it to the "uploads/" folder in "www/uploads/" from my external server. My upload.php file is located in "www/".
UPDATE1: I believe my error is either the client headers, or when writing the image to send to the external server. I get an error 400 226 on the external server when trying to send the image. The 400 for a bad client request, and I believe the 226 is the amount of bytes sent/received.
Thanks!

you can do client.write(normPicture);

To get image on PHP Side using move_uploaded_file() you need to send them using a HTML Form with input like . So or you "simulate" such a form, or you send data directly. In that case, maybe the easiest way would be to have a folder on you remote server with a specific FTP acces to send data to it. Look for FTP Arduino on Google.

@Juraj I did try doing while(normPicture.available()){client.write(normPicture))} but it ends up writing incomplete. It starts writing fine like 56,78...,45, and then ends with a -1. On the external server, I get error 400 226. The 400 is a bad client request, and I believe the 226 is the bytes the external server received?

@Peter Thanks for the input. I’ll definitely look into it!

use esp8266 arduino package 2.4.2. Peter is right that you could do a direct upload, not a form simulation, but I don't understand his FTP recommendation. It would be a completely different approach

@juraj I’m using an esp32. Would it matter?

sorry. then latest version. I would guess it is "bad request" because of problems with your multipart boundaries

@Juraj It seemed like I wasn’t using the latest version. It writes correctly now I think, since it doesn’t end in “-1”. I do believe my boundaries are incorrect because the image did get sent to my external server, but I can’t open the file. It says “The file could not be opened. It may be damaged or use a file format that Preview doesn’t recognize”.


text:
LED on same Pin as Toggle Switch, not illuminating
I am trying to do something I think should be relatively simple. I would like to read an input from a toggle switch, and have a red 5mm LED indicate the state of the switch. Rather, however, than have an input for the switch and an output for the LED (controlled by software), I'd like to put them in series on a single circuit. That is, flip the toggle and current flows from the 5v source on the Arduino Uno through an LED and to an input pin on the Arduino. (I would ultimately like to have eight such switches; I am trying to create a sort of simulated byte, with individually flippable bits controlled by toggles; this will be read by a GTK Python program, that can interpret that "byte" in different ways: as a decimal value, a hex value, an ASCII character, a color in 8-bit color space, etc).
So, I have an LED with a 200 Ohm current-limiting resistor. I also have a pull-down resistor (1k) to prevent the toggle from floating.
My results, however, have been inconsistent. Using a breadboard, I've gotten this working. But it seems very fragile, and sometimes when I rebuild the circuit on a breadboard, it doesn't work as expected. Right now, for instance, the switch seems to work, and I am reading the expected value from the Serial Monitor--but the LED is not illuminating.
I had been playing around with different values for the pull-down resistor and the current-limiting resistor. This pair (200-ohm current limiting; 1k pull down) seemed to work, but now isn't. (I have swapped out the LED; and current is passing through the LED, otherwise I wouldn't be able to read the correct pin value--I think.)
Is there something I'm not understanding? Does the position of the current limiting resistor (before/after the LED) make any difference (I assume not)? Does this seem like the correct setup for what I'm trying to achieve? More generally, should, in principle, this approach scale to 8 more toggle/LED pairs? Is there a better/smarter approach? Is there a reason why I see so few Arduino projects that put LEDs in series with an input toggle?
The breadboard looks like this:

Do you want to turn the led on and off regardless of the switch as well? Or do you only want to read the switch (and the switch turns the led on and off).

Can you post your code? You might have switch bounce. An even number of bounces could cancel a press, and an odd number would effectively count as one press.

LEDs have a (fairly) fixed voltage drop across them.  The red LED is about 2V.
You can use that to work out the voltage at the input.  You basically have a voltage divider, with your 200Ω resistor as R1, and your 1kΩ resistor as R2.  The voltage drop of the diode is subtracted from Vin.
So:
Vout = (Vin - Vled) * (R2 / (R1 + R2))

     = (5 - 2) * (1000 / (200 + 1000))

     = 3 * (1000 / 1200)

     = 3 * 0.833

     = 2.5V

The ATMega328P datasheet states that a HIGH input voltage must be over 0.6*Vcc, and a LOW input voltage must be below 0.3*Vcc.  That means to register a HIGH you need more than 3V.  To register a LOW you need less than 1.5V.
You're between those two voltages - in the "dead zone".
The simplest way to achieve what you want is to use a douple-pole switch and keep the LED completely separate from the Arduino.

Using a double-pole switch seems indeed the smarter approach here. Thanks. I see your logic... but it doesn't account for my case, however, where I am getting the correct input on the Arduino--the LED is not illuminating. The dead zone you note would be like a floating pin, no?

This is your circuit that does not work:

simulate this circuit – Schematic created using CircuitLab
There are many ways to use a single pin. Some circuits are with a diode and some circuits need to turn off the led to read the switch. The most simple solution might be this:

simulate this circuit
When the switch is not closed, the LED is a weak pullup (perhaps too weak). By using INPUT_PULLUP for D7, the pullup is stronger and D7 can read the switch.
As an extra it is possible to turn the LED on when the switch is open. But you have to be sure to switch between OUTPUT + LOW and INPUT_PULLUP in the code or else there is a shortcut.


text:
How to start serial monitor on Windows startup
How can I get Windows to start the Serial Monitor window after a restart? Is there something I have to copy into the Windows startup folder for my account? Thanks

You can't.  You would need to have some way of telling the Arduino IDE to open the serial monitor and connect to a certain serial port. That can't be done.
Instead you would need to use some other third party serial communication program. How you would configure that depends on what the software is.
For Windows 10 you can make a program run at startup by following these instructions. You still need to configure the software to automatically connect to the right port at the right speed, of course.


text:
arduino LCD help
I am trying to create smart clock with alarm using an Arduino Uno.
My problem is when I set the alarm, I can't set the alarm again. Every time I must power off my Arduino and then power on in order to set the alarm again.
I am using:
Arduino Uno
LCD 16*2
buttons
buzzer and LED
RTC
My code works like this:
At the beginning it will let you to set date and time by buttons and you can set alarm too.
When it reaches the alarm time, it turns on the melody of buzzer and LEDs turn on.
but
I want to turn off the alarm so I can set another alarm.
This is my code:
#include "RTClib.h"
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int alarmState = 0;
int alarmSnooze = 0;
int btnSet = 0;
int btnSel = 0;
int alarmValue = 0;
int alarmCounter = 0;
boolean turnOffAlarm = false;
boolean settingAlarm = false;
int counter = 0;
boolean initialCount = true;
boolean alarmSet = false;
int timeArray[6]; // 0=Hour, 1=Minutes, 2=day, 3=Day of Week, 4=Month, 5=Year;
int timeCounter = 0;
int alarmArray[2];
char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
char* months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
RTC_DS1307 rtc;    // Create a RealTimeClock object
DateTime now; // Read data from the RTC Chip

//////////////////////////
 ///difine button////
int  b6=6;
int b7=7;
int b8=8;
int b9=9;
////////////////////

///melody///
#include "pitches.h"

const int piezoPin = 13; //piezo
const int rPin = A0;  //red LED
const int gPin = A1;  //green LED
const int bPin = A2;  //blue LED
const int pPin = 6;  //pushbutton

int ledState = 0;
int ledOn = false;

// notes
int melody[] = {
  NOTE_F5,NOTE_D5,NOTE_AS4,NOTE_D5,NOTE_F5,NOTE_AS5,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_D5,NOTE_E5,NOTE_F5,
  NOTE_F5,NOTE_F5,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_A5,NOTE_AS5,NOTE_AS5,NOTE_F5,NOTE_D5,NOTE_AS4,
  NOTE_D6,NOTE_D6,NOTE_D6,NOTE_DS6,NOTE_F6,NOTE_F6,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_DS6,
  0,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_A5,NOTE_AS5,NOTE_D5,NOTE_E5,NOTE_F5,
  NOTE_F5,NOTE_AS5,NOTE_AS5,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_G5,NOTE_G5,NOTE_C6,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_AS5,NOTE_A5,
  NOTE_F5,NOTE_F5,NOTE_AS5,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_F6,NOTE_AS5,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_C6,NOTE_AS5
};

// durations: 2 = half note, and 8/3,4,6,8,12. It appears that 8/2.9 is more accurate than 8/3.
float noteDurations[] = {
  6,12,4,4,4,2,6,12,4,4,4,2,
  8,8,8/2.9,8,4,2,8,8,4,4,4,4,4,
  6,12,4,4,4,2,8,8,4,4,4,2,
  8,8,8/2.9,8,4,2,8,8,4,4,4,2,
  4,4,4,8,8,4,4,4,4,8,8,8,8,4,4,
  8,8,8/2.9,8,8,8,2,8,8,4,4,4,2
};

// calculates the number of elements in the melody array.
int musicLength=sizeof(melody)/sizeof('NOTE_F5');

//////////////////////////

void setup()
{

  pinMode(pPin, INPUT);
  pinMode(rPin, OUTPUT);
  pinMode(gPin, OUTPUT);
  pinMode(bPin, OUTPUT);

  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(10, OUTPUT);
  rtc.begin(); // Start the RTC library code
  rtc.adjust(DateTime(0, 0, 0, 0, 0, 0));
}
void loop()

{ alarmState = digitalRead(b9);
  alarmSnooze = digitalRead(b6);
  btnSet = digitalRead(b7);
  btnSel = digitalRead(b8);

  if (timeCounter == 0)
  {
    if(initialCount == true){
      counter=0;
      initialCount = false;
    }
    setHour();
  }
  else if (timeCounter == 1)
  {
    if(initialCount == true){
      counter=0;
      initialCount =false;
    }
    setMinute();
  }
  else if (timeCounter == 2)
  {
    if(initialCount == true){
      counter= 1;
      initialCount=false;
    }
    setDay();
  }
  else if (timeCounter == 3)
  {
    if(initialCount == true){
      counter = 0;
      initialCount =false;
    }
    setDOW();
  }
  else if (timeCounter == 4)
  {
    if(initialCount==true){
      counter=0;
      initialCount=false;
    }
    setMonth();
  }
  else if (timeCounter == 5)
  {
    if(initialCount==true){
      counter=0;
      initialCount=false;
    }
    setYear();
  }
  else if (timeCounter == 6)
  {
    rtc.adjust(DateTime(2000+timeArray[5], timeArray[4], timeArray[2], timeArray[0], timeArray[1], 0));
    timeCounter++;
    delay(200);
  }
  else if (timeCounter > 6){
    if(alarmState == LOW&&settingAlarm==false){
      now = rtc.now();
      digitalClockDisplay();
    }
    else if(alarmState == HIGH||settingAlarm==true)
    {
      settingAlarm = true;
      if(alarmValue==0){
        if(initialCount==true)
        {
          lcd.clear();
          alarmCounter=0;
          initialCount=false;
        }
        setAlarmHour();
      }
      else if(alarmValue==1){
        if(initialCount==true)
        {
          alarmCounter=0;
          initialCount=false;
        }
        setAlarmMinute();
      }
      else if(alarmValue>1){
        alarmSet = true;
        settingAlarm = false;
      }
    }
    if(alarmArray[0]==now.hour()&&alarmArray[1]==now.minute()&&turnOffAlarm==false&&alarmSet==true&&alarmSnooze==LOW){
       for (int thisNote = 0; thisNote < musicLength; thisNote++) {
      // blink the three LEDs in sequence
      if (thisNote%3==0){
        digitalWrite(rPin, HIGH);
        digitalWrite(gPin, LOW);
        digitalWrite(bPin, LOW);
      }
      else if (thisNote%3==1){
        digitalWrite(rPin, LOW);
        digitalWrite(gPin, HIGH);
        digitalWrite(bPin, LOW);
      }
      else if (thisNote%3==2){
        digitalWrite(rPin, LOW);
        digitalWrite(gPin, LOW);
        digitalWrite(bPin, HIGH);
      }

      // calculate the note duration. change tempo by changing 2000 to other values
      int noteDuration = 2000/noteDurations[thisNote];
      tone(piezoPin, melody[thisNote],noteDuration);

      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well
      float pauseBetweenNotes = noteDuration * 1.30;

      //split the delay into two parts and check to see
      //whether the pushbutton is pressed to turn off
      //the sound and light
      delay(pauseBetweenNotes/2);
      if(digitalRead(pPin)==HIGH) {
        break;
      }
      delay(pauseBetweenNotes/2);
      if(digitalRead(pPin)==HIGH) {
        break;
      }

    }
      digitalWrite(13, HIGH);

    }

    else if(alarmArray[0]==now.hour() && alarmArray[1]==now.minute()&&turnOffAlarm==false&&alarmSet==true&&alarmSnooze==HIGH){
      noTone(13);
      digitalWrite(13, LOW);
      digitalWrite(rPin, LOW);
    digitalWrite(gPin, LOW);
    digitalWrite(bPin, LOW);
      turnOffAlarm = true;
    }
  }
}

void nextValue(){
  btnSel=LOW;
  // Update array value with counter
  timeArray[timeCounter] = counter;
  counter=0;
  initialCount = true;
  timeCounter++;
  delay(200);
  lcd.clear();
}
void nextAlarmValue(){
  btnSel=LOW;
  // Update array value with counter
  alarmArray[alarmValue] = alarmCounter;
  alarmCounter=0;
  initialCount = true;
  alarmValue++;
  delay(200);
  lcd.clear();
}

void setAlarmHour(){
   if(alarmCounter==24){
    alarmCounter=0;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set alarm hour");
  lcd.setCursor(7,1);
  lcd.print(alarmCounter);
  if (btnSet==HIGH)
  {
    alarmCounter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextAlarmValue();
 }
}

void setAlarmMinute(){
  if(alarmCounter==59){
  alarmCounter=0;
  lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set alarm minute");
  lcd.setCursor(7,1);
  lcd.print(alarmCounter);
  if (btnSet==HIGH)
  {
    alarmCounter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextAlarmValue();
 }
}

void setDOW(){
  if(counter==7){
    counter=0;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set day of week");
  lcd.setCursor(7,1);
  lcd.print(days[counter]);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}
void setHour()
{
  if(counter==24){
    counter=0;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set hour");
  lcd.setCursor(7,1);
  lcd.print(counter);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}

// Function to set minutes
void setMinute()
{
  if(counter==60){
    counter=0;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set minute");
  lcd.setCursor(7,1);
  lcd.print(counter);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}

// Function to set date
void setDay()
{
  if(counter==32){
    counter=1;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set day");
  lcd.setCursor(7,1);
  lcd.print(counter);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}

// Function to set month
void setMonth()
{
  if(counter==12){
    counter=0;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set month");
  lcd.setCursor(7,1);
  lcd.print(months[counter]);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}

// Function to set year
void setYear()
{
  lcd.setCursor(0,0);
  lcd.print("Set year");
  lcd.setCursor(7,1);
  lcd.print(counter);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}

void digitalClockDisplay(){
  // digital clock display of the time
  long hours;
  String amOrPm = "";
  if(now.hour() > 12){
    hours = now.hour() - 12;
    amOrPm = "PM";
  }
  else if(now.hour()==0){
    hours=12;
    amOrPm = "AM";
  }
  else{
    hours = now.hour();
    amOrPm = "AM";
  }
  lcd.setCursor(0,0);
  lcd.print(days[timeArray[3]]);
  lcd.print(" ");
  lcd.print(months[timeArray[4]]);
  lcd.print(" ");
  lcd.print(now.day());
  lcd.print(" ");
  lcd.print(now.year());
  lcd.setCursor(0,1);
  lcd.print(hours);
  printDigits(now.minute());
  printDigits(now.second());
  lcd.print(" ");
  lcd.print(amOrPm);
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  lcd.print(":");
  if(digits < 10)
    lcd.print('0');
  lcd.print(digits);
}

What did you try to do by sizeof(melody)/sizeof('NOTE_F5')??? What is the point of sizeof('NOTE_F5') specifically? What did the compiler tell you about 'NOTE_F5'?

It looks like you haven't reset your state variable turnOffAlarm after you turn off the alarm.

Since the question is tagged [code-review]

char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

This should be a const array of const char *, not of char *.
const char *const days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

Same goes for months.
int  b6=6;
...
const int piezoPin = 13;
...

Why some of your pins are const and others are not? I don't see any attempts or reasons to change the value of b6 in the code. Why is it not const?
int melody[] = { ... };
float noteDurations[] = { ... };

Both are supposed to be be const, apparently.
// calculates the number of elements in the melody array.
int musicLength=sizeof(melody)/sizeof('NOTE_F5');

Really? What is 'NOTE_F5'? What did your compiler tell you about it? Did you just ignore the compiler's message?
Should be
const int musicLength = sizeof melody / sizeof *melody;

I'd prefer unsigned or size_t, but let's not open this can of worms.
In a single-file sketch all global variables (i.e. the ones that really need to be global) should be declared either const or static (or placed in an anonymous namespace). Declaring a global variable that is not const or static requires a good reason for doing so.


text:
How do I redefine the overlfow of compare interrupts in Arduino programming?
If I'm programming a pin change interrupt I can call attachInterrupt at various points in my code and change what function is called when the interrupt occurs.
The overflow and compareA/B interrupt calls are defined by the ISR macro which is evaluated at compile time, which therefore can't be changed at run time. One solution would be to make that function consist of a single line, which invokes a function pointer. If I'm reading the code correctly, this is how attachInterrupt is implemented. Short of mucking with the interrupt vector table (which seems like a bad idea, or at least very hard to debug if you screw it up), is there another way to redefine the overflow or compare interrupt functions?

For a arduino uno with a microcontroller of the avr family? They have the vector table in code (in flash), you can not change that runtime. You could make each vector of the vector table point to ram which you could change runtime, but that would be the same as having a ISR that invokes a function pointer. That is not a bad idea, as long as it is clear and well defined, it is a normal way to change the function of an interrupt. For the pin-change-interrupt I suggest the EnableInterrupt: https://github.com/GreyGnome/EnableInterrupt

call attachInterrupt at various points in my code ..... you could set a global variable at various points in your code ...... the ISR would execute a function dependent on value of the global variable

What about using a switch statement inside the ISR function and reroute the flow depending on the value of the global variable used in the switch?
uint8_t status = 0;

void myInterruptFn() {
  switch(status) {
    case 0:
      // do something
      status = 1;
      break;
    case 1:
       // do something else
       status = 0;
       break;
   }
}


text:
ESP 8266 serial error
I am using an ESP8266 board and I had it plugged in to my computer via usb. I reached accross the board to press the reset button, and it felt like my finger got stung. The best I can figure, I touched the VIN and Gnd pins with my finger, and, I didn't think this at first, the reset pin. Whenever I try to open a serial port all that shows, and at a different baud rate then I specified, is this error message
 ets Jan  8 2013,rst cause:2, boot mode:(3,7)

 load 0x4010f000, len 1384, room 16
 tail 8
 chksum 0x2d
 csum 0x2d
 v951aeffa
 ~ld

Everything I find online says that this means that the reset pin is causing problems. Although this is the first time a 7 showed up, it used to be a 6. Also, the computer doesn't seem to have a problem uploading the sketches, but they don't seem to run.
I have tried re-flashing the firmware, but just now when I was typing this out, I thought to upload Blink, just to say I could, and it worked, but it isn't sending anything to the computer of serial, at all. I own two of these boards, but the problem happened across both making me think that something happened to my computer.
Any help is appreciated.
Edit: I am running Win 10, using Vscode to upload sketches, and arudino IDE v1.8.7 to monitor serial. I have many Serial.print() lines, and Serial.begin(115200)

is this error message that's not an error message, that's the ESP boot message

you would not feel the voltages on the ESP8266 pins ..... you would however feel a static electricity discharge from your finger into the board ..... did you walk across a carpet before you touched the board? ..... if it was a static electricity discharge, then there is a good reason to believe that the board has been destroyed

rst cause:2 means the boot was due to a reset (perfectly OK) and boot mode(3,x) means GPIO15 was LOW, and GPIO0 and GPIO2 were HIGH ... which is what you want when you boot into your sketch ... what's the issue again?

do you have any Serial.print() commands in your sketch? if not, then there wont be any output

Do you set Generic ESP8266 settings? Try to set DIO

@JaromandaX forgetting Serial.begin() is also classic

@JaromandaX Thanks, that makes me feel a lot better, but why would it send this at a different baud rate?

@jsotola I was sitting in my chair for the last thirty mins reading up on MDNS and the such, and, as I said above, the only clue I got was that my finger felt like it was stung

@Juraj I am using the NodeMCU 1.0 (ESP-12E) board setting following the instructions on the amazon page. A DIO? (is that a digital I/O pin?

"Flash mode" in Tools menu. it is not available to set for NodeMcu


text:
Serial.available is working only for the first time
I am working on RFID. I am sending data through serial monitor and the Serial.available is not identifying the data after the first time, its working perfectly fine only once after reopening the comport.
I have tried all the possible changes I could do in the code. I want that when I run this code, then after entering the data in serial monitor it should show "Scan the mifare card" and after scanning the card it should perform read or write action.
#include <SPI.h>//include the SPI bus library
#include <MFRC522.h>//include the RFID reader library

#define SS_PIN 10  //slave select pin
#define RST_PIN 9 //reset pin
MFRC522 mfrc522(SS_PIN, RST_PIN);        // instatiate a MFRC522 reader object.
MFRC522::MIFARE_Key key;//create a MIFARE_Key struct named 'key', which will hold the card information

void setup()
 {
        Serial.begin(9600);        // Initialize serial communications with the PC
        SPI.begin();               // Init SPI bus
        mfrc522.PCD_Init();
        //while (! Serial); // Wait untilSerial is ready - Leonardo
        //Serial.println("Enter data");
 }

String incomingStr;
byte blockcontent[16];
int count=0;
String arr2[6];
int arr3[6];
int u2=0;
String arr[16];
int arr1[16];
int u=0;
int y;
char action;
//int newc=0;

void loop()
{
 // Serial.println("bahar");
  if (Serial.available())
    {
      doReceive();
      int newc=0;
      while(newc==0)
       {
         if ( ! mfrc522.PICC_IsNewCardPresent())
            {
               if(count==0)
                   {
                       Serial.println("Scan your mifare card %");
                       count++;
                   }
            }
        else
            {
               newc=1;
            }
       }

     if ( ! mfrc522.PICC_ReadCardSerial())
       {
         return;
       }
     if(action=='%')
       {
         doWrite();
       }
     else if(action=='$')
       {
         doRead();
       }
     else if(action=='^')
       {
         for (byte i = 0; i < mfrc522.uid.size; ++i)
           { // read id (in parts)
              Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
              Serial.print(mfrc522.uid.uidByte[i], HEX);
           }
         Serial.print("*");
       }
  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
  Serial.flush();
   }
}

void doReceive()
{
   incomingStr = Serial.readString();
   int sto=incomingStr.indexOf(')');
   action=incomingStr.charAt(sto+1);
   y=sto+2;
   for(int j=0;j<sto;j++)
    {
      if(incomingStr.charAt(j)!= ' ')
       {
         //Serial.print(incomingStr.charAt(j));
         //arr[u]=arr[u].concat(incomingStr.charAt(j));
         arr2[u2]+=incomingStr.charAt(j);
       }
     else
       {
         //Serial.println(arr[u]);
         u2++;
       }
    }
  for(u2=0;u2<6;u2++)
    {
      arr3[u2]=arr2[u2].toInt();
      key.keyByte[u2]=arr3[u2];
      //Serial.println(key.keyByte[u2]);
    }
 }
void doWrite()
{
  int block=1;
  for(int i=0;i<incomingStr.length();i=i+16)
  {
    if(block == 3 || block ==7 || block ==11 || block ==15 || block ==19 || block ==23 || block ==27 || block ==31 || block ==35 || block ==39 || block ==43 || block ==47 || block ==51 || block ==55 || block ==59 || block ==63)
      {
        block=block+1;
      }
    for(int u=0;u<16;u++)
      {
        blockcontent[u]=0;
        //Serial.println(arr1[u]);
      }
    String s1=incomingStr.substring(y+i,y+16+i);
    s1.getBytes((char *) blockcontent, 30);
    writeBlock(block, blockcontent);
    block=block+1;
  }
  Serial.println("Data written successfully*");
}
void doRead()
{
  int block=1;
  for(int i=0;i<4;i++)
    {
      if(block == 3 || block ==7 || block ==11 || block ==15 || block ==19 || block ==23 || block ==27 || block ==31 || block ==35 || block ==39 || block ==43 || block ==47 || block ==51 || block ==55 || block ==59 || block ==63)
        {
          block=block+1;
        }
      byte readbackblock[18];
      readBlock(block, readbackblock);//read the block back
      //Serial.print("Block contains: ");
      for (int j=0 ; j<16 ; j++)//print the block contents
        {
           Serial.write (readbackblock[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
        }

     //Serial.println();
     block=block+1;
    }
  Serial.println("*");
 }

I have tried all the possible changes I could do in the code. First of all, you could make it reabable by proper indenting.

arr2[u2]+=incomingStr.charAt(j); I don't understand this. But I doubt, it's doing want you want

@user55609 please use proper indentation wile programming. It help other to understand your code easily.

add some test point in you code after every module execution, that will help you to get the error.

what string you sent from serial monitor?

First of all try to add these debugging prints here to see if this while loop is becoming infinite:
  while(newc==0)
   {
     if ( ! mfrc522.PICC_IsNewCardPresent())
        {
           if(count==0)
               {
                   Serial.println("Scan your mifare card %");
                   count++;
                   **Serial.println("test0")*
               }

        }
    else
        {
           newc=1;
           **Serial.println ("newc=1")**
        }
   }

arr2 have size 6. Have you made sure that here
...
for(int j=0;j<sto;j++)
{
  if(incomingStr.charAt(j)!= ' ')
   {
     arr2[u2]+=incomingStr.charAt(j);
   }
 else
   {
     u2++;
   }
}
...

you are not writing beyond the bounds of that array?
Moreover, you never explicitly set the initial value of u2 before starting this cycle - whatever was left in global variable u2 from the previous uses will serve as the staring value for this cycle.
Judging by cursory examination of the rest of your code, only the very first call to doReceive will begin this cycle with u2 == 0. After that every time you call doReceive, you will start this cycle with u2 == 6, definitely overflowing the array and destroying the content of adjacent memory locations. The behavior is undefined.
I guess it is a "global variables strike again" kind of situation. Why on Earth is u2 made a global variable???
It is quite possible that you can "fix" your code by simply adding u2 = 0; before the above cycle. But even after that the code will remain in a rather precarious state.


text:
Input value constantly
The code is for a DC motor position control PID system. I need the angle I need to move to "setpoint" and change it throughout the process. Though it is only changing once and then nothing happens if I insert a new value unless I upload the code again. I need help in finding the problem, thank you.
Code:
double count = 0; //set the counts of the encoder
double angle = 0;//set the angles
boolean A,B;
byte state, statep;

double pwm = 9;// this is the PWM pin for the motor for how much we move it to correct for its error
const int dir1 = 6;//these pins are to control the direction of the motor (clockwise/counter-clockwise)
const int dir2 = 7;

double    setpoint = 0;
double Kp = 0.2;// you can set these constants however you like depending on trial & error
double Ki = 0.25;
double Kd = 1;

float last_error = 0;
float error = 0;
float changeError = 0;
float totalError = 0;
float pidTerm = 0;
float pidTerm_scaled = 0;// if the total gain we get is not in the PWM range we scale it down so that it's not bigger than |255|
String readString;

void setup() {
   Serial.begin(9600);
  pinMode(2, INPUT);//encoder pins
  pinMode(3, INPUT);
  attachInterrupt(0,Achange,CHANGE);//interrupt pins for encoder
  attachInterrupt(1,Bchange,CHANGE);

  pinMode(pwm, OUTPUT);
  pinMode(dir1, OUTPUT);
  pinMode(dir2, OUTPUT);

}

void loop(){

   if (Serial.available()) { //Check if the serial data is available.
    delay(3);                  // a small delay
    char c = Serial.read();  // storing input data
    readString += c;         // accumulate each of the characters in readString
  }

  if (readString.length() >0) { //Verify that the variable contains information

   Serial.println(readString.toInt());  //printing the input data in integer form
    setpoint = readString.toInt();   // here input data is store in integer form

  }
   PIDcalculation();// find PID value

  Serial.print("         ");
Serial.print(setpoint);
Serial.print("         ");

  if (angle > setpoint+0.5) {
    digitalWrite(dir1, LOW);// Forward motion
    digitalWrite(dir2, HIGH);
  }
else if  (angle < (setpoint-0.5)) {
    digitalWrite(dir1, HIGH);//Reverse motion
    digitalWrite(dir2, LOW);
  }
  else{
      digitalWrite(dir1, LOW);//Reverse motion
    digitalWrite(dir2, LOW);
  }
  analogWrite(pwm, pidTerm_scaled);

  Serial.println("WHEEL ANGLE:");
  Serial.print(angle);  // here input data is store in integer form;
  delay(100);

}

void PIDcalculation(){

  angle = (0.9 * count);//count to angle conversion
  error = setpoint - angle;

  changeError = error - last_error; // derivative term
  totalError += error; //accumalate errors to find integral term
  pidTerm = (Kp * error) + (Ki * totalError) + (Kd * changeError);//total gain
  pidTerm = constrain(pidTerm, -155, 155);//constraining to appropriate value
  pidTerm_scaled = abs(pidTerm);//make sure it's a positive value

  last_error = error;
}

void Achange() //these functions are for finding the encoder counts
{
  A = digitalRead(2);
  B = digitalRead(3);

  if ((A==HIGH)&&(B==HIGH)) state = 1;
  if ((A==HIGH)&&(B==LOW)) state = 2;
  if ((A==LOW)&&(B==LOW)) state = 3;
  if((A==LOW)&&(B==HIGH)) state = 4;
  switch (state)
  {
    case 1:
    {
      if (statep == 2) count++;
      if (statep == 4) count--;
      break;
    }
    case 2:
    {
      if (statep == 1) count--;
      if (statep == 3) count++;
      break;
    }
    case 3:
    {
      if (statep == 2) count --;
      if (statep == 4) count ++;
      break;
    }
    default:
    {
      if (statep == 1) count++;
      if (statep == 3) count--;
    }
  }
  statep = state;

}

void Bchange()
{
  A = digitalRead(2);
  B = digitalRead(3);

  if ((A==HIGH)&&(B==HIGH)) state = 1;
  if ((A==HIGH)&&(B==LOW)) state = 2;
  if ((A==LOW)&&(B==LOW)) state = 3;
  if((A==LOW)&&(B==HIGH)) state = 4;
  switch (state)
  {
    case 1:
    {
      if (statep == 2) count++;
      if (statep == 4) count--;
      break;
    }
    case 2:
    {
      if (statep == 1) count--;
      if (statep == 3) count++;
      break;
    }
    case 3:
    {
      if (statep == 2) count --;
      if (statep == 4) count ++;
      break;
    }
    default:
    {
      if (statep == 1) count++;
      if (statep == 3) count--;
    }
  }
  statep = state;

}

your code is unreadable as it is ..... please use the {} button to  format the code ...... just select all of the code text and click {}

Since you have all that Serial calling in your sketch, please copy and paste the serial output, that you get to the question. Also specify what exactly you entered into the serial monitor to get to these results.


text:
Using RTC DS1307 and OLED on Arduino MEGA
I'm using RTC DS1307 and OLED on an Arduino MEGA together.
When I try to use a rtc code like
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
or DateTime now = rtc.now(); the OLED display starts not showing what i wish in "void loop".
The summary of the code is below:
#include "Arduino.h"
#include "U8g2lib.h"
#include "U8x8lib.h"
#include "RTClib.h"
#include "Wire.h"
#include "SPI.h"
U8G2_SSD1306_128X32_UNIVISION_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE);   // Adafruit Feather M0 Basic Proto + FeatherWing OLED
RTC_DS1307 rtc;
void setup() {

  Serial1.begin(57600);
 if (! rtc.isrunning()) {
    Serial1.println("RTC is NOT running!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
     }
     if (! rtc.begin()) {
    Serial1.println("Couldn't find RTC");
    while (1);
  }
  Serial1.end();

  Serial2.begin(9600);
  while (!Serial2) {
    ; // wait for Serial2 port to connect. Needed for native USB port only
  }
  u8g2.begin();

  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_6x13_te);
  u8g2.drawStr(30, 25, "WELCOME!");
  u8g2.sendBuffer();
  delay(2000);
  Serial2.setTimeout(1100);
}

void loop() {
 u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_6x13_te);
  u8g2.drawUTF8(0,12,"EepromA");
  u8g2.setCursor(55,12);
  //u8g2.print(EepromA);
  u8g2.setCursor(100,12);
  u8g2.print("EepromA");
  u8g2.drawUTF8(0,22,"EepromB");
  u8g2.setCursor(55,22);
 // u8g2.print(EepromB);
  u8g2.setCursor(100,22);
  u8g2.print("EepromB");
  u8g2.drawUTF8(0,32,"EepromC");
  u8g2.setCursor(55,32);
//  u8g2.print(EepromC);
  u8g2.setCursor(100,32);
  u8g2.print("EepromC");
  u8g2.sendBuffer();
      delay(50);

}

It seems like it is about i2c of Arduino Mega but how to solve the problem?
Note: After a search on the website I found some similar problems, I have removed R2 and R3 pull-up resistors on RTC module, this did not solve it.

Does it display "WELCOME"?

@geometrikal, yes it displays.

This means the hardware and pullups are not an issue and the I2C clock is good. It might be that you are filling the I2C buffer too quickly. Try adding a longer delay in the loop.

In addition, when i uncomment OLED codes, the RTC also works fine.

So either RTC or OLED works, but never at the same time?

Exactly right  ..


text:
Arduino Uno & ESP32 communication using RS485
I am trying to establish a communication between Arduino Uno ( Master) and ESP32 (Slave) using RS485 protocol (using MAX485 module).
I have successfully done this between two Arduino Unos. SoftwareSerial library is what i am using between two Arduino Unos, now trying with ESP32 and Arduino Uno (using MAX485 module)
.
For ESP32 i have used SoftwareSerial (https://github.com/akshaybaweja/SoftwareSerial) library.
After reading the library and making connection i am not be able to establish a communication between them. Sharing my code below.
Receiver
#include <SoftwareSerial.h>

SoftwareSerial softwareSerial(9, 10);
String str;

void setup()
{

  Serial.begin(9600);
  softwareSerial.begin(9600);

}

void loop()
{

  while (softwareSerial.available() > 0) {

    char inChar = softwareSerial.read();

    if (inChar == '$') {

        str.trim();
        Serial.println("received command" + str);
        memset(&str, 0, sizeof(str));
        Serial.flush();
        softwareSerial.flush();
    }
    else {
        str = str + inChar;
    }

 }

}

Sender
#include <SoftwareSerial.h>

SoftwareSerial swSer1(22, 23, false, 256);
String str;

void setup() {

  Serial.begin(9600);
  swSer1.begin(9600);

}

void loop() {

  String sendCmd = "MSG1$";
  Serial.println("Sending ");
  Serial.println(sendCmd );
  char copy[50];
  sendCmd.toCharArray(copy, 50);
  swSer1.write(sendCmd);
  delay(1000);

}

Here my question is where i am going wrong in this project. Please guide me.
Note : DE AND RE PINS are connected to high for sender device and to low for receiver device as given in the RS485 documentation.

Maybe you have already solved this but in any case, have you tried working with the hardware serial ports? You have three of them in the ESP32. I read sowhere else that there may be some interrupt issues using the SoftwareSerial library on the ESP devices, especially at higher baud rates.

I havent solved yet , i changed the circuit itself other than what i was using.. also i have tried but those are not so helping me in my application.

@dejoo Where you read about some interrupt issues? I work in Arduino Libraries and I'll like receive this information. Thanks!:) Pd. I can't comment because I just registered

I don't think you can use pins 9 and 10 they are connected to the internal mSPI flash, uart0 is connected to FTDI usb chip, use uart2 on 16 and 17.