text:
My "avoid car" can't move straight

I use 2 gearbox motors with 2 wheels .. but if I try to run it, he can not walk straight. he always moves slightly to the right or to the left.
How i fix it ?

well you have posted no code, no schematics, no real information, so I guess we are to guess at how you have it all configured?  I would guess you are using PWM output to  control how fast the motors are going. So you should increase or decrease one to adjust the speed

I've tried it, do I need to use a "encoder motor" ?

What were the results when you tried it?  Did it work but you were not able to find the correct balance between the motors?  Encoders will help ensure they are spinning at the same rate yes, but other factors could still make the car turn slightly.

What, exactly, did you try, and what happened? Please show more details about how your car behaves, what you changed, whether the car's behavior changed at all, etc. There just isn't enough information here to offer you much more than guesses.

swap the motor wires just to make sure that the problem is the motor (it should still turn the same direction .... if the direction changes then it is the driver or the software

Likely the two gearbox motors you have are running at slightly different speeds for the same voltage. This is probably within normal tolerances, given that you say it moves slightly to the right or left.
You can use PWM-capable pins for motor control so you can adjust how fast the motors turn. If you do this, you have a couple of paths you can take:
You can, through trial-and-error, lower the PWM value (analogWrite(pin, speed)) for the faster-turning motor so that they both turn at the same speed.
or
You can find some way to detect the actual rotational speed of each motor and do the calibration in real-time on the Arduino. This might mean adding new sensors such as rotary encoders (mechanical or optical), or light-break sensors, etc.

I will try it again , to find the same speed with PWM. But if that not work , what module can i use to the rotary encoder ?

To use the rotary encoder solution gets much more complex. You have to find a rotary encoder that can fit onto the same shaft as your motor or wheel, or obtain a motor/gearbox that has a built-in encoder.


text:
Why my servo motor is always on?
Why my servo motor is always on?

#include <Servo.h>

Servo myservo;

int pos = 0;

void setup() {

pinMode(2, INPUT);
myservo.attach(9);

}

void loop() {

  if (digitalRead(2) == LOW) {

    for (pos = 0; pos <= 180; pos += 1) {
      myservo.write(pos);
      delay(15);
    }

    for (pos = 180; pos >= 0; pos -= 1) {
      myservo.write(pos);
      delay(15);
    }
  }
  else {
    myservo.write(0);
    delay(15);
  }
}

Provide a proper schematic and listing.

What do you mean by 'always on', is it always moving or always energized?

@TimWescott Why not simply give the OP the opportunity to alter the question rather than hastily 'close' the question. Once closed it seems unlikely to get votes to open again even if it is altered. This is really just 'close' being used as a form of bullying.

Drastically simplify your setup.  Take the condition out of the code and just command a steady angle.  Then try again with a different one.  As you make your sketch more complicated again, add serial logging to explain what it thinks it is doing.  And of course explain precisely what is happening.

Closing would prevent a bunch of well-intended but poorly informed (no info from OP) answers to be written and made obsolete by updates on the question and context.

It looks like you need to enable the pull-up resistor on D2.  As written D2 is left floating and most likely is a low voltage relative to ground.  Enabling the pull up resistor will force the pin high until you flip the switch.

Arduino inputs have significant capacitance. So once the switch has been pressed the input will tend to stay low. Use either pinMode(pin, INPUT_PULLUP) or use digitalWrite(pin, HIGH) to turn on the pullup for a (pin) configured as INPUT.

it works!! thanks

source: Stack Exchange

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

sort: votes


text:
Unexplainable int behavior in encoder/LED project
I am trying to use a rotary encoder to cycle through the brightest versions of R, G & B. And it works! Red goes to blue just fine. Then G happens. For some reason, the int for green goes completely haywire. And it does this the same way on two Arduinos.
So my question is this: why would two, identically assigned variables treat ++ completely differently? After hours (and hours and hours) of looking, I'm completely out of possible answers.
#include <Encoder.h>
#include <FastLED.h>

/* Encoder */
Encoder myEnc(2, 3);
const int swPin = 4 ;
long oldPosition  = -999;

/* LEDs */
#define LED_PIN     7
#define NUM_LEDS    150
CRGB leds[NUM_LEDS];

/* RGB Loop */
volatile int cycle = 1;
volatile int brightness = 0;
volatile int r = 127;
volatile int g = 0;
volatile int b = 0;

void setup() {
  pinMode(swPin, INPUT);
  Serial.begin(9600);
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
}

void loop() {
  // Read from rotary encoder.
  long newPosition = myEnc.read();

  if (newPosition != oldPosition) {
    oldPosition = newPosition;
    Serial.println(newPosition); /* Sends elsewhere */
  }

  /* Will eventually move this inside the above if
   * statement so the color shift is controlled by
   * a rotary encoder.  Down here for debugging.
   */
  delay(50);
  updateColor( );
}

void updateColor(  ) {

  Serial.println(" "); // For readability.

  if ( brightness >= 127 ) {
    brightness = 1;
    if ( cycle > 6 ) {
      cycle = 1;
    } else {
      cycle++;
    }
  } else {
    brightness++;
  }

  if ( cycle == 1) {
    b++;
  }
  else if ( cycle == 2) { /* rb --> b */
    r--;
  }
  else if ( cycle == 3) { /* b --> bg */
    g++;
  }
  else if ( cycle == 4) { /* bg --> g */
    b--;
  }
  else if ( cycle == 5) { /* g --> rg */
    r++;
  }
  else if ( cycle == 6) { /* g --> rg */
    g--;
  }
  else {
    Serial.print("==================== ");
  }

  /* Debugging */
  Serial.print("brightness:");
  Serial.print(brightness);
  Serial.print("   cycle:");
  Serial.print(cycle);
  Serial.print("   r:");
  Serial.print(r);
  Serial.print(" g:");
  Serial.print(g); // goes completely bonkers
  Serial.print(" b:");
  Serial.print(b);
  Serial.println(" ");

  for (int i = 0; i <= NUM_LEDS; i++) {
    leds[i].setRGB( r, g, b );
  }

  FastLED.show();

}

spits out the following in the serial monitor :
brightness:1   cycle:1   r:127 g:0 b:1

brightness:2   cycle:1   r:127 g:127 b:2

brightness:3   cycle:1   r:127 g:32639 b:3

brightness:4   cycle:1   r:127 g:32639 b:4

brightness:5   cycle:1   r:127 g:32639 b:5

brightness:6   cycle:1   r:127 g:32639 b:6

Red and blue are doing exactly what I want. Green is off on Mars.
Any/all help would be enormously appreciated.  Thanks in advance.

127 = 0x7F, 32639 = 0x7F7F.

I can't yet comment so therefore here.
Could you try casting the rgb printouts to uint8_t? It could be that it goes out of bounds or something? I don't see anything wrong with the code so maybe it could be that some pointer is changing the value of g?

I do not see a relation between the encoder and the r,g,b values. Or between the encoder and your rgb problem. BTW: rgb values are byte, not int

laffan, we don't see the problem. It could be a compiler or optimization bug (not likely, but it is possible) or a bug in a library that overwrites memory. You have to try a number of things. Start with an example, and slowly change that in the direction of your sketch. The setRGB is a inline function that has uint8_t as parameters. I think there is no need to make the variables volatile.

Thank you all!
@Jot I think you're on to something. I'm not sure what you're on to, but that at least explains the number. Looks like I need to learn some more about hexidecimals.  And good to know re: that variable volatility (I was grasping at straws.)
Tarik Welling - I'm afraid this hobbiest hasn't gotten to pointers yet, but I'll take a look.
DataFiddler - The new/old position thing is the rotary encoder part (see comments) which works, incredibly. Thanks for the byte tip.

couple of things to try ..... comment out the FastLed code ..... exchange the b++ and the g--  in the if blocks

Here:
CRGB leds[NUM_LEDS];

you are defining an array of NUM_LEDS objects of the CRGB type.
Valid indices for this array range from 0 to NUM_LEDS-1.
Here:
for (int i = 0; i <= NUM_LEDS; i++) {
  leds[i].setRGB( r, g, b );
}

you are accessing the array elements at indices 0 to NUM_LEDS. The
last iteration is an out-of-bounds access, which is causing memory
corruption. You should instead write
for (int i = 0; i < NUM_LEDS; i++) ...

Thank you so much @edgar-bonet - I don't think I ever would have figured that out.

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


text:
0 temperature & hummidity DH11
Alright so I'm having problems with my code. Its my first time using DH11
I keep on getting that temperature is 0 degrees so as the humidity
#include "dht.h"
#define dht_apin A0

dht DHT;

void setup(){

  Serial.begin(9600);
  delay(500);
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(1000);

}

void loop()
{

    DHT.read11(dht_apin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");

    delay(5000)

}

What Im getting is basically

Current humidity = 0.00%  temperature = 0.00C

did you run the example code?

Suggestion: drop the dht11 in favor of Bosch's BME280 (not BMP!).  It measures temperature, humidity AND pressure.

@tonygil ... and it doesn't make use of dump 1-wire protocoll. As long as 1w is not supported by hardware this turns out to be a game-breaker in many professional (non-makers) applications (my experience). BME is a great alternative and provides SPI and i2c

Do you have the external pullup?

I have run into problems when using some DHT library versions.  May I suggest that you try using a different version of dht.h?
This version works for me (there is a newer version I have NOT tested):
dht.h (606B 6/12/2012)
//
//    FILE: dht.h
// VERSION: 0.1.00
// PURPOSE: DHT Temperature & Humidity Sensor library for Arduino
//
//     URL: http://arduino.cc/playground/Main/DHTLib
//
// HISTORY:
// see dht.cpp file
//

#ifndef dht_h
#define dht_h

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

#define DHT_LIB_VERSION "0.1.00"

class dht
{
public:
    int read11(uint8_t pin);
    int read22(uint8_t pin);
    double humidity;
    double temperature;

private:
    uint8_t bits[5];  // buffer to receive data
    int read(uint8_t pin);
};
#endif
//
// END OF FILE
//


text:
How to use external libraries in CLion
I would like to use the external libraries that are downloaded by Arduino IDE into the default sketchbook location (~/Arduino/libraries/).
If you open Library Manager in Arduino IDE and if you install an external library (e.g DHT sensor library 1.3.7 and its dependency Adafruit Unified Sensor 1.0.3) then it will be downloaded to the sketchbook location and you can use them freely in case of writing code in Arduino IDE.
However I really like auto code completion, managing source code in GIT repository, formatting source lines, etc. which functionalities are not provided by Arduino IDE, so I changed to CLion.
I have installed CLion and Arduino Support 1.4.4 Plugin and created a new Arduino Sketch Project.
Project Structure:
.
+--cmake
   +--Platform
      +--Arduino.cmake
   +--ArduinoToolchain.cmake
+--libs
   +--Adafruit_Sensor
      +--Adafruit_Sensor.h
      +--library.properties
      +--README.md
   +--DHT
      +--DHT.cpp
      +--DHT.h
      +--DHT_U.cpp
      +--DHT_U.h
      +--keywords.txt
      +--library.properties
      +--README.md
+--CMakeLists.txt
+--first_test_project.ino
+--User_Setup.h

first_test_project.ino:
#include <Arduino.h>
#include "User_Setup.h"
#include <libs/Adafruit_Sensor/Adafruit_Sensor.h>
#include <libs/DHT/DHT.h>

DHT *dht;

void setup() {
    dht = new DHT(7, DHT22);
}

void loop() {

}

So I have copied over the downloaded libraries from ~/Arduino/libraries folder to the project folder under libs folder.
When I try to upload the code to Arduino Board I am getting the following in the log:
undefined reference to `DHT::DHT(unsigned char, unsigned char, unsigned char)'

Could somebody please explain what is wrong here.
Thank you very much!

Are you sure you are using the correct method signature, it seems that this method signature of the constructor does not exist: dht = new DHT(7, DHT22); takes 2 args, versus what is the complain is 3 args, something is not right

In my opinion, the easiest way for the beginner is to use Platformio, it sets up CLion project automatically.
See docs for more info.

do you have any link to configure platform IO, I'm using CLion as an editor and arduino IDE to compile and deploy to microcontroller, if there is any guide available it would be helpful to share. thanks

@OmarS. see the edited answer. It also configures build tasks for uploading, so no need to use Arduino IDE. But read the docs carefully: remember pressing "build" hotkey for all tasks instead of "run".

Did you add your libraries to the cmake files?
I don't have any experience with CLion but undefined reference normally means that
the linker couldn't find the function/class your are using.
So make sure the libraries are compiled and the linker knows where to find the object files.


text:
Can't create an array of type const char*
I have something being returned as a const char* and would like to save it to an array.
I've tried this:
const char* book[amtBooks] = "";

and get this error:
error: array must be initialized with a brace-enclosed initializer

How about with const char* book[amtBooks] = { NULL };. This will initialize every book to a null pointer.

const char* book[amtBooks] is an array of pointers.
"" is an array of chars (with only a NUL character).

You can initialize an array of chars with an array of chars:
const char foo[] = "hello";

You can also initialize a pointer to char with an array of chars:
const char *bar = "good bye";

this works because of the “decay to pointer” feature of C and C++.
But initializing an array of pointers with an array of chars simply does
not make sense. An array of pointers to char could be initialized as
const char *book[] = {"hello", "good bye"};


text:
Reading names of files on sd card returning odd file names
When trying to read the file names from an sd card some are being returned with a ~1 and cutting off the full file name.
Initializing SD card...initialization done.
TEST.TXT        402
UNTITL~1        0
HELLOT~1        49
DATALOG.TXT     562288
ALONGN~1        0
done!

Is there any way I get the full file name of each file?
The code for this is from here: https://www.arduino.cc/en/Tutorial/Listfiles

That's the way the FAT filesystem works.
On the page you link to there's a link to a page on SDCardNotes.

FAT file systems have a limitation when it comes to naming conventions. You must use the 8.3 format, so that file names look like “NAME001.EXT”, where “NAME001” is an 8 character or fewer string, and “EXT” is a 3 character extension. People commonly use the extensions .TXT and .LOG. It is possible to have a shorter file name (for example, mydata.txt, or time.log), but you cannot use longer file names.

When you wrote the files to the file system you were on an OS that supports longer filenames. When filenames are too long there's an 8.3 name created automatically with chunks of characters removed and replaced with ~.

You have long filenames on your SD card. The SD library is too primitive to know what they are.
I'd suggest switching to FatFS (here is one implementation) which has the option of using long filenames.

Nice, didn't know about that.

@DaveNewton I'm not sure if that implementation enables long filenames, but the code it wraps certainly supports them.


text:
Do some variables not hold their value when a while loop is exited?
Sorry if i'm asking too many silly questions but i'm really stumped on this one. I understand if I set a variable inside a loop that that variable won't be within scope from the outside of the loop.
Usually I find that variables declared outside of a loop will be accessible inside the loop, modifiable within the loop, and hold their value when exiting the loop but in this case that doesn't seem to be happening.
There are books on the sd card.
I'm saving the name of each book to an array from within a while loop.
When the while loop is exited the array is still null.
How can I solve this? thanks
int amtBooks = 5; //this gets set previously but im not going to show all the code

// create an array the size of the amount of books
  char* book[amtBooks] = { NULL };

// assign the name of each book to the array
  int bookNum = 0;
  while (true) {

    File entry =  root.openNextFile();
      if (! entry) {
        break; // no more files
      }

    book[bookNum] = entry.name();

    Serial.println(book[bookNum]); // <--------PRINTS FINE HERE

    bookNum ++;

  }

  root.close(); // close the stream

Serial.println(book[0]); <---ONCE OUT OF THE WHILE LOOP NOTHING DISPLAYS?
Serial.println(book[1]);

note: you have inconsistent indentation in your code .... the first line and the last two lines should be indented 2 spaces .... they are on the same level as the while (true) { line .... the three lines of the if block should be indented 2 spaces less  .......... incorrect indentation adds confusion to debugging

this is not about Arduino. it is C

variables declared outside of a loop will be accessible inside the
  loop, modifiable within the loop, and hold their value when exiting
  the loop

This is correct.

in this case that doesn't seem to be happening.

It is happening. The reason it looks like it doesn't is that
book[bookNum] is a pointer: the address of some data in memory. You
can check that the pointer does hold its value by printing it:
Serial.println((uintptr_t) book[bookNum]);

However, the statement you used:
Serial.println(book[bookNum]);

has a different meaning. It doesn't print the value of the variable
(i.e. the pointer): it prints the characters that are stored at the
pointed-to address, up to and excluding the first NUL.
Your problem comes from the fact that when you declare
File entry =  root.openNextFile();

you have a variable that is local to the loop. Then, when calling the
method
entry.name()

you get a pointer to an array of characters that belongs to the entry
object. This pointer is only valid as long as the object is in scope. As
soon as it gets out of scope (at the end of each loop iteration), the
entry object is destroyed and all memory belonging to it is released.
At this point the pointer you saved is a “dangling” pointer: it points
to an area of memory that has already been deallocated.
The proper fix is to allocate yourself the memory you need to hold the
character arrays, as in:
for (int bookNum = 0; bookNum < amtBooks; bookNum++) {
    File entry = root.openNextFile();
    if (!entry) break;
    const char *name = entry.name();
    book[bookNum] = (char *) malloc(strlen(name) + 1);
    strcpy(book[bookNum], name);
    Serial.println(book[bookNum]);
}

If you know in advance the maximum length of a book name, you could
follow the advice of Jot and Juraj and statically allocate the maximum
space you may need. That would be safer in terms of memory management.

You store a pointer to char array name in File variable entry. The entry goes out of scope (is deleted from stack) and your stored pointer points nowhere.
You need char book[amtBooks][13] = {{0}}; and strcpy(book[bookNum], entry.name());

It helps if you know where the variables are located.
Local variables are located on the stack. They are created when entering a function and vanish when exit from a function. They can even be locally inside a if, for, while or other statement when they are declared inside that statement.
Global variables have a fixed memory location. They can be used from every function.
When a pointer is created and it points to nothing, then you may not write data to where that pointer it pointing to.
You create a array of pointers, but you need memory that you can use to store data. For example: char booknames[5][20]. An array of text is often copied with strcpy().

This entire piece of code is within the main do loop. There is something weird going on because even if I declare the array globally at the very top, setting the array values from within the while loop is not persistant. If I remove the while loop I can set the values of the array.  Within the while loop the array values are present but loses the values once exiting the while loop.

That is what I was trying to explain. It helps if you know where the variables are located. The actual text in your code is stored nowhere, since you use pointers. You have to create a memory location to store those texts. Not a pointer to something or nothing, but you need a memory location for the characters of the text.


text:
AT command parsing and listening for incoming SMS Arduino Leonardo SIM800H
I am trying to make a program that receives commands contained in SMS. The commands can be $CMD1 and $CMD2. Of course I need to verify the phone number of the sender by its last 6 digits. Other than this I have to ask and receive rtc clock information from the modem. AT commands format:
+CCLK: "YY/MM/DD,HH:MM:SS+TT" (works properly)
+CMTI: "SM",N (where N is the index number of the sms in the phone mem)
+CMGR: "REC READ","+1234567890","","04/01/01,00:00:00+00" (it reaches only the 15th char and hangs)
My code:
const long interval = 1000;
static long currentMillis;

byte searchcharpos = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256]; //Array to store the chars before parsing

char rtcy1[3]; //Current year  Format: yy\0
char rtcm1[3]; //Current month  Format: mm\0
char rtcd1[3]; //Current day  Format: dd\0
char rtch1[3]; //Current hour  Format: hh\0
char rtcmm1[3]; //Current minute  Format: mm\0
char rtcs1[3]; //Current second  Format: ss\0

char esemesemes[3];

byte pointingfinger = 0;

char enabledtime = 0;

char cclkenabl = 0;

char foundchar[6];

byte cmtienabl = 0;

byte witdqt = 0;

byte acceptsms = 0;

byte ocpos = 0;

byte occurence = 0;

byte cmgrenabl = 0;

byte esemindex[3];

char phone1[6] = {'5', '6', '7', '8', '9', '0'};

char phone2[6];

byte enableclock = 1;

void setup() {
  Serial.begin(9600); //USB to Computer
  Serial1.begin(9600); //UART to Modem
  Serial1.print("ATE0\r"); //Disable echo
}

void loop() {
  if (millis() - currentMillis >= interval) //This is done every second
  {
    if (enableclock == 1) {
      Serial1.print("AT+CCLK?\r");
    }
    Serial.println("=========");
    Serial.print(serialdata[searchcharpos]);
    Serial.print(serialdata[searchcharpos + 1]);
    Serial.print(serialdata[searchcharpos + 2]);
    Serial.print(serialdata[searchcharpos + 3]);
    Serial.print(serialdata[searchcharpos + 4]);
    Serial.print(serialdata[searchcharpos + 5]);
    Serial.print(serialdata[searchcharpos + 6]);
    Serial.print(serialdata[searchcharpos + 7]);
    Serial.print(serialdata[searchcharpos + 8]);
    Serial.print(serialdata[searchcharpos + 9]);
    Serial.print(serialdata[searchcharpos + 10]);
    Serial.print(serialdata[searchcharpos + 11]);
    Serial.print(serialdata[searchcharpos + 12]);
    Serial.print(serialdata[searchcharpos + 13]);
    Serial.print(serialdata[searchcharpos + 14]);
    Serial.print(serialdata[searchcharpos + 15]);
    Serial.print(serialdata[searchcharpos + 16]);
    Serial.print(serialdata[searchcharpos + 17]);
    Serial.print(serialdata[searchcharpos + 18]);
    Serial.print(serialdata[searchcharpos + 19]);
    Serial.print(serialdata[searchcharpos + 20]);
    Serial.print(serialdata[searchcharpos + 21]);
    Serial.print(serialdata[searchcharpos + 22]);
    Serial.print(serialdata[searchcharpos + 23]);
    Serial.print(serialdata[searchcharpos + 24]);
    Serial.print(serialdata[searchcharpos + 25]);
    Serial.print(serialdata[searchcharpos + 26]);
    Serial.print(serialdata[searchcharpos + 27]);
    Serial.print(serialdata[searchcharpos + 28]);
    Serial.print(serialdata[searchcharpos + 29]);
    Serial.print(serialdata[searchcharpos + 30]);
    Serial.print ("=========");
    //Serial1.print("AT+CCLK?\r"); //ask for the time
    //delay(50);
    Serial.println("");
    Serial.println("=====");
    Serial.println(millis());

    if (enableclock == 1) {
      Serial.println("YEAR: ");
      Serial.print(rtcy1[0]);
      Serial.println(rtcy1[1]);
      Serial.println("MONTH: ");
      Serial.print(rtcm1[0]);
      Serial.println(rtcm1[1]);
      Serial.println("DAY: ");
      Serial.print(rtcd1[0]);
      Serial.println(rtcd1[1]);
      Serial.println("HOUR: ");
      Serial.print(rtch1[0]);
      Serial.println(rtch1[1]);
      Serial.println("MINUTE: ");
      Serial.print(rtcmm1[0]);
      Serial.println(rtcmm1[1]);
      Serial.println("SECOND: ");
      Serial.print(rtcs1[0]);
      Serial.println(rtcs1[1]);
    }
    enabledtime = 1;

    currentMillis = millis();
  }

  if (enabledtime == 1) {
    if (Serial1.available () > 0) {
      foundchar[0] = foundchar[1];
      foundchar[1] = foundchar[2];
      foundchar[2] = foundchar[3];
      foundchar[3] = foundchar[4];
      foundchar[4] = foundchar[5];
      foundchar[5] = Serial1.read();

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'C' && foundchar[3] == 'L' && foundchar[4] == 'K' && foundchar[5] == ':' && enableclock == 1) {
        cclkenabl = 1;
        pointingfinger = 0;
      }

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'T' && foundchar[4] == 'I' && foundchar[5] == ':') {
        cmtienabl = 1;
        pointingfinger = 0;
        enableclock = 0;
      }

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'G' && foundchar[4] == 'R' && foundchar[5] == ':') {
        cmgrenabl = 1;
        pointingfinger = 0;
      }

      if (foundchar[0] == '$' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'D' && foundchar[4] == '1') {
        if (acceptsms == 1) {
          while (true) {
            Serial.println("CMD1");
          }
        }
      }

      if (foundchar[0] == '$' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'D' && foundchar[4] == '2') {
        if (acceptsms == 1) {
          Serial.println("CMD2");
        }
      }

      if (cclkenabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read();

          }
        }
        cmgrenabl = 0;
        cclkenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
      }

      if (cmtienabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read();

          }
        }
        cmtienabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        enableclock = 0;
        esemesemes[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        esemesemes[1] = serialdata[searchcharpos + 9];
        esemesemes[2] = '\0';
        esemindex[0] = serialdata[searchcharpos + 12];
        esemindex[1] = '\0';
        Serial.println("CMTI");
        Serial.println(esemesemes[0]);
        Serial.println(esemesemes[1]);
        Serial.println(esemindex[1]);
        if (esemesemes[0] == 'S' && esemesemes[1] == 'M') {
          Serial1.println("AT+CMGF=1");
          Serial.println("AT+CMGF=1");
          delay(100);
          Serial1.println("AT+CMGR=1");
          Serial.println("AT+CMGR=1");
        }
        if (esemesemes[0] != 'S' || esemesemes[1] != 'M') {
          Serial1.println("AT+CMGD=4,1");
          Serial.println("Deleted");
        }
      }

      if (cmgrenabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read(); //                       I THINK HERE WE HAVE SOME PROBLEM
            Serial.println("Searching");
            Serial.println(serialdata[pointingfinger]);
            Serial.println(pointingfinger);
            Serial.print(serialdata[searchcharpos]);
            Serial.print(serialdata[searchcharpos + 1]);
            Serial.print(serialdata[searchcharpos + 2]);
            Serial.print(serialdata[searchcharpos + 3]);
            Serial.print(serialdata[searchcharpos + 4]);
            Serial.print(serialdata[searchcharpos + 5]);
            Serial.print(serialdata[searchcharpos + 6]);
            Serial.print(serialdata[searchcharpos + 7]);
            Serial.print(serialdata[searchcharpos + 8]);
            Serial.print(serialdata[searchcharpos + 9]);
            Serial.print(serialdata[searchcharpos + 10]);
            Serial.print(serialdata[searchcharpos + 11]);
            Serial.print(serialdata[searchcharpos + 12]);
            Serial.print(serialdata[searchcharpos + 13]);
            Serial.print(serialdata[searchcharpos + 14]);
            Serial.print(serialdata[searchcharpos + 15]);
            Serial.print(serialdata[searchcharpos + 16]);
            Serial.print(serialdata[searchcharpos + 17]);
            Serial.print(serialdata[searchcharpos + 18]);
            Serial.print(serialdata[searchcharpos + 19]);
            Serial.print(serialdata[searchcharpos + 20]);
            Serial.print(serialdata[searchcharpos + 21]);
            Serial.print(serialdata[searchcharpos + 22]);
            Serial.print(serialdata[searchcharpos + 23]);
            Serial.print(serialdata[searchcharpos + 24]);
            Serial.print(serialdata[searchcharpos + 25]);
            Serial.print(serialdata[searchcharpos + 26]);
            Serial.print(serialdata[searchcharpos + 27]);
            Serial.print(serialdata[searchcharpos + 28]);
            Serial.print(serialdata[searchcharpos + 29]);
            Serial.print(serialdata[searchcharpos + 30]);
          }
        }
        //pointingfinger = 0;
        enabledtime = 1;
        occurence = 0;
        ocpos = 0;
        Serial.println("mode1");
        while (occurence < 7) {
          Serial.println("mode2");
          if (serialdata[ocpos] == '\"') {
            Serial.println("mode3");
            occurence++;
            Serial.println(occurence);
          }
          Serial.println("mode4");
          ocpos++;
          Serial.println(ocpos);
        }
        witdqt = ocpos;
        Serial.println("PHONE1: ");
        Serial.print(serialdata[witdqt - 1]);
        Serial.print(serialdata[witdqt - 2]);
        Serial.print(serialdata[witdqt - 3]);
        Serial.print(serialdata[witdqt - 4]);
        Serial.print(serialdata[witdqt - 5]);
        Serial.print(serialdata[witdqt - 6]);
        Serial.println("");
      }
      acceptsms = 0;

      if (serialdata[witdqt - 1] == phone1[5] && serialdata[witdqt - 2] == phone1[4] && serialdata[witdqt - 3] == phone1[3] && serialdata[witdqt - 4] == phone1[2] && serialdata[witdqt - 5] == phone1[1] && serialdata[witdqt - 6] == phone1[0])
      {
        acceptsms = 1;
        Serial.println("Accepted");
      }

      if (serialdata[witdqt - 1] == phone2[5] && serialdata[witdqt - 2] == phone2[4] && serialdata[witdqt - 3] == phone2[3] && serialdata[witdqt - 4] == phone2[2] && serialdata[witdqt - 5] == phone2[1] && serialdata[witdqt - 6] == phone2[0])
      {
        acceptsms = 1;
        Serial.println("Accepted");
      }

      /*Serial.println("");
        Serial.print(foundchar[0]);
        Serial.print(foundchar[1]);
        Serial.print(foundchar[2]);
        Serial.print(foundchar[3]);
        Serial.print(foundchar[4]);
        Serial.print(foundchar[5]);
        Serial.println("");*/

    }
  }
}

This is the Serial Monitor:

What is the exact question? You presented your project and your code. You want code for general AT command parsing?

I have some error that doen't allow me to see and parse the whole char array and get the phone number to compare. I cannot see what's wrong with my code.

That is the most bizarre serial parsing code I have ever seen. You're not making life easy on yourself with that stuff...

This might help you to write better parsing code: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/ and https://hackingmajenkoblog.wordpress.com/2017/04/08/splitting-up-text-in-c/

I also cannot comprehend that parsing code. You might want to start working on a general ATCmdParser like mbed-os has or look at the parsing code from other libraries which receive AT commands (example)

Or, in short: Read an entire line into the buffer, and only once the line is complete do you analyse it and decide what to do with it. A sliding window is not what you want for line-based ASCII communication.

how to detect what command I have? I did this with shifting values, but is there a better way?

You could write a unified "send command and parse response", which will send a command, read the entire response in a buffer until a delimiter is reached, then use custom parsing functions or simple sscanf to parse the data out of it, according to the sent command.

strncmp() on a properly formatted line (c string) buffer is what you want.

Thank you both, I will see what I can do with the new info and write here.

@Majenko why there isn't a break; in the switch statement in your line by line reading example?

For '\r' there is a return, so you don't need a break (it would never get there). For default it's the last entry, so you don't need a break (though you could put one there if you like).  I should really swap over the \r and \n entries - the \n is really the proper one to detect for a line ending.

There - I've updated it. It was such a long time ago I wrote that snippet...

Argh! I hate Wordpress! It just trashed my post!  C  * N * S! I hope I just got it back in there right again.

I am really sorry, hope your site is ok

You should throw away all your own code and read the serial data in a line at a time. Only once a complete line has been received should you then examine it to see what you have.
For example, here's something I just threw together based around a snippet I posted here:
int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
            buffer[pos++] = readch;
            buffer[pos] = 0;
        }
        break;
    }
  }
  return 0;
}

// ... later, in your loop:

if (Serial1.available()) {
    // Read one character and send it to the readline function.
    if (readline(Serial1.read(), serialdata, 512)) { // do you really need 512 bytes of buffer?!?!

        // readline() told us we got a valid string. Let's
        // parse it.

        // If the string starts with '+CCLK: "'
        if (strncmp(serialdata, "+CCLK: \"", 8) == 0) {
            // Slice it up by the different delimiters
            // starting at the 9th character:
            char *cyear = strtok(serialdata + 8, "/");
            char *cmonth = strtok(NULL, "/");
            char *cday = strtok(NULL, ",");
            char *chour = strtok(NULL, ":");
            char *cmin = strtok(NULL, ":");
            char *csec = strtok(NULL, "+");

            // Check the last slicing worked
            if (sec != NULL) { // It parsed OK
                // And convert each slice to a number.
                year = atoi(cyear);
                month = atoi(cmonth);
                day = atoi(cday);
                hour = atoi(chour);
                minute = atoi(cmin);
                sec = atoi(csec);

                // Show the time.
                Serial.print(F("The time is "));
                Serial.print(minute);
                Serial.print(F(" minutes past "));
                Serial.println(hour);
            }
        }
    }

    // Do similar operations for the different possible messages
    // you may get.

}


text:
Why when I pull an EEPROM index the value returned is garbage?
I have an array of colors for my tft screen:
const uint16_t colorTheme [] PROGMEM = {BLACK, WHITE, NAVY, CYAN, RED, GREEN, VERDEAQ, PINK, ORANGE, PURPLE, GRAY, YELLOW};

When I try to use colorTheme [EEPROM.read (2500)] I am returned with a value of any garbage, or a value of 0, and I checked it in read_eeprom and the value of EEPROM.read (2500) is equal to 4, and 4 in mine vector is cyan color, not black or 0 number, why does this go so wrong?

Your array is in PROGMEM, but you are accessing it as if it were in RAM.
You must use pgm_read_word() to access the data in your array.
pgm_read_word(&(colorTheme[EEPROM.read(x)]))

BTW - what Arduino board has more than 2kB of EEPROM?

Thanks, i'm using Atmega2560, he https://store.arduino.cc/usa/mega-2560-r3, your EEPROM is 4kb


text:
USB to Arduino to bluetooth
I have a piece of equipment that has a USB output, that a flash drive gets inserted into, to collect data as the equipment completes its cycles. I need to make a device that can replace the Flash Drive and take the data from the USB port and either save onto an SD Card, to re transmit when completed, or to transmit live as the cycles complete.
I was thinking about using a UNO, & a USB HOST Shield. to receive the data. Then transmit with a wireless or Bluetooth shield.
I have a "SANDISK WIRELSS FLASH DRIVE" which works as a flashdrive, and then you can connect it to other devices through wireless transmission, problem with it is, the wireless feature disables when plugged into the usb port. If the wireless stayed connected, then this would be exactly what I needed.
Any help or ideas, sample schematics would be welcomed.

can you mod the device? if you can make your wifi card disconnected in-situ your problem is solved.

There once was once something called an "Infinite USB Memory Drive" that acted as a thumb drive that read and wrote data to a networked share over wifi.
They aren't selling those anymore, but their approach might be what you need - network share to resolve the issue of multi- device connected to same drive.
In your shoes, I'd be looking at a Raspberry Pi Zero W (the one with wireless) instead of an arduino.  More computing options means more ways to solve your problems with the same hardware.

Your plan is flawed.
First, you don't want a USB host - a flash drive is a device, not a host. This unspecified unit that you are connecting to is the host.
Secondly you would require an Arduino a lot more complex than an Uno. You need one that is capable of operating as a USB MSD (Mass Storage Device), and the Uno or any other '328p-based device cannot do that.
The only two kinds of Arduino-like board that I know of that can do that are Teensy and chipKIT.
On top of that is a simple fact that is the reason your existing wireless flash drive doesn't work for you: only one thing can access a "block device" at once. If you had the USB and the wireless both accessing the flash drive at once you would get massive data and filesystem corruption - so it is just disabled.  You need to have some manual way of switching off one point of access and switching on the other - and of course safely "unmounting" the device to ensure that all cached data is written to the disk properly.

I appreciate to input. That gives me a better avenue to search.


text:
Specific ports on Teensy 3.6 not reading correct bit resolution using ADC library?
I have a basic circuit, where I'm reading analog values from 14 infrared receivers.
I set the bit resolution to 16 but specific ports are returning 10 bit values (from 0 - 1024) instead of 16 bit values (from 0 - 65536).
I can confirm this is not a problem with my circuitry because when I've tested reading each individual sensor with a port that "works" and the correct range is returned every time.

Here is my code:
#include <ADC.h>

ADC *adc = new ADC();
const int* RECIEVERS = (int[14])
{
    A15, A16, A17, A19, A20, A21, A22, A1, A2, A3, A6, A7, A8, A9
};

void setup() {
    Serial.begin(4608000);
    adc->setAveraging(16); // set number of averages
    adc->setResolution(16); // set bits of resolution
    adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS);
    adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED);
    for (int i = 0; i < 14; i++) pinMode(RECIEVERS[i], INPUT);
}

void loop() {
    for (int i = 0; i < 14; i++) {
        Serial.print(adc->analogRead(RECIEVERS[i]));
        Serial.print(" | ");
        delay(1);
    }
    Serial.println("");
}

Is there a problem with my code or is my Teensy damaged?

The Kinesis 66 (the chip on the Teensy 3.6) has two ADC modules. Each one talks to different pins.
By default the configuration functions in that library configure ADC0, so unless you tell it otherwise, you will only be configuring half the ADC pins.
You should call each of the configuration functions twice, once for ADC0 and once for ADC1:
adc->setAveraging(16, 0); // set number of averages
adc->setResolution(16, 0); // set bits of resolution
adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS, 0);
adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED, 0);

adc->setAveraging(16, 1); // set number of averages
adc->setResolution(16, 1); // set bits of resolution
adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS, 1);
adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED, 1);

Exactly it. Thanks so much.

In the new version of the Library that must be adc->adc0->xy and adc->adc1->xy


text:
Using a class inside of another class
I have a seemingly simple problem that seems to be popular, but after searching several forums I still have not found the answer: How do you use a class inside of another class?
I have simplified my problem:
class A {
  const int pin;
  public:
  A(int attachPin) : pin(attachPin) {
  }

  void setup() {
    pinMode(pin, INPUT_PULLUP);
  }
};

class B {
  A myA;
  public:
  B(int a_attach) : myA(a_attach) {
  }

  void setup() {
    myA.setup();
  }
};

B test;

void setup() {
   test.setup();
}

void loop() {
}

I think, the problem in that line B test. You are define a variable, but you forget to define default constructor ( B() ). You try to setup an A class with unknown pin! To avoid this you may define test variable in that way B test(2); or in that way const int test_pin = 2; B test(test_pin);. Also to avoid this problem you may to set default value to the constructor sucha as  B(int attach=2) : myA(attach) {} and define test variable, as you do in your code B test;.


text:
Esp8266 + Atmega328p as flash
Being clear I'm not talking about How to flash ESP8266 using arduino.
I want to ask how can I use atmega328p as flash with esp8266 (instead of that 8 pin small chip on ESP-01) so that I can burn Webserver code on Atmega328p and it simply works with esp8266?
Thanks in advance.

No. No you cannot.

Can I ask why? And if I need a webserver should I upload a code to Esp8266 seperatly and make atmega328p and esp8266 communicate via TX RX?

To do it you would need 1) a high speed (40mhz or better) spi slave interface, 2) hundreds of kB or even multiple mb of flash, 3) firmware to emulate a flash chip. The Arduino doesn't have 1 or 2 and writing 3 would be a chore.

To make a web server either install the at firmware on the esp and follow the examples or program the esp directly and use whatever communication method you feel is appropriate to talk to an Arduino if you really feel you need to have an Arduino at all.

why emulate the flash if every esp8266 module has the flash to which you can upload over the esp8266?

It can't be done (also, why would you think that would ever be a good idea?!)
The 8 pin chip on the ESP-01 is a 512kB SPI flash that runs at (at least) 40MHz.  So to emulate that you would need:

More than 512kB of flash,
A slave SPI interface that can operate at a minimum of 40MHz, and
The knowledge, time and energy to write the firmware to emulate an SPI flash chip

The first two are certainly beyond an ATMega328P with 32kB flash and an 8MHz maximum speed SPI interface. The third is probably beyond you since you have to ask the question in the first place (which shows a certain lack of knowledge on what it is you are proposing).
There are plenty of examples for creating a web server using an ESP8266 using either the standard AT firmware or by directly programming the ESP8266's flash chip through the ESP8266's built-in UART bootloader.  Personally I find the use of AT firmware clumsy at best and prefer to always program my ESP8266's directly.  If you feel the need to also add an ATMega328P into the mix for some reason then the communication protocol that you use between them is entirely up to you.


text:
Information about 'Arduino Nano 33 IoT'
blox w-102 is based on esp32** which (Esp32) can be used as a standalone chip for projects.
Here I want to know how w-102 and samd21g18a are communicating with each other.
If they are communicating then what is the need of doing so?

The Arduino boards with the NINA module: MKR 1010 WiFi, MKR 4000 vidor, Uno WiFi and Nano 33 IoT use the NINA module for WiFi networking with the WiFiNINA library and for BLE with the ArdunioBLE library. Additionally the flash memory of the NINA module will be available as storage.
The NINA module runs a firmware made by Arduino with ESP32 IDF framework.
I wired MKR ZERO with an ESP32 dev board for the WiFiNINA firmware and library according to MKR 1010 WiFi schematics, which is very similar to Nano 33 IoT. The MCUs are connected on SPI pins and UART for communication. The firmware uses one additional pin to signal to SPI master as 'ready' pin. Also io 0 and enable pin of NINA module are wired to put the ESP32 into flashing mode for firmware upgrade over UART.
On MKR 1010 and Nano33 IoT I2C is connected too. Boot MCU have access to on-board I2C sensors and could in theory communicate over I2C. This is currently not used.
The WiFiNINA library uses SPI communication. SAMD is master, NINA is slave.
The ArduinoBLE library communicates over UART. 'Ready' pin is used to switch to BLE mode in firmware at NINA reset.
The firmware uses io 0 as 'heartbeat' signal for the library.
My wiring:

the orange wire from MKR pin 5 is connected as reset to EN (with a wire under the ESP32 board)
io 0 of ESP32 is the yellow wire to MKR pin 4
VSPI pins 5, 18, 19, 23 (I changed 12 to 19 in firmware). white wire on MKR pin 7 and ESP32 pin 19 is CS
I used 22 as readyPin (originally 33). white wire on MKR pin 6
I didn't wire I2C and Serial here

The two chips are connected together by both UART and SPI channels.  I am unsure, but I think the main communication is performed over SPI and the UART is only used for programming and debugging of the NINA.


text:
DC Motor Shuddering
I am testing my BTS7960 Module with my UNO for bi-directional rotation of DC Motor. I am using a small DC motor as a test (like the one here) and I am powering the UNO via USB cable. The problem is whenever I try to shift it to take power from my MB102 supply instead of USB connector, the DC motor starts shuddering and stalling. But it runs completely fine when connected via USB cable.
I think there is something wrong with my connections but I can't figure out where.
The code is fairly straightforward and is attached below
void setup() {  // put your setup code here, to run once:

Serial.begin(9600);
  pinMode(2,OUTPUT); //R_EN
  pinMode(3,OUTPUT); //L_EN
  pinMode(8,OUTPUT); //L_PWM
  pinMode(12,OUTPUT); // R_PWM
  digitalWrite(3,HIGH);
  digitalWrite(2,HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(12,HIGH);
  delay(5000);
  digitalWrite(12,LOW);
  delay(1000);
  digitalWrite(8,HIGH);
  delay(5000);
  digitalWrite(8,LOW);
  delay(1000);
}

I am trying to find a good circuit simulator for the schematics for better visualization, if anyone has any leads it would be really appreciated
The connections are as follows:
DC 12V is provided to BTS7960. The R_EN and L_EN are connected to pins 2 and 3 of the Arduino. the R_PWM and L_PWM are connected to digital pins 8 and 12 of the Arduino. VCC and Ground are connected to +5 and GND pins respectively while another GND pin is connected to the DC12V negative.
When connecting MB102, DC12 is supplied via the Jack while the +5V and GND Headers are used to supply power to Arduino via Vin and GND Pin of Arduino respectively.

That's a lot of motor controller for a wee motor! It's unclear what the schematic looks like when you're running off the breadboard power supply, though, or why you'd need both a breadboard power supply and the power off the motor controller module.

Arduino Vin requires at least 7V to be powered properly, not 5V. It actually accept voltage from 7V to 12V, so connect the DC12V directly to the Arduino Vin which will be used internally to drive the regulator to generate the 5V.

@DaveNewton Like i said its only a test motor. I plan on using it to power 20A DC Motors for my carrier robot. The motor controller module requires 5V. i was initially giving it via the +5V Arduino pin but now am providing it through the breadboard supply

@hcheung Thanks a ton! That worked like a charm, the only problem is running 2 drivers simultaneously case the 2nd motor to be extremely slow. I guess it's because the DC 12V adapter gives 1.5 A current only which is insufficient for the second motor right?


text:
Differential voltage measurement using Arduino
I have a electrolysis cell in which the anode is hanging using a Structure in a electrolyte. The cathode is at the bottom of the cell with electrolyte above it and anode being dipped into this electrolyte (not completely, a portion of the anode is dipped). The cell operates at 7  volts DC and 90000 amperes of current flowing through it. This is a typical electrolysis process of producing aluminium from alumina powder in a aluminium smelter. The cell is called a pot.
Now the question is I need to measure a potential drop on the anode rod. We usually take a meter to measure the potential drop on the anode rod and typically the reading are in millivolts. As the readings are in millivolts, it just indicates the drop in rod voltage due to resistance of rod. Now can I measure this millivolts drop using Arduino provided the voltage at one point of anode is 5 volts with respect to ground and the voltage at the other point is 4.95 volts with respect to ground, however the difference between these voltages is 0.5 volts and this is voltage I need to measure using Arduino and some arrangements as add on to it. How can I do this?
Can anyone help.
If you want more details, please comment. I will also provide more details.
So far I have done is tried measuring 1.5 volts on a pencil cell using Arduino by connecting A0 analog pin on Arduino to positive directly to the positive of 1.5 volts battery and ground of Arduino to the negative of Arduino.
Can I do the same for this millivolts measurements? I understand that the ground of Arduino and the 2nd point of anode measurement will not be at same potential, so shouldn't be connected together. I am scared to burn my board, so didn't try practically and wanted to get some opinion.

90000 amps?! Are you sure? That's just over half a megawatt of power!

Lacking experience of high current applications, I'd never put an Arduino anywhere near something capable of pushing 90000 amps through it. I suspect it might be a problem to interrupt the arc current through the carbonised remains of the Arduino and nearby objects (/buildings). Maybe better qualified people can be bolder though.

Yes. An aluminium smelter typically consumes 1400MW of power for 0.5MTPA capacity.  Current wouldn't flow from Arduino as the anode is a conducting material made up of aluminium solid rods. The current flowing through Arduino would be really small i think. Because we can measure the voltage on the cell with a multimeter as well. So high amps shouldn't be a problem as far as I think.

@Majenko Smelting! Big power.

High current will always pass from the least resistance path and as the rod itself is highly conductive in nature, the dc current shouldn't pass through Arduino, however we will have to have some safety as well. I can't figure out a method to measure this potential difference. Or maybe I will have to open the existing meter and connect the measurement pin to the Arduino.

Yes smelting requires huge power. My company have another plant with 1.25 MTPA capacity and 3750 MW power plant. All big metals and mining companies have huge assets in power. For e.g rio tinto, alcoa, ega, chalco, qatalum, alba etc

Measuring a "differential" voltage is as simple as measuring two separate voltages and subtracting one from the other. As long as you have a common "ground" reference point there's no magic involved.

Consider using an isolated differential ADC

This is obviously a significant project, not something to economize on. I would recommend you use a separate difference amplifier to get a single-ended output referenced to the Arduino ground and scaled to maximize the 10-bit range use.  The diff amp can use its own supplies (+/-7.5 or +/-15, say) with the ground tied to the Arduino ground.  That way the Arduino only sees the difference, never the full 7 V no matter what.

As you do it with the multimeter: connecting ground to the lower potential (4.95 Volts in your example) and the volt probe to the higher potential (in your case 5.0 V), you can also connect the Arduino between the two potentials: Arduino GND to the lower (!) potential and A0, A1, ... or A7 to the higher (!) potential.
As long as you use the correct polarisation and the difference between the potentials is less than VCC of the ADC (5V Arduino ADCs) you should be save.
The resolution of the Arduino might be a problem. I don't know what resolution you need; 5V divided by 1024 is about 5 mV per step.
You might want to provide a reference Voltage at Vin of -let's say- 1 Volt if you need a better resolution. That would improve the resolution to about 1 mV per step. But then the meassured voltage must no exceed the 1 Volt reference voltage.
EDIT (Gerben's comment)
You could use the 1.1V internal reference of the ATMega328P (analogReference(INTERNAL))
And please let me give you a security advice: If the resistence in any part of your meassuring setup is significantly lower than the resistance between the messuring points (e.g you shorten the probe wires), then there is a chance that 90000 A running through this setup. That could burn away your hand, arm or even your life. Amperes kill; not Voltage. I've seen a wrench that was vaporized (ok, melted, ok glowing ;-) ) in a second, when it had fallen between the poles of a car battery (12 V; 300 Amps). An you operate with 90000 Amps. !

You could use the 1.1V internal reference of the ATMega328P (analogReference(INTERNAL))

@Gerben Yes that should also be mentioned. But I think even the 5 mV resolution is good enough in the 500 mV range. I just mentioned that there could be a problem with the resolution. Oh, and you brought me to another potential problem. If the measured Voltage can be higher than 1 Volt the idea of using  an alternative reference voltage may be not the best. Thank you!

Note that the Mega2560 has an ADC that can do differential measurements, with a programmable gain of 1×, 10× or 200×. This should solve the resolution problem.

Thanks all of you. I will read more into it. Thanks peter for clarification. This cleared a lot of doubts. Further there's no need to worry as entire potline in smelters is kept highly insulated and besides it's all DC, not AC. We can touch the DC terminal of any end as long as there's no potential difference and we are good to go with proper insulation. I have seen people directly working on these structures. Only thing is that, it gets really really hot as the electrolysis happens at 960-980 degrees, otherwise molten metal will not be produced.

I now have another question, we use a manual meter with an lcd. Can we read the values from that meter's lcd pin using digital pin read. I know it has to be pwm and the frequency may not be the same, however can anyone explain that part as well. @peter.

@surendrachoudhary A human body has some MOhms of resistance, so with max 5V there is no danger. But that is no example that can be compare with a conductor with a few micro ohms. You said you work in a highly isolated environment. So there should be no problem.

@surendrachoudhar To you second question: An LCD has many pins; seven for each segment and 1 for each decimal point. And all of theses are driven with alternating polarity to keep the LCD cristals alive. I dont think there is a practicable way to read out these pins. Does your meter has UART/RS232 or Bluetooth? That would be a much better way to read the meter.

No it doesn't have any communication media. That's the problem. I am planning to open the meter and check the insights. I will update here on this thread once I get more information about meter

@surendrachoudhar Please open a new question if you want to go deeper into the topic. And be sure it is still an Arduino question. Perhaps the Meter has an internal I2C or SPI Bus you could connect to the Arduino. But I fear that would lead to a loit of investigations about the protocol and to electronic questions. If the company can afford a Power Plat with many MWatts, I would expect a new Multimeter sould be affordable too. ;-) Sorry I could not resist.

Yes. I just wanted to get it done by ourselves. Actually I have made an android app to read data from Arduino and wanted to use the same for sending field measurements directly to our servers using this app. This will eliminate the need of logging readings on paper and will automate this process. However most important part of measurement is yet to figure out. :) Maybe I am going backwards. :)


text:
How to establish a connection between an Arduino and a web server via ESP8266
I'm working on a IOT project where three or more IOT device communicates with a web server. The IoT device will have Arduino UNO which is connected to a ESP8266 so internet access is available. Arduino UNO reads current sensor data and post it to a website that I built and I also want to control a single relay switch from the same website. I am a beginner and most project I find is only single directional communication or making ESP8266 as web server. Please point me to right Direction.
I was able to post sensor data to thingspeak.com. I was also able to control The relay switch from a website but only separately. I was not able to make it work when I combined the two.
Directions:

How to build web APIS to send and receive data to Arduino UNO via esp8266?
How to send data and check the received data in Arduino UNO VIA esp8266?
Can I send and receive data in JSON format Arduino UNO?
How can the Arduino UNO filter required data from the received json?
Is this project possible without Arduino and just by programming the ESP8266 module?

I know basic HTML, Basic CSS, Basic JavaScript, Basic Nodejs, json and a tiny bit of JQuery.

@MichaelT, it is not a duplicate of that question. in this question he wants 3 esp8266 communicate with a web server, not to run a web server on esp8266 with AT commands

Thank you @Juraj... that is exactly what I want. How can it be done?

@tonymathew, I wrote an Answer yesterday as I could to your broad question. read it and ask in comments

Is this project possible without Arduino and just by programming the
  ESP8266 module?

Yes if you use ESP-12 or an esp8266 dev board like Wemos or NodeMCU. The problem could be the current sensor. I would recommend to read it with I2C ADC module, because the esp8266 A0 can read only to 1 V and is shared with WiFi functions. Wemos boards use a circuit to read analog until 3.3 V, but it doesn't help much.

How to build web APIS to send and receive data to Arduino UNO via
  esp8266?

Run your Web server in Internet and let the esp8266 and clients communicate over it. But think about security.
For accessing a Web server from Arduino or esp8266 see the WebClient example of networking libraries.

How to send data and check the received data in Arduino UNO VIA
  esp8266?

For Arduino with esp8266 as network adapter connected to Serial you can use AT firmware in esp8266 and WiFiEsp library in Arduino. Or you can have a sketch for the esp8266 with Arduino esp8266 core package and your own protocol over Serial to communicate between esp8266 and Uno. And there are firmwares for esp8266 written as esp8266 sketch, which you can use with corresponding Arduino library (WiFiLink, WiFiSpi).

Can I send and receive data in JSON format Arduino UNO?
  How can the Arduino UNO filter required data from the received json?

ArduinoJson library helps with processing the JSON format. Amount of RAM could be a problem on Uno.

I not only want to post data to a web server and using this data the web server will automatically send an instruction to Arduino UNO to turn off the switch, also I should be able to manually turn the light on and off from the website

I am using ESP-01 ESP8266 and Current Sensor ACS712

the IoT device must check the server for commands (with GET requests). try Blynk service. it is good for remote controlling of iot device

I finall could HTTP GET and POST data to node_express server.. thanks for help.. heres link to my entire project https://github.com/tonyclx/Nodewifiesp/tree/master


text:
Arduino respond to input from HT12D data output
Is there a way to connect a data output pin from an HT12D to an Arduino or ESP8266-12e input pin, then sense when the data pin is activated so I can have the Arduino or ESP8266-12e do something like turn on an output pin?

What's a HT12D?

Sure, as long as the voltage levels are ok for the Arduino or ESP, just connect the data pins to digital input puts of the Arduino or ESP.

The ESP is 3.3v and I think the HT12D is 5v.  Could I use resisters as voltage divider.  What kink of code would I use to recognize the input?  HT12D is a unit that takes an RF signal and makes it a digital signal I think.

I am afraid I could not understand your question properly. But maybe, the answer is YES, if ...
First of all, OUTPUT pins, cannot be turned ON and turned OFF, however, you can start or stop READING that particular OUTPUT PIN based on another INPUT pin value.
If you want to connect HT12D decoder to any arduino or ESP, you must be aware to use same voltage level between IO PINS, a good approach is to use a I2C bi-directional level shifter.
if(INPUT_PIN_VALUE >= SOME_VALUE)
{
   digitalRead(PIN)
}

on the ESP I can make a pin D5 HIGH based on the reading of another input pin from the HT12D.  So if I used a l2C to make the 5v from the HT12D computable with the 3.3v ESP.  I could read the input level and then make another pin go HIGH in reaction.                                                                                digitalRead(D5);                                                                                if(D5>=SomeValue){                                                                          digitalWrite(D6,HIGH);

Disclaimer: In this answer I'm using ESP and Arduino interchangeably, as if they were the same. They are in context this question, but not in general.
First: According to the datasheet of the HT12D, the supply voltage can be between 2.4V and 12V, so you could just provide it with the 3.3V of your ESP. That way the output pins will also run on 3.3V. Then you can simply run a wire each from an output of the chip to a digital input pin of the Arduino.
Though you then should also provide your receiver chip with 3.3V. If that is not possible, you can provide the HT12D with 5V and use simple voltage dividers on each output to break the voltage down to 3.3V. That places restrictions on the transmission speed, but I don't think, that this is relevant here, as the outputs are more meant as momentary state outputs, not data transmission outputs. In that case you connect the output of the voltage dividers to one digital input pin on the Arduino each.
How to read the data:
The chip will read the data from the receiver on its Din pin. When it has found a valid transmission for the used address (which is configured through the address pins), then it will pull the VT pin to HIGH and output the new data on the pins. The datasheet says:

The HT12D, on the other hand, provides 4latch type data pins whose data remain unchanged until new data are received.

Let's imagine, that you have send the pattern HIGH, LOW, HIGH, LOW. The HT12D will see this as valid data and set it's outputs to this pattern. The VT pin is pulled high to show, that new valid data arrived. Now you can read this pattern into the Arduino via multiple digitalRead() calls, one for each output pin of the HT12D.
The surrounding code depends on your needs. For example you could just read the pins continuously again and again, every time just outputting corresponding on the data. For example like this:
void loop(){
    if(digitalRead(HT12D_pin1)) digitalWrite(LED_pin, HIGH);
}

Or even easier:
void loop(){
     digitalWrite(LED_pin, digitalRead(HT12D_pin1));
}

Or you could also read the VT pin of the HT12D and only do something, if it is HIGH. That way you only act, if there is valid data received.

For more info you really need to improve your question.


text:
activate a relay with two esp8266 -12e pins
I have an esp8266-12e that I want to activate the reset side of a latching relay.  The problem is that the 12e only puts out 12mA/pin and the relay needs more than that.  I am using a transistor on the set side from a rf antenna signal.  I only have one 3.3v power source.  Is there a way to have two pins go HIGH at the exact same time and be connected to the reset side of the relay so there is enough current?  Would this work, would it hurt anything, and how would I write the code for it and how would I wire it up?
I have tried the code where one pin is written HIGH right after the other like this
digitalWrite (5,HIGH);
digital Write (6,HIGH);

but I think pin 5 goes of before pin 6.
Any way to get them to go off at the same time?
Thanks for the help

No that's not a good idea.  You need to use a transistor to switch the relay.  You can drive the relay from an output pin.

I think you will need a transistor. On separate question that you asked, you can turn two digital pins on at the same time through port manipulation.

get power from power supply. use a pin to switch the power over a transistor

@hcheung Port manipulation like that isn't available on the ESP8266 where all the hardware interaction is performed through an SDK and the internal port -> pin arrangements aren't known (if they even exist).  Better is to use the tri-state functionality of the pins if you must do it at all.

That is not a good idea.
Isolating the relay from the IO pin is not just about the current limit of an IO pin, it's also about preventing back-EMF spikes from the relay coil(s) from damaging the delicate internals of the chip.
Instead you must at least use a transistor and a back-EMF protecting diode.
However - if you did want to theoretically have two pins safely controlled to provide double the current (though I stress again, do not do this for driving a relay), it is possible.
But it's not straight forward.
It's not possible on the ESP8266 to use port manipulation to make two pins change state at the same time. However it is possible to go via a third state that makes it safe.
Note: this will only be "safe" for IO pins that do not do strange things at bootup, and many of the pins on the ESP8266 do strange things.
IO pins actually have three states, not two:

High
Low
High Impedance

The latter is the state the pin is in when in INPUT mode. And we can use that to our advantage.
When in High Impedance mode it's like the pin is disconnected.  So we could:

Make sure both pins are in INPUT mode
Switch one pin to OUTPUT and set it to the desired state
Switch it back to INPUT mode (keeping the desired state latched)
Switch the other pin to OUTPUT and set it to the desired state
Set the first pin back to OUTPUT mode again.

This can be slightly compressed as we don't really need to set both pins to INPUT at the start, only one.  So here's some code that might do it:
void digitalDoubleWrite(int pina, int pinb, bool level) {
    pinMode(pina, INPUT);
    pinMode(pinb, OUTPUT);
    digitalWrite(pinb, level);
    pinMode(pinb, INPUT);
    pinMode(pina, OUTPUT);
    digitalWrite(pina, level);
    pinMode(pinb, OUTPUT);
}

You might ask why we'd want to switch to OUTPUT just to latch a level into the pin. Well, that's because of a quirk of the Arduino API. A historical artefact that is lingering in there to this day:

digitalWrite() on a pin set to INPUT mode was used to turn the internal pullup resistor on and off

It's actually how the AVR's IO ports control the pullup resistors internally, and that has most often been copied in software for other chips to maintain backward compatibility with old code. So as a result we have to switch to OUTPUT mode so that the API code knows that we mean to set the output latch state and not the pullup resistor state.

Thank you for your answers.  They are all very valuable.  I will make this one as the answer as it provides the most information for anyone wishing to get information.


text:
How can I program an Arduino Pro Mini with an ESP8266-01 connected to its TX and RX?
I am working on a project that uses an Arduino Pro Mini to gather information from various sensor. Once the readings are taken I turn on an ESP-01 from a separate dedicated 3.3v power supply. The ESP-01 then sends the info to Adafruit.
This works fine. My problem lies in programming the Arduino Pro Mini. If I program it separately (without the ESP attached) using FTDI connected to my Mac using Arduino IDE everything goes great and program is successful.
If however I have the whole thing connected up on the PCB board where the TX on the Pro Mini is connected to RX on ESP-01 and the RX on Pro Mini to TX on ESP I can't get the program to upload. It just keeps trying to connect but can't even though it recognizes the board via the USB port.
Is there anyway to work around this without unsoldering things. I just want to tweak a bit of the programming on the Arduino Pro Mini. Not a big deal but I would be nice. I soldered a female header onto the end of the Pro Mini for programming.
I am enclosing a visual of the connection set up when I am trying to program Arduino Pro Mini.

Thanks in advance.

(a) Can you get access to pins 11,12 ,13 and Reset on the PCB mounted Promini and (b) have you another Arduino (or ICSP programmer)  available?

Pretty sure you can use OTA uploads to the pro mini via the attached ESP01. A bit of googling should confirm.

Pins 11, 12, and 13 are connected to other things on PCB mounted Pro Mini.  I do have other FTDI programmers and have tried different ones in different USB ports with no difference.  I don't know if the small update to the Pro Mini is that important that I want to go through the hassles of setting up OTA but that is an interesting idea.  Thanks.  Since it works with another Pro Mini connected up the same wayI think it has to do with maybe the header on the Pro Mini.  I'm going to try to remove it and resolder another one on.  Or maybe just live with what is programmed already.

You could try connecting a temporary jumper between the esp01 pin CH_PD and GND. Find a pinout diagram. It is one of the pins broken out on the 8 pin header. This is the "enable" pin of the esp01. Grounding it will have the effect of disabling the esp01 and may prevent it interfering with the attempt to upload code to the pro-mini. This would be less hassle than attempting an ICSP type upload. If this works, I'll add a formal answer to the question.


text:
Why are times different on different Arduino Pro Minis?
I am working on a project using a 5v Arduino Pro Mini. To save power I have it power down and wake up every about 15 minutes to check on the battery strength and then power down again. This cycle runs 8 times when I have it wake up and then run through my main code, checking sensors and then handing those reading off to an ESP8266-1 to send the information to Adafruit. I have built three units using the same components/configuration and the exact same code. On one of the Arduino Pro Minis the elapse time is about 1hr 55min. on another it is about 1hr. 56min. 30seconds while the third is about 1hr. 59min. 50seconds. Why is there a difference between the three. I can understand being a few seconds different based on how fast the ESP8266-1 connects to the internet and transmits the data but a difference of 4minutes I don't understand. Can someone explain why this happens? Or should I be posting this somewhere else. Thanks.

probably dependent on the code

What do you use to wake up? Could you reduce your sketch to a minimum, reproducible, and complete example? Please [edit] your question to add new information.

WiFi scan will take from 6s to sometime more than 10s... Connecting to a server could also varies depend on network traffic and server readiness... If you program your Arduino Pro Mini to only wake up once at 2 hour, will you still see the difference of 4 mins? Also, are you using the external crystal during power down mode, or the internal oscillator (8MHz or 128KHz) on your Pro Mini?

The Arduino Mini Pro uses the ATMEGA328 processor. That processor has six sleep modes (described in this data sheet).
Beyond that, there are techniques one can explore to extend power savings down to the mA range and less. One such possible technique could use the WDT which runs on an internal oscillator to wake up the processor.
From the data sheet:

Atmel ® ATmega328P has an enhanced watchdog timer (WDT). The WDT is a timer counting cycles of a separate on-chip
128kHz oscillator

The slower oscillator will likely save on power requirements. However, it is unlikely such an oscillator will be as accurate as the higher frequency crystal based oscillator used by the ATMEGA328 during normal operation.
If the length of sleep needs to be more accurate, consider adjusting the sleep time to compensate for processor to processor discrepancies. Note, the internal ATMEAG328 128kHz oscillator may not be as stable across temperature changes as a crystal based oscillator.

This 128 kHz oscillator is indeed notoriously inaccurate and unstable... but it draws very little power.


text:
Why can't I post an image to the Image Block feed on Adafruit?
I am using an AI Thinker Cam32 to subscribe and publish to my Adafruit.io account.  I am using Adafruit_MQTT.h and Adafruit_MQTT_Client.h libraries. I am using ArduinoIDE on a MacBook Pro running MacOS Sequoia 15.1.
I am able to publish a simple uint32_t x=1 and Subscribe to two feeds.  I can get the value of those feeds and turn on and off pins on the ESP32 depending on the values from one feed.  From the other feed I would like to take a photo and Publish the Image to the Image Block feed when the subscribed feed is a certain value.
I have been able to Publish an image from the ESP32 using PubSubClient.h library but would prefer using the Adafruit libraries.
Here is the code I use to connect to the Wifi, my Adafruit account, and Subscribe and Publish to that account.
#include "Arduino.h"
#include <WiFiManager.h>
//#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include "src/OV2640.h"
#include <string.h>
#define CAMERA_MODEL_AI_THINKER
#include "camera_pins.h"
#include <base64.h>
/************************* WiFi Access Point *********************************/

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883                   // 8883 for MQTTS
#define AIO_USERNAME    "VVVVVVV"
#define AIO_KEY         "aioXXXXXXXXXXXXXXXXXXXXXXX0eL"
#define LED 14
int tripper = 1;
OV2640 cam;

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

/****************************** Feeds ***************************************/

// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
Adafruit_MQTT_Publish camera1 = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/camera");
Adafruit_MQTT_Publish wifi = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/wifi-connection");

// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe trip2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/video");

/*************************** Error Reporting *********************************/

Adafruit_MQTT_Subscribe errors = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/errors");
Adafruit_MQTT_Subscribe throttle = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/throttle");

/*************************** Sketch Code ************************************/

// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();

void setup() {
  Serial.begin(115200);
  delay(1000);

  Serial.println(F("Adafruit MQTT demo"));

  // Connect to WiFi access point.
 WiFiManager wifiManager;
 wifiManager.autoConnect("LEVEL2");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.println("WiFi connected");
  Serial.println("IP address: "); Serial.println(WiFi.localIP());

  // Setup MQTT subscription for onoff feed
  mqtt.subscribe(&trip2);

  // Setup MQTT subscriptions for throttle & error messages
  mqtt.subscribe(&throttle);
  mqtt.subscribe(&errors);

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  config.frame_size = FRAMESIZE_SVGA;
  config.jpeg_quality = 10;

  config.fb_count = 1;

  cam.init(config);
}

uint32_t x=1;

void loop() {

  MQTT_connect();

  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    if (subscription == &trip2) {
      Serial.print(F("Got onoff: "));
      Serial.println((char *)trip2.lastread);
    uint16_t sliderval = atoi((char *)trip2.lastread);
      if((sliderval ==0)&&(tripper == 1)){
        camera_fb_t *fb = NULL;
    fb = esp_camera_fb_get();
    //delay(500);

    if (!fb)
    {
      Serial.println("Camera capture failed");
      return;

    }
    else
    {
      Serial.println("Camera Captured");

    }

   //ADAFRUIT REQUIRES IMAGES BE BASE64 ENCODED

     size_t size = fb->len;
   String buffer = base64::encode((uint8_t *)fb->buf, fb->len);
    //String buffer = base64::encode(fb->buf, fb->len);
    Serial.println(buffer);

    unsigned int length();
    Serial.println("Buffer Length: ");
    Serial.print(buffer.length());
    Serial.println("");

    if (buffer.length() > 102400)
    {
      Serial.println("Image size too big");
      return;
    }

Serial.print(F("\nSending camera1 val"));

  Serial.print(buffer.c_str());
 Serial.print("...");

 //THIS IS WHERE IT CRASHES AND RESTARTS

  if (! camera1.publish(buffer.c_str())) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }
        tripper = 2;
         buffer = "";
      }

      else if((sliderval == 8)&&(tripper == 2)){

        tripper = 1;
      }
    } else if(subscription == &errors) {
      Serial.print(F("ERROR: "));
      Serial.println((char *)errors.lastread);
    } else if(subscription == &throttle) {
      Serial.println((char *)throttle.lastread);
    }
  }

  // Now we can publish stuff! 01
  Serial.print(F("\nSending wifi val "));
  Serial.print(x);
  Serial.print("...");
  if (! wifi.publish(x)) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }

delay(5000);

}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");

}

Here is the log crash report.
Sending wifi val 1...OK!
Got onoff: 0
Camera Captured
/9j/4AAQSkZJRgABAQEAAAAAAAD/2wBDAAoHCAkIBgoJCAkLCwoMDxkQDw4ODx8WFxIZJCAmJiQgIyIoLToxKCs2KyIjMkQzNjs9QEFAJzBHTEY/Szo/QD7/2wBDAQsLCw8NDx0QEB0+KSMpPj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj7/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1E I removed most of the stream to shorten the post. I can put the whole thing in if you need it //Z
Buffer Length:
27712

Sending camera1 val/9j/4AAQSkZJRgABAQEAAAAAAAD/2wBDAAoHCAkIBgoJCAkLCwoMDxkQDw4ODx8WFxIZJCAmJiQgIyIoLToxKCs2KyIjMkQzNjs9QEFAJzBHTEY/Szo/QD7/ again I shortened the post  //Z...

Backtrace: 0x6a537667:0x3ffbed0c |<-CORRUPTED

Backtrace: 0x00667fbd:0x00667fc0 |<-CORRUPTED

ELF file SHA256: 474b6a6f54754d5a

Re-entered core dump! Exception happened during core dump!
Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1344
load:0x40078000,len:13964
load:0x40080400,len:3600
entry 0x400805f0
Adafruit MQTT demo

I have tried different things to get the post to work but to no avail.  If I change the part where it crashes to
if (! camera1.publish(x)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}

the program doesn't crash, the OK! is printed out and the block feed says it was updated but with no imaged displayed.
I don't know what is corrupted since I have tried three different CAM32 with the same results.  Do I need to use different code to do the publishing of an image?  Does the Adafruit_MQTT.h library allow for the Publishing of images?
I would really appreciate any and all help anyone could give me.
Thanks

I see the output for the ESP8266 12e is 12mA per pin where the output for the ESP32 CAM is 20mA per pin.  I don't think this should cause a problem.  Maybe if it were less but not if it is more mAs  What do you think.

Got this to work.  Changed IO12 pin for IO14pin.  Also rebuilt a whole new board to make sure all components were good.  Works like a charm.  Thanks for all the input.


text:
Incompatible types in assignment of 'uint8_t {aka unsigned char}' to 'uint8_t [1] {aka unsigned char [1]}'
I'm trying to send custom data. But it doesn't seem to work. I can't find a way to parse my string to a unit8_t. I tried to follow other people's solutions but they don't seem to work for me.
// Declaration
uint8_t myData[] = "";

void loop(){
    myData = *(uint8_t*)atoi("custom string".c_str());
}

This is the error message that I keep getting:
Incompatible types in assignment of uint8_t {aka unsigned char}' to 'uint8_t [1] {aka unsigned char [1]} .

What are you attempting to do there? Are you trying to convert a textual representation of a number into an actual number, or place a bit of text into a uint8_t buffer?

So you are constructing a C++ String object from a C-String literal, then retrieve the C-String from it and try to parse a number from it (which it does not contain). Makes totalle sense to me....

@Majenko I am  trying to place a bit of text in a uint8_t buffer, because I am trying to send data over the LoRaWAN network. If I declare myData[] as myData[] = "Test data"; It send over the network without compiling errors. When I try to put a string into myData after going through setup and in my loop it doesn't seem to be able to add this as simply as myData = "Custom String";

What is "custom string".c_str() supposed to mean? In modern C++ you can do "custom string"s.c_str(), but only if you do using namespace std::string_literals; first.

atoi is for converting a textual representation of a number ("123" for example) into an actual integer.
The c_str() function gives you a pointer to the internal buffer of the String (assuming you actually have a String) which is no different to a uint8_t[] or uint8_t * (other than the signedness).
Without knowing exactly what the destination function for this buffer requires it's very hard to help you, but you may want something like:
LoRaWan.send((uint8_t *)myString.c_str(), myString.length());

If you need to copy the data into a fixed length buffer then you need to first create a buffer of that actual size - then copy the string data into it:
// Create a buffer of 32 bytes
uint8_t myBuffer[32];
// Copy at most 32 bytes, but no more than there actually is, into the buffer
memcpy(myBuffer, myString.c_str(), min(myString.length(), 32));

I used your method and deleted the atoi method. I understand the methods a lot more now. I also added a pointer to my declaration variable like uint8_t* myData[2];

That will actually create an array of two unassigned pointers, not a pointer to an array of 2 bytes.

@MounirMehjoub This might help: https://majenko.co.uk/blog/arrays-pointers-what-c

Your code is a mess. It's clear you are badly confused between arrays, pointers, and C++ strings.
When you say
uint8_t myData[] = "";

you make myData of type "array of uint8_t" and make it contain an empty string. You should not then change that value.
When you say
uint8_t *myData;

it means that myData is a variable of type "pointer to uint8_t", but it doesn't point to anything yet.
With that declaration, you can later say:
myData = "custom string";

That points the myData pointer to the address of your constant string. I think that's what you want:
// Declaration
uint8_t *myData;

void loop(){
    myData = "custom string";
}

Yeah, I'm sorry @Duncan C you are right. I'm not really experienced in C++ with pointers. So I tried your resolution but It gave again an error. cannot convert 'String' to 'uint8_t* {aka unsigned char*}' in assignment. What I'm trying to do is convert a custom string to uint8_t so I can send it over LoRaWAN. The method for sending LoRaWAN messages that I use had uint8_t as a parameter.

Re “You should not then change that value”: There is no problem changing that value. Just be aware that it's an array of length 1.

Firstly, arrays in C and C++ are not assignable. So, your attempts to assign something to myData array with = operator are bound to fail in any case. Copying data into naked arrays should be done either manually or using library functions.
Secondly, your myData array is declared with size 1. It is just one byte. It is too small to store anything useful. It will not magically "stretch" by itself to accommodate more data. If you need to store more data in that array, it is your responsibility to declare with the appropriate size in advance.
Thirdly, what is "custom string".c_str() supposed to mean??? Something looking very similar to that can be expressed in modern C++ as
#include <string>
...
using namespace std::string_literals;
"custom string"s.c_str();

but I see no reason for that at all. If your input is a C-string, then function atoi is directly applicable to C-strings. No need to convert such C-string to std::string and then back.
Fourthly, atoi is a "dead" function that exists for compatibility with legacy code only. You are not supposed to use atoi in your code. A C-style string-to-number conversion functions are functions from strto... group. E.g. strtol in your case. But in C++ you might have better options, like std::stoi and such.


text:
Difference between L298 and L298N motor driver
I was planning to buy a motor driver for my project purpose, but I don't understand which motor driver will suit my purpose. As there are two motor drivers available online. Can someone explain me the main difference between the two :
L298N : https://www.amazon.in/L298N-Based-Motor-Driver-Module/dp/B01N1H97CL
L298 : https://www.amazon.in/Robodo-L298-Motor-Driver-Module/dp/B00N4KWYDE?tag=googinhydr18418-21

Have you looked into the datasheet?

L298 is the name of the chip. The most often used variant is the L298N. The so called Multiwatt L298.  I would say, both boards use the same chip. L298N. The other variant are L298HW and L298P (horizontal Multiwatt and SOIC packaging).

The chip itself can drive up to 4A but the boards may differ. The L298N called board is specified with 2 Ampere.  The L298 called board is described with 2A too.

Those are exactly the same boards just viewed from different angles.


text:
Pulse Sensor Working Bottom-Side-Up Better?
i recently bought me an pulse-heartbeat sensor.
Connected him to my brand new M1 mini as well.
I wrote a piece of Code which just outputs the Raw ADC Value from A0 (where the pulse sensor is connected).
Now I'm confused.. When i open Serial Plotter, i get this:

Which is confusing because i don't get useable Values when putting the sensor up side down, which is the promoted way to do this (i guess!!)
When i press the other side against my wrist, i get this:

Which i can work with..
But it still doesnt look like some of those perfect diagrams on the internet.
Any can help me understand why i get this type of behaviour?
thanks, nice friday , luca

is that the correct usage of the device? ... what happens if you put your finger on the sensor?

Need to build a watch  So there are some significant  cons to put it on finger

place the sensor as it is in the picture ... cover the sensor so that extraneous light does not get to it ... wrap a towel around your wrist, for example

„cover the sensor so that extraneous light does not get to it ..“, thanks mate nice tip

From what I see, this is a pulse sensor that work with light. It emits a bright light beam, that is reflected by the pulsing blood. To work, it must send the light directed to your veins. It should work well on your finger, because the probability to target a vein directly is much greater with a small finger then e.g. a wide wrist. Also the veins in your finger are closer to your skin and the oxygen situation is more different while pulsing, so the blood has more impact on the reflection.
The second curve might be a light source in your room, or an electrical wave. (?) I doubt it is your heart, because, if the numbers below the graph are milliseconds, then your heartbeat would be between 10-15 beats / second, i.e. 600 - 900 per minute. That would be too much even for a hummingbird ;-).

Thanks for the input!


text:
How can I make YX5300 MP3 player play song in a loop?
I am doing a Christmas project and I have an ultrasonic sensor that detects if a person is In front of it. I want that if someone is in front of it, it lights up LEDs, which it does, and it also has to play a Christmas song, which it doesn't. I tried to make it play the Christmas song but nothing happens. Also the LEDs are only blinking when you put ur hand in front of the ultrasonic sensor. I want it to light up the lEDs for the same amount of time the song is, 28 seconds, and than the lEDS should stop and the ultrasonic sensor should wait for another person and it repeats. I am new to this so please be specific in your reccomendations.
Here is my code:
#define trigPin 10
#define echoPin 13
#include <SoftwareSerial.h>
#define ARDUINO_RX 7//should connect to TX of the Serial MP3 Player module
#define ARDUINO_TX 6//connect to RX of the module
SoftwareSerial mySerial(ARDUINO_RX, ARDUINO_TX);
static int8_t Send_buf[8] = {0} ;
#define CMD_SEL_DEV 0X09
#define DEV_TF 0X02
#define CMD_PLAY_W_VOL 0X22
#define CMD_PLAY 0X0D
#define CMD_PAUSE 0X0E
#define CMD_PREVIOUS 0X02
#define CMD_NEXT 0X01

int red1 = 5;
int red2 = 4;
int green1 = 3;
int green2 = 2;

long lCnt = 0;
unsigned long lStart;

void setup(){
  Serial.begin (9600);
  mySerial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(red1,OUTPUT);
  pinMode(red2,OUTPUT);
  pinMode(green1,OUTPUT);
  pinMode(green2,OUTPUT);
  delay(500);//Wait chip initialization is complete
  sendCommand(CMD_SEL_DEV, DEV_TF);//select the TF card
  delay(200);//wait for 200ms

}

void loop(){
  float duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0344;

  if(distance > 0 && distance <=60){

    digitalWrite(red1,HIGH);
    delay(50);
    digitalWrite(red2,HIGH);
    digitalWrite(green1,HIGH);
    delay(50);
    digitalWrite(red1,LOW);
    delay(50);
    digitalWrite(red2,LOW);
    digitalWrite(green2,HIGH);
    delay(50);
    digitalWrite(green1,LOW);
    digitalWrite(green2,LOW);
    delay(50);
    sendCommand(CMD_PLAY_W_VOL, 0X1E01);
  }

}

void sendCommand(int8_t command, int16_t dat)
{
  delay(20);
  Send_buf[0] = 0x7e; //starting byte
  Send_buf[1] = 0xff; //version
  Send_buf[2] = 0x06; //the number of bytes of the command without starting byte and ending byte
  Send_buf[3] = command; //
  Send_buf[4] = 0x00;//0x00 = no feedback, 0x01 = feedback
  Send_buf[5] = (int8_t)(dat >> 8);//datah
  Send_buf[6] = (int8_t)(dat); //datal
  Send_buf[7] = 0xef; //ending byte
  for(uint8_t i=0; i<8; i++)//
  {
    mySerial.write(Send_buf[i]) ;
  }
}

Thanks

I think you want to use the command [Single cycle play] which is 7E FF 06 08 00 00 01 EF (the 00 01 towards the end is the song number to play).
All the commands are detailed in the manual.

Where should I put that in my code?

@elimar008 in place of your current play command. You may want to add a set volume command as well.