text:
Detecting step motor effort
I'm working on a project using steper motor which turn a threaded shaft (long screw) in order to open or close a water valve (high flow, high pressure).
My fear is that, after a long time of use, the grease on the threaded shaft will dissapear and it can became hard for the stepper motor to rotate correctly the threaded shaft.
In order to tell the user to add grease, I have to know when the stepper needs more effort than before to rotate the threaded shaft. So, would it be possible to detect the "effort" made by the stepper in order to get this information on the Arduino?
Any ideas are welcomed!

I'm voting to close this question as off-topic because it is about electromechanical systems, not about Arduino.

I suggest that if the answer involves the Arduino, the question might be appropriate to this forum.
If you can mount your stepper motor in such a manner as to apply pressure to a force sensor, you may have a method to resolve your goal.
As the motor rotates, under normal conditions, pressure on the sensor will give you a baseline on which you can base your program for consideration of the amount of force involved.
Picture the motor mounted in the center of a circle, with cut-outs appropriate for the mounting bolts. On the outside of the circle, you would have suitable bearing surfaces to reduce rotational friction. From the motor circle platform, a lever pressing against a fixed point on the outside of the circle provides the contact points for the pressure sensor.
If you will be rotating the motor in both directions, perhaps a pair of sensors mounted to encase the lever would be suitable.
When the screw is new, clean and lubricated, you can collect pressure readings and establish a safe and comfortable range. Those numbers would be fixed into your code and measured during motor activity.
If the activity results in force outside the range, you can either stop or reverse the motor and have the same checks apply.
The logic and code is beyond my capability, but you'd have very few parameters to examine during operation.

Nice idea. As I'm going to have more than one system, with this idea I can also make some statistic, in order to know the limit. Thanks!

After fred_dot_u answer I have made other research. Not sure this can help us (Look Alterno and me), but some post are talking about "can I detect the over intensity".
Here is a very interresting post (in French, but Google Translate can help). The guy use and Arduino to control a step motor using to open a fence. And he wants to detect when the motor need more effort:
http://forums.futura-sciences.com/electronique/687244-lecture-de-lintensite-dun-moteur-un-arduino.html
Here the text from this site, I translated:

QUESTION
Hello everyone, I have a DC motor powered at 30 V. In normal
  operation, it consumes 2.5A (the power supply is OK, no problem on
  that side). It is an electric gate motor (sliding gate). I want to
  control it with an arduino. So far, not too much trouble, I go through
  a MOSFET (for the moment, I do not run the engine in one direction,
  later, I will make a bridge in H to go both ways). All this works well
  but I would also be able to detect when the engine forces (to stop
  it). When the motor forces, it consumes more, so more intensity in the
  circuit. The problem is that an Arduino can not read an intensity, I
  can only read a voltage between 0 and + 5V. So I was thinking of
  putting a resistor in series with the motor and measuring the voltage
  across the resistor with the arduino. If I take a max intensity not to
  exceed 5 A, Ohm's law gives me a resistance of 1 Ohm to have a voltage
  of + 5V (I'm good?) The problem is that a resistance of 1 Ohm at 5A
  will dissipate 25W (R x I x I, I'm always good?). How to solve this
  power dissipation problem? the big resistors I have at the moment are
  3/4 W, they will not take long
My problem is the following: if I take a smaller resistance to have a
  smaller power (like 0.1 Ohm or less), the voltage has its limits will
  be too low to be read by my arduino,
How to do ? Does anyone have an idea?
Thank you in advance for your answers.
Steph.
ANSWER 1 Just amplify the signal: rail-to-rail operational amplifier
  (to power it with a single positive voltage), a non-inverting device
  with a gain of 10 for example.
ANSWER 2 Indeed, it's an idea. So I was thinking of putting a resistor
  in series with the motor and measuring the voltage across the resistor
  with the arduino. . The risk of this type of assembly is:
  - the maximum voltage overshoot (5V) at the input of the uC (ARDUINO) at the change of direction (see ground point).
  - the maximum voltage surge (5V) at the input of the uC (ARDUINO) in the event of a break in the resistance. Explanations: The ARDUINO
  board must have a common point (Ground) and an Ax input, therefore
  when changing polarity (change of direction of the motor) the DDP is
  no longer 0V-> 5V but 0V-> 30V and there it smokes, ditto in case of
  rupture of this resistance. The good solution in my opinion would be a
  system like http://www.gotronic.fr/cat-courant-1125.htm
  Regards

The answer 2 give link to products like the i-Snail-VC: Current Transducer with 0-5VDC Output. Can be linked directly to the PIN of an Arduino.

Link-only answers are prohibited.  To be a valid answer, sufficient technical information must be contained in the answer posting itself that it will still be usable even if the off-site link ceases to function.

A few ways, assuming that it is a DC motor.

Measure the current through the motor: current is proportional to torque, everything else being equal.
Put a strain gauge on the axle.
Put a frictional plate on the axle.

...
Or to completely abandon the idea and control the movement via a position sensor.

Yes, most certainly. Use an ammeter to detect the "effort" required to actuate the motor. Both hall-effect and series measurements are acceptable here. Make sure to sample and average because motors can cause huge current spike (both positive and negative) which confuse naive readings. If your averages are climbing, as they eventually should, you know that it's getting harder to do the work. The hard part is deciding how hard is "too hard", and that depends on a lot of factors you're in the best position of judging.

I think deciding how hard is "too hard" can be made only by testing and set a "range" on the Arduino. In some case, reachin the "too hard" point will need to reverse motor. In my case I can have a range and say "Its not TOO hard,but it start to be not as easy as before so you must add some grease".


text:
ESP32 and SQLite - ALTER TABLE problem
I'm using an ESP32 and SQLite3 from https://github.com/siara-cc/esp32_arduino_sqlite3_lib
Everything is OK except the ALTER TABLE command.
When I try
    ALTER TABLE TAB_JOUEUR RENAME TO TAB_NEW_JOUEUR

I get a "SQL logic error". I just see that the default source code will not compile with the ALTER TABLE option if SQLITE_OMIT_ALTERTABLE is defined.
So at the begining of the .c source, I added:
 #if defined(SQLITE_OMIT_ALTERTABLE)
      #undef SQLITE_OMIT_ALTERTABLE
#endif

But result is the same.... Any idea?

Looks like a known problem with no known fix: https://github.com/siara-cc/esp32_arduino_sqlite3_lib/issues/10

Thank. i'll see if it's also the case with add field.

Well. After searching a lot here's the way todo a "RENAME" for a table. It's a bit tricky...
Renaming table in ESP SQLite is very interesting because SQLite has very limited features for editing table. So you can't add field, remove and so on. The only way is to create a new tmp table, copy the content of the orginal one into this tmp table, drop the original one and rename the tmp with the name of the new one.
DROP TABLE is OK with the ESP version of SQLite, but as said in the question, ALTER RENAME don't work.
So here is the way to do:
1-What tables do we have?
When we init the ESP, we call
  sqlite3_initialize();

and then we give SQLite the file it will use for saving data with a call to sqlite3_open() giving the name of a previously created file.
All our own tables will be saved into this file but also definitions of our tables. For that, SQLite create system table. So in the database we have our own tables but also the SQLlite system tables
2 - The data base schema table
One of the most important table is the database schema one. Its name depend on the version of SQLite. With the version we use on ESP8266 or ESP32, its name is sqlite_master .
This table has 4 fields:

type. Value can be  'table', 'index', 'view', or 'trigger'
name. Value is the name of the data. If type='table', name is the name of
the table defined in this record
tbl_name. Name of the table. So if type='name', tbl_name = name
rootpage. An int which is the index in the Btree used by SQLite to
access the data
sql. The code to create the table

3-Check the schema
To check the content of this specific table, just make a  CREATE TABLE then SELECT * FROM sqlite_master
Here is what I've done and the result:
The CREATE TABLE CALL:
create TABLE    IF NOT EXISTS     TAB_JOUEUR ('tjoueur_id' INTEGER,"tjoueur_prenom" TEXT   , "tjoueur_nom" TEXT,   "tjoueur_ville" TEXT ,  PRIMARY KEY("tjoueur_id" AUTOINCREMENT))
The result of the SELECT * FROM sqlite_master

type = table
name = TAB_JOUEUR
tbl_name = TAB_JOUEUR
rootpage = 2
sql    = CREATE TABLE TAB_JOUEUR ('tjoueur_id'
INTEGER,"tjoueur_prenom" TEXT   , "tjoueur_nom" TEXT,"tjoueur_ville" TEXT ,  PRIMARY    KEY("tjoueur_id" AUTOINCREMENT))

and then

type = table
name = sqlite_sequence
tbl_name = sqlite_sequence
rootpage = 3
sql = CREATE TABLE sqlite_sequence(name,seq)

As you can see the sql field relative to the table "TAB_JOUEUR" as the CREATE call but it's not a pure copy of the original CREATE call. The original one as "create" in lower case, had extra spaces and has a "IF NOT EXISTS" which we don't have in the sql field of sqlite_master. But the part between the () is exactly the same (single quote for tjoueur_id, double for tjoueur_nom, extra spaces...)
4 - The trick
In order to rename a table, you just have to make a SELECT on sqlite_master in order to get the record of the table you want to rename. Then, change the content of the sql field to replace the "old name" by the "new one", and perform an update, using the rootpage as id.
So like that:
void alter_table(String old_name, String new_name){

int rc ;
String data_rootpage;
String data_sql;
int pos_start;
char *err_msg = 0;

String query_sql = "SELECT rootpage,sql FROM sqlite_master WHERE type='table' AND name = '"+old_name+"'";

const char* sql = query_sql.c_str();
rc = sqlite3_prepare_v2(db_handle, sql, -1, &stmt, NULL);
rc = sqlite3_step(stmt);
data_rootpage = (const char *)sqlite3_column_text(stmt, 0);
data_sql = (const char *)sqlite3_column_text(stmt, 1);

// Find first ( in the string
pos_start = data_sql.indexOf ('(');
String tmp = "CREATE TABLE "+new_name+" "+data_sql.substring(pos_start);

query_sql = "UPDATE sqlite_master SET sql='"+tmp+"', name='"+new_name+"', tbl_name='"+new_name+"' WHERE rootpage = "+data_rootpage;
sql = query_sql.c_str();
rc = sqlite3_exec(db_handle, sql, 0, 0, &err_msg);

sqlite3_close(db_handle);
sqlite3_initialize();
sql_connect("/littlefs/transcom.db", &db_handle);}

It's basic and don't have test (you must add some!). I start by searching for the record concerning the "old_name" table. In the sql field I search for the "(" and then I replace the first part of the sql field data with the new name of the table.
Then I update. Notice I don't escape the quote because I've previously make a CREATE call without any ' or " (easier!)
After that, I perform a sqlite3_close() then re-open with sqlite3_initialize(); If you don't do that, SQLite don't take change in account (maybe there is a cache for data).
5 - Great but... not enought!
If you try this, you'll get an error on the update call. That's because for you, "user", sqlite_master is a read only table. So you can't update it. In order to prevent writing on some table (like the sqlite_master one), when SQLite create it, it sets a "read only" flag. The trick is to edit the source code in order to give to this flag, the value of "read and write".
In the sqlite3.c of the LIB, it's a line 17420. You'll see:
  #define TF_Readonly        0x0001    /* Read-only system table */

Just change it by
   #define TF_Readonly        0x0000    /* Read-only system table */

So when SQLite will create a system table, it will set a read+write flag and so, you would be able to update the sqlite_master table. You need to compile again de lib (on Arduino IDE, just select a wrong board, try to compile, get an error, select ESP32 and compile again and the IDE will perform a full compilation of the lib)
If you have trigger, and some other specific feature, maybe it would be nice to check the result of the select * from sqlite_master in order to see if some records need also to be updated. But for basic table, this will do the job.
Hope this will help.
Edit
If you add an index (or more than one) to your table, you'll have also to update 'index" records from sqlite_master. They are like that:

type = index
name = index_ttest_nom
tbl_name = TAB_TEST
rootpage = 6
sql = CREATE UNIQUE INDEX index_ttest_nom ON TAB_TEST (ttest_nom)

So just update the tbl_name value giving the new name of the table, and update the sql field the same way.

source: Stack Exchange

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

sort: votes


text:
How to query data from my ELM327 via BLE?
I have a HM-10 module connected to my Arduino Nano that I want to use to get data from a ELM327 OBDII.
I have been able to successfully connect to the ELM327 via:
AT

AT+RESET

AT+BAUD2

AT+ROLE1

AT+IMME1

AT+DISC?

AT+CON4823350035BB

I sent "ATZ" through my Serial Console and received nothing.
I then tried other baud rates, with no luck.
I suspected it needs to go to a specific characteristic.
So I found the names of the services and characteristics via Light Blue application.
But I see long hex values, where the AT+CHAR command from the datasheet gives a much shorter example.
I have been able to connect via an ESP32 using the BLEDevice.h library - ideally I would like to use a smaller microcontroller such as the Nano.
Is this possible with the Nano?

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


text:
Leonardo keypresses not working with OBS
I am using an Arduino Leonardo to have hotkeys for OBS but they don't work when the OBS Studio window is not focused.
I have the Leonardo press Ctrl + Alt + Shift + F7 when I press a button connected to the Leonardo. On OBS I have Ctrl + Alt + Shift + F7 switch to a slide. When I have the OBS window focused and I press the button it works fine. But when I have another application focused it does not work. The strange thing is, is that when I press (on my keyboard) Ctrl + Alt + Shift + F7, it will switch to the slide, but when I press the button it does not work.
I am running OBS as an Administrator btw.
My code for the Leonardo is below
int pinA = 8;

void setup() {
    pinMode(pinA, INPUT);
}

void loop(){
digitalWrite(pinA, HIGH);
readPinA = digitalRead(pinA);
if (readPinA == 0){
    Serial.print("A\n");
    Keyboard.press(KEY_RIGHT_CTRL);
    Keyboard.press(KEY_RIGHT_ALT);
    Keyboard.press(KEY_RIGHT_SHIFT);
    Keyboard.press(KEY_F7);
    Keyboard.releaseAll();
    delay(250);
    }
}

you really need to examine the example sketch closely

@jsotola could you give me a bit more info?

Try adding a delay between pressing the keys and releasing them all.

@RyanVogel have you looked at the example sketch? ... what does it have that your sketch does not have?

Warning: the below is all supposition.
When the OBS window is focused the OS can send keyboard events to the window. That means that it gets "The button has been pressed" messages. These are generated when the "press" events are sent from the Leonardo.
When the OBS window isn't focused it can't be sent those messages - so it has to manually poll the state of the keyboard to see what buttons are pressed at any one time. It can't be doing this all the time, so it does it periodically (but still pretty fast).
The knock-on effect is, though, that when not focused it can only see buttons that have been pressed for at least enough time for it to poll the state.
If you add a delay into your routine between the last "press" and the "release all" commands that is longer than the period between polling (no idea what that is - you'll have to experiment, but starting at around 50ms to 100ms should be adequate) you should give OBS enough time to see that the buttons are pressed before you then release them.

This worked! Thanks!


text:
How to calculate the RZERO value in MQ135 sensor, I have already burned it for 24 hours?

I've already burned it for 24 hours and it is now giving the constant value of 932.36,pls tell me how to calculate the RZERO value.

your question is not about the Arduino ... it is about calibrating a sensor ... try to find a website that deals with chemistry

From the datasheet here --->MQ135 datasheet, It is the value of Sensing resistor at 100 PPM of Ammonia(NH3) or from the graph in Fig. 3, you can use gases that has y intercept as 1 and appropriate concentration, i.e you need atleast some known parameter to get it. The legend in the graph is also not clear (as far as getting the values from the Log - Log graph, there are tutorials in youtube).
I'm also in need of solution to this, so far this is what I read on the internet... You need a chemistry lab to do it !!!


text:
Why does per-led current consumption diminishes when more leds are on?
I'm rather new to Arduino. I've been performing some current consumption measurements lately, with a INA219 current sensor, on the blue LEDs from a starter kit.
I plugged three LEDs, on pins 2, 3, and 4 of my Arduino UNO, and wrote a simple script:
digitalWrite(led1, 1);
delay(2000);
digitalWrite(led2, 1);
delay(2000);
digitalWrite(led3, 1);
delay(2000);
digitalWrite(led1, 0);
digitalWrite(led2, 0);
digitalWrite(led3, 0);

Which turns on the leds one by one, and finally turn them off at once.
I measured the current consumption of the first LED, and measured that:

When it's the only one on, LED 1 consumes ~23.5 mA
When the second one is on, LED 1 consumes ~21.7 mA
When the third one is on, LED 1 consumes ~20.2 mA

Could you please tell me why it behaves that way ? Is there any source I should read that would formalize that ?
Thank you

First of all, it's better to not exceed 20 mA per LED, so increase your resistor values.
Second, although 40 mA is the maximum rating for GPIOs, 20 mA is advised.
Note, there is also a maximum per port (in case you want to add more LEDs).
This both doesn't explain your problem though.

Ok, I will add some resistors in the future, I don't want to break anything. Thanks

You mean you don't use resistors now?   Please do immediately before you break your gpios and or leds

Oops. So now I did add some 220ohms resistors on each leds, and performed some new measurements on my LED1.
The difference of current consumed by my LED1 when more LEDs are on is way smaller now: 4.4mA alone, 4.3mA when LED2 is also on, and 4.2ma when LED3 is on. There's still a difference though

I see the problem already has been answered. If you do not use a resistor, the maximum current will flow through the leds. It seems you have a non ideal power source, if it would be (giving much high current), probably you would have broken some components. But with the formula of st2000 you can now calculate your resistor in such a way not to exceed 20 mA.

it's from resistances.  could be on the trace of your MCU or the socket, etc. these lower the voltage diff between gnd and HI, either by raising gnd or dropping vcc. perfectly normal. that's why do don't drive stuff directly from the MCU.

If using a constant voltage source it is advisable to use current limiting resistors in series with LEDs.
If these LEDs are different colors that may explain the different current readings.
Or, if all LEDs are of the same color and you are powering the project from a source with internal resistance (a battery), the more current you draw the lower the supply voltage.  This may show up as a reduced incremental current increase.
Or, if using a poor power source or operating at the current capacity of the power supply - again - this may show up as a reduced incremental current increase.
Note that different generations of LEDs operate at slightly different voltages.  But, in general, RED, GREEN & BLUE LEDs of the same generation operate at slightly increasing voltages respectively.  Details can be found here in this wikipedia.com page:

Typically, the forward voltage of an LED is between 1.8 and 3.3 volts.
  It varies by the color of the LED. A red LED typically drops 1.8
  volts, but since both voltage drop and light frequency increase with
  band gap, a blue LED may drop from 3 to 3.3 volts.

Use the LED current (Iled) and voltage (Vled) specifications to determine the proper resistor value for a given supply voltage (Vbatt).
The following equation from this article should prove useful for this calculation:

Hi, thanks a lot for your answer. I will thoroughly read those references.
My three blue LEDs are exactly the same, this is the corresponding tech spec:
https://www.arduino.cc/documents/datasheets/LED(blue).pdf
I tried with a different power supply (USB this time) and find similar current drop when more leds are turned on.

With out current limiting resistors you are operating outside of specifications.  This may include the processor operating outside of specifications.  This may also include any on board regulator operating outside of specifications.  So it becomes difficult to specify an exact cause for your observations.  Also note, a moderately stressed LED will likely only permanently dim.  So it may be difficult to tell if an LED has been operated outside of specifications.  It looks like these LEDs need a current limiting resistor of (5 - 3.2) / 0.02 ohms when driven by an 5 volt Arduino board.


text:
Trouble with PID code, variable error_x acting strange
I'm trying to get error_x and error_y to display the difference between the target and the position. For some reason I cannot get error_x to function correctly. error_y has the same code, but works correctly. Can anyone help?
Here is the code on my Arduino:
void setup() {
  Serial.begin(9600);
  Serial.print("Starting...\n");
}

int previousTime = 0;
float lastError_x = 0;
float lastError_y = 0;

void loop() {
  //pid variables
  float Kp = 1;
  float Ki = 0;
  float Kd = 0;
  float pos_x;
  float pos_y;
  float target_x;
  float target_y;
  float error_x;
  float error_y;
  int currentTime;
  int elapsedTime;
  float cumError_x;
  float cumError_y;
  float rateError_x;
  float rateError_y;
  float output_x;
  float output_y;

  //invkinematic variables
  float inVec[4] = {1, -1.5, 3};
  float height = 3.5;
  float B = 4;
  float L = 3;
  float U = 3.5;
  float plateRadius = 5.5;
  float alpha[4] = {0, 0, 0};
  float normVec[4];
  float p1[4] = {0,0,0};
  float p2[4] = {0,0,0};
  float p3[4] = {0,0,0};
  float crosskv[4] = {0,0,0};
  float normSave;
  float dotSave;
  float radius;
  float gamma;
  float beta;

  //serial variables
  char buf[32];
  char str_temp1[6];
  char str_temp2[6];
  char str_temp3[6];

  //PIXY CAMERA CODE (outputs x and y)

  pos_x = 1;
  pos_y = 1;

  //DETERMINE TARGET LOCATION
  //default:(0,0)
  target_x = 0;
  target_y = 0;

  //PID CODE (inputs x and y and outputs normal vector and height)

  error_x = target_x - pos_x;
  error_y = target_y - pos_y;

  dtostrf(error_x, 5, 3, str_temp1);
  dtostrf(error_y, 5, 3, str_temp2);
  sprintf(buf, "error1:%s error2:%s\n", str_temp1, str_temp2);
  Serial.print(buf);

  currentTime = millis();
  elapsedTime = currentTime - previousTime;
  if(elapsedTime==0){elapsedTime = 1;}

  cumError_x += error_x * elapsedTime / 1000;
  cumError_y += error_y * elapsedTime / 1000;
  rateError_x = (error_x - lastError_x)/(elapsedTime/1000);
  rateError_y = (error_y - lastError_y)/(elapsedTime/1000);

  output_x = Kp*error_x + Ki*cumError_x + Kd * rateError_x;
  output_y = Kp*error_y + Ki*cumError_y + Kd * rateError_y;

  inVec[0] = output_x/plateRadius;
  inVec[1] = output_y/plateRadius;
  inVec[2] = plateRadius;

  lastError_x = error_x;
  lastError_y = error_y;
  previousTime = currentTime;

  //INVKINEMATIC (inputs normal vector and height and outputs alpha values)

  normVec[0] = inVec[0]/(sqrt(inVec[0]*inVec[0]+inVec[1]*inVec[1]+inVec[2]*inVec[2]));
  normVec[1] = inVec[1]/(sqrt(inVec[0]*inVec[0]+inVec[1]*inVec[1]+inVec[2]*inVec[2]));
  normVec[2] = inVec[2]/(sqrt(inVec[0]*inVec[0]+inVec[1]*inVec[1]+inVec[2]*inVec[2]));

  p1[0] = normVec[2];
  p1[2] = -1*normVec[0];
  normSave = sqrt(p1[0]*p1[0]+p1[1]*p1[1]+p1[2]*p1[2]);
  p1[0] = plateRadius*p1[0]/normSave;
  p1[1] = plateRadius*p1[1]/normSave;
  p1[2] = plateRadius*p1[2]/normSave;

  crosskv[0] = normVec[1]*p1[2] - normVec[2]*p1[1];
  crosskv[1] = normVec[2]*p1[0] - normVec[0]*p1[2];
  crosskv[2] = normVec[0]*p1[1] - normVec[1]*p1[0];
  dotSave = normVec[0]*p1[0] + normVec[1]*p1[1] + normVec[2]*p1[2];
  p2[0] = -0.5*p1[0] + crosskv[0]*0.866 + normVec[0]*dotSave*1.5;
  p2[1] = -0.5*p1[1] + crosskv[1]*0.866 + normVec[1]*dotSave*1.5;
  p2[2] = -0.5*p1[2] + crosskv[2]*0.866 + normVec[2]*dotSave*1.5;
  normSave = sqrt(p2[0]*p2[0]+p2[1]*p2[1]+p2[2]*p2[2]);
  p2[0] = plateRadius*p2[0]/normSave;
  p2[1] = plateRadius*p2[1]/normSave;
  p2[2] = plateRadius*p2[2]/normSave;

  p3[0] = -0.5*p1[0] + crosskv[0]*-0.866 + normVec[0]*dotSave*1.5;
  p3[1] = -0.5*p1[1] + crosskv[1]*-0.866 + normVec[1]*dotSave*1.5;
  p3[2] = -0.5*p1[2] + crosskv[2]*-0.866 + normVec[2]*dotSave*1.5;
  normSave = sqrt(p3[0]*p3[0]+p3[1]*p3[1]+p3[2]*p3[2]);
  p3[0] = plateRadius*p3[0]/normSave;
  p3[1] = plateRadius*p3[1]/normSave;
  p3[2] = plateRadius*p3[2]/normSave;

  p1[2] = height+p1[2];
  p2[2] = height+p2[2];
  p3[2] = height+p3[2];

  radius = sqrt((p1[0]-B)*(p1[0]-B)+p1[1]*p1[1]+p1[2]*p1[2]);
  gamma = atan2(p1[2],sqrt((p1[0]-B)*(p1[0]-B)+(p1[1])*(p1[1])));
  beta = acos((L*L+radius*radius-U*U)/(2*L*radius));
  alpha[0] = 3.1416 - (gamma + beta);

  radius = sqrt((p2[0]+0.5*B)*(p2[0]+0.5*B)+(p2[1]-0.866*B)*(p2[1]-0.866*B)+(p2[2])*(p2[2]));
  gamma = atan2(p2[2],sqrt((p2[0]+0.5*B)*(p2[0]+0.5*B)+(p2[1]-0.866*B)*(p2[1]-0.866*B)));
  beta = acos((L*L+radius*radius-U*U)/(2*L*radius));
  alpha[1] = 3.1416 - (gamma + beta);

  radius = sqrt((p3[0]+0.5*B)*(p3[0]+0.5*B)+(p3[1]+0.866*B)*(p3[1]+0.866*B)+(p3[2])*(p3[2]));
  gamma = atan2(p3[2],sqrt((p3[0]+0.5*B)*(p3[0]+0.5*B)+(p3[1]+0.866*B)*(p3[1]+0.866*B)));
  beta = acos((L*L+radius*radius-U*U)/(2*L*radius));
  alpha[2] = 3.1416 - (gamma + beta);

  dtostrf(normVec[0], 5, 3, str_temp1);
  dtostrf(normVec[1], 5, 3, str_temp2);
  dtostrf(normVec[2], 5, 3, str_temp3);
  sprintf(buf, "a1:%s a2:%s a3:%s\n", str_temp1, str_temp2, str_temp3);
  Serial.print(buf);

  //OUTPUT alpha to servos

  delay(1000);
}

Here is the output with the error:
Starting...
error1: error2:-1.000
a1:  NAN a2:  NAN a3:

error1: error2:-1.000
a1: a2:-0.033 a3:

error1: error2:-1.000
a1: a2:-0.033 a3:

error1: error2:-1.000
a1: a2:-0.033 a3:

error1: error2:-1.000
a1: a2:-0.033 a3:

Try to print the errors directly with multiple Serial.print() statements, ditching all the dtostrf() and sprintf().

Consider enlarging your character arrays.  When creating strings an extra character is likely necessary to indicate the end of a string.  This is usually the null character or zero.  If missing, many string related features will not see an end of a string and likely cause unexpected results.

What I think happened, the 1st dtostrf() call created a properly formed string.  however, the null character likely ended up at the beginning of the next character array.  Which likely got over written by the 2nd dtostrf() call.

I'm actually getting a whole new error. Something seems very wrong now.

The serial output is now: Sta⸮⸮⸮⸮⸮⸮⸮⸮⸮

So the 1st print in setup() is not working?  Likely something else is wrong. You have a huge number of floats for an embedded processor project.  This requires a lot of memory.  And most of the floats are local variable so are on the stack.   That means memory is set aside for them as you run your program.  So running out of memory is not easily check at compile time.  You might be running out of memory.  This depends on the actual stack usage and the specific processor your Arduino platform is using.  Try cutting back on the number of floats variables.

Also, I appreciate getting the answer marked as correct.  But you may want to remove that until it is understood why the program does not work so that others do not skip over your question.  Debugging a program in a stack exchange Q/A never works well as the question usually changes over time making a mess of the Q/A.  In future, simplify your program to the minimum which still exhibits the unexpected results then post your question.


text:
Audio Signal to LED Lights Code Speed Improvement
I wrote this code that inputs audio from a jack (DC offset at 2.5V), performs the fft on a portion of the data, and then outputs a signal to an LED light strip dependent upon which frequency has the highest magnitude. It works but it would be nice if it was faster. Can anyone help out?
#include <arduinoFFT.h>
#include <FastLED.h>

arduinoFFT FFT = arduinoFFT();

const uint16_t samples = 128; //This value MUST ALWAYS be a power of 2
const double samplingFrequency = 16000;
double vReal[samples];
double vImag[samples];

int freqBounds[] = {0,300,500,800,2000,8000};

int colorValue = 0;
int sensorValue = 0;

#define SCL_INDEX 0x00
#define SCL_TIME 0x01
#define SCL_FREQUENCY 0x02
#define SCL_PLOT 0x03

#define LED_PIN   7
#define NUM_LEDS  5

CRGB leds[NUM_LEDS];

void setup()
{
  Serial.begin(115200);
  pinMode(A0, INPUT);
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  for(int i = 0; i < NUM_LEDS ; i++) {
      leds[i] = CRGB(0,0,0);
  }
  FastLED.show();
}

void loop()
{

  for (uint16_t i = 0; i<samples; i++){
    vReal[i] = int8_t(analogRead(A0));
    vImag[i] = 0.0;
    delay(1/samplingFrequency);
  }

  FFT.Windowing(vReal, samples, FFT_WIN_TYP_HAMMING, FFT_FORWARD);  /* Weigh data */
  FFT.Compute(vReal, vImag, samples, FFT_FORWARD); /* Compute FFT */
  FFT.ComplexToMagnitude(vReal, vImag, samples); /* Compute magnitudes */
  double x;
  double v;
  FFT.MajorPeak(vReal, samples, samplingFrequency, &x, &v);

  if (v>300){

    if (x>=freqBounds[0] && x<freqBounds[1]){
      Serial.print("BASE ");
      colorValue = (x - freqBounds[0]) * 255 / (freqBounds[1] - freqBounds[0]);
      leds[0] = CRGB(0,colorValue,255);
    }
    if (x>=freqBounds[1] && x<freqBounds[2]){
      Serial.print("TWO  ");
      colorValue = (x - freqBounds[1]) * 255 / (freqBounds[2] - freqBounds[1]);
      leds[0] = CRGB(0,255,255-colorValue);
    }
    if (x>=freqBounds[2] && x<freqBounds[3]){
      Serial.print("MID  ");
      colorValue = (x - freqBounds[2]) * 255 / (freqBounds[3] - freqBounds[2]);
      leds[0] = CRGB(colorValue,255,0);
    }
    if (x>=freqBounds[3] && x<freqBounds[4]){
      Serial.print("FOUR ");
      colorValue = (x - freqBounds[3]) * 255 / (freqBounds[4] - freqBounds[3]);
      leds[0] = CRGB(255,255-colorValue,0);
    }
    if (x>=freqBounds[4] && x<=freqBounds[5]){
      Serial.print("HIGH ");
      colorValue = (x - freqBounds[4]) * 255 / (freqBounds[5] - freqBounds[4]);
      leds[0] = CRGB(255,0,colorValue);
    }

    Serial.print(x,6);
    Serial.print(", ");
    Serial.println(v, 6);
  } else {
    leds[0] = CRGB(0,0,0);
  }
  for(int i = (NUM_LEDS - 1); i > 0 ; i--) {
      leds[i] = leds[i-1];
  }
  FastLED.show();
}

the answer to your question is yes ..... is that really all you want to ask?   ..............  btw: you can remove the serialPrint() calls to speed up the code

use a faster MCU

Does the code work as it is? The delay near the top looks wrong to me - it will always delay(0). Anyway, how fast does it currently run, how fast do you need it to run, and which parts of the process take the most time?

Ad some code that prints how much micros each part of your code uses. Something tells me that the FFT calculations will take 90% of the loop time, and there is no easy way of optimizing that. You can always use electronic circuits instead of digital MCU logic to calculate the FT at half of speed of light. I found a nice source here http://sound.whsites.net/project136.htm

Use an integer fft algorithm instead of a floating point one.


text:
Error with Sparkfun MP3 Shield and Arduino Due playing music files
The code worked on my Ardino Uno. I plugged it up the exact same way and am now getting an error.
Here is the error I get when I try to upload my code to the due:
Arduino: 1.8.5 (Windows 10), Board: "Arduino Due (Programming Port)"

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp: In static member function 'static void SFEMP3Shield::refill()':

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:1984:7: error: 'sei' was not declared in this scope

   sei();

       ^

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2006:9: error: 'cli' was not declared in this scope

     cli(); // allow transfer to occur with out interruption.

         ^

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp: In member function 'void SFEMP3Shield::SendSingleMIDInote()':

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2053:7: error: 'cli' was not declared in this scope

   cli(); // allow transfer to occur with out interruption.

       ^

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2067:7: error: 'sei' was not declared in this scope

   sei();  // renable interrupts for other processes

       ^

exit status 1
Error compiling for board Arduino Due (Programming Port).

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Here is my code:
#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>

SdFat sd;
SFEMP3Shield MP3player;

const uint8_t volume = 10; // MP3 Player volume 0=max, 255=lowest (off)
//10 for normal 50 for testing

const uint16_t monoMode = 1;

void setup() {
  initSD();
  initMP3Player();
}

void loop() {
  if(!MP3player.isPlaying()){
    MP3player.playTrack(1);
  }
}

void initSD() {
  if(!sd.begin(SD_SEL, SPI_HALF_SPEED))
    sd.initErrorHalt();
  if(!sd.chdir("/"))
    sd.errorHalt("sd.chdir");
}

void initMP3Player() {
  uint8_t result = MP3player.begin();
  MP3player.setVolume(volume, volume);
  MP3player.setMonoMode(monoMode);
}

The library is written for the Uno, not the Due. It relies on two instructions that are only available in the AVR compiler.
Newer versions of the core provide a pair of macros, interrupts() and noInterrupts() that should be used in place of sei() and cli() respectively, which should be provided by the Due's core as well to make it cross-platform. However that library has never been updated to work with those macros.
You could replace the sei() and cli() calls in the library with interrupts() and noInterrupts(), however that may not make it work, since it was written with the Uno and other AVR based chips in mind.

I don't have permission to change that library file. Do you know how I can get it?

You must have permission to edit it, otherwise you won't have been able to install it in the first place. Or are you on some strange system controlled by some overarching all knowing power?

I just changed the permissions in the properties. The code uploads, but the board does nothing. It doesn't even blink when I hit reset.

I feared as much. The library probably needs much work to run on a due.

do you have a suggestion on how i can play mp3 files on a due, maybe a different shield or something?

You just need either a library for that shield that works with the due, or you need to learn how the shield works and write a new library for it.

The mega uses the same libraries as the uno right?


text:
Output clock signal on MKRZERO
I have to port a Project written for an Arduino Micro to an MKRZERO.
It communicates via UART with an IC and should also provide a clock signal.
The former code I have used is this:
#define OUTPUTPIN 8
#define CLOCKOUTPIN 5
#define CONTRLEDPIN 13

void Setup() {
pinMode(OUTPUTPIN, OUTPUT);
// Needed for initialization
digitalWrite(OUTPUTPIN, HIGH);
// set clock PIN
pinMode(CLOCKOUTPIN, OUTPUT);
// sets PIN for internal LED
pinMode(CONTRLEDPIN, OUTPUT);

TCCR3A = (1 << COM3A0);
TCCR3B = ((1 << WGM32) | (1 << CS30));
TIMSK3 = 0;
OCR3A = 7;
}

As the MKRZERO uses a different IC the registers are not the same. I've waded through the data sheet document but cannot find something similar.
Does somebody have any experience with the MKRZERO and can help me with this?

The IC on the MKRZERO is an Atmel SAMD21.  Look up the datasheet and read the section on timer counter.  Yes, it's a long document, but you will find all of the information there.


text:
More than 4 PWM output at 25khz?
Is it possible using an arduino to control more than 4 PWM fan at 25khz ?
I have found this but 4 PWM limited with an UNO
https://arduino.stackovernet.com/fr/q/8407
An other arduino, like a 2560 could be used ?
Thanks
Best regards
Sébastien

I would like replace this : https://www.nzxt.com/products/grid-plus-v3 in my work station

See answers in https://arduino.stackexchange.com/questions/3182/what-is-the-frequency-of-pwm-output-on-arduino for a guide on how fast Arduino PWM can be.

You could also use timer0, but then delay and millis won't work anymore. Second option is to use a external chip. You could also use a MEGA like you suggested, or the newer ATMega328PB (I don't think the latter is already used in the UNOs)

why would you need individual control of the 4 fans? ... just use one PWM signal to control all four.

'328P supports 6 analogWrite() outputs on D3,5,6,9,10,11. Won't all 6 do 25 KHz?

Indeed you could use a Mega. See this answer: it explains how
you can use Timer 1 on an Uno to provide two PWM channels at
25 kHz. This is the only 16-bit timer on that board. The Mega, on
the other hand, has four 16-bit timers: Timers 1, 3, 4 and 5. These
timers are almost identical to the Uno's Timer 1, except that they
provide 3 PWM channels each. So you have potentially up to
12 PWM channels that you can run at 25 kHz.
Now, look at this pinout diagram. Every pin labeled OCnx,
where n is either 1, 3, 4 or 5, and x is a letter, is a 16-bit PWM
output. Just take the code from the answer I linked to and adapt it to
the Mega. You configure all those timers in the same way, and you set
the duty cycle for pin OC3B by writing to the register OCR3B (and so
on...).


text:
upload sketch via bluetooth for android
How can i convert file .ino to hex file so that i can compile new sketch via bluetooth. Can you help me to figure out the way to do this? thanks for helping

You press the "verify" button in the IDE. That makes a .hex file. But I don't think that's really your question, though, is it? Getting a HEX file is the easy part. Uploading from android isn't. You would need something to implement the Arduino bootloader protocol in Android. No clue if there is anything out there to do that for you or not. Maybe Google can help?

https://play.google.com/store/apps/details?id=io.iotool.iotoolarduinohex&hl=en_GB

i mean like bluino app or arduinodroid app they can compile code via bluetooth, so i really wants to understand  how arduino receives data. Sorry sir because my question isn't clear. hope you help

You don't compile code via bluetooth. You compile code on your computer, then copy the compiled .hex file to your phone to upload with whatever app you choose.

so i need to find way compile it by java or computer, and then send compiled .hex file to arduino via bluetooth to make it work

You press the "verify" button in the IDE.  -- Then you use your favourite file transfer tool over whatever protocol you prefer (I use Amaze to access a share through the network). Then you use the Arduino programmer app.

let me explain what i aim to do , that i want to make an android app that can create ino  then upload it via bluetooth to arduino to make robot work and instead of controlling just send a string to control that i would want replace a whole file in arduino chip

So you want to write your own Android-based IDE, and port the compiler to Android? Good luck with that. There's a reason people write web-based applications...

thank you sir, you are so nice.

It is very hard to understand exactly what you want to do, but from what I can gather you want to:

Write an Android application that lets you edit sketches
Compile those sketches on an android device, and
Upload those compiled sketches to an Arduino over Bluetooth

While what you are asking is technically possible, it is not realistically practical.
Writing a text editor in Android is easy enough. That's not a problem. It's the compilation of the code that is not practical.
You would need to port the compiler (a very large project written in C) to Android. That would essentially need to remain as compiled C code, and so you would have to individually port it to each possible platform you want it to run on (various different types of ARM, Intel, etc) and for different versions of android.
Unless you're a genius at Android and C programming that's just not going to happen.
A more practical way would be to write a web-based application that allows you to edit your sketches, which can then run the compiler on a real computer (no porting needed then), which can then download the compiled HEX file to your Android device, then use a pre-existing application to program that HEX file over bluetooth.
Alternatively, just use the Arduino Create website to compile and download your HEX file.


text:
Which temperature sensor is accurate?
I have an Arduino Nano RP2040 Connect with two temperature sensors. A DHT22 is connected to D2 and pulled up with a 5 kΩ resistor to 5V, and a LSM6DSOX IMU is built in to the board. Here's my code:
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <Arduino_LSM6DSOX.h>

#define DHTPIN 2
#define DHTTYPE    DHT22

DHT_Unified dht(DHTPIN, DHTTYPE);

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

void loop() {
  delay(1000);

  sensors_event_t event;
  dht.temperature().getEvent(&event);
  Serial.print(F("DHT22: "));
  Serial.print(event.temperature);
  Serial.print(F("°C and "));

  float temperature_float = 0;
  IMU.readTemperatureFloat(temperature_float);
  Serial.print("LSM6DSOX: ");
  Serial.print(temperature_float);
  Serial.println(" °C");
}

When I run it, I get this in the serial monitor:
DHT22: 24.50°C and LSM6DSOX: 28.94°C

Why is there such a large difference (4.5°C/8.1°F) between the sensors?

Your 1st stop should be the specification sheets for the two parts.  You should find the STMicro accelerometer spec sheet at st.com.  I'm not sure about the DHT22.  Since I've had my share of problems with the DHT22, I'd look else where.  But that's just personal preference.

Also, where is the accelerometer?  If it's buried next to heat generating parts then it may not reflect ambient temperature.  Remember, the accelerometer needs its temperature to compensate for its own acceleration sensors.  Not for telling you what the ambient temperature is.

you title question cannot be answered without knowing the ambient temperature ... you can answer it yourself anyway


text:
Make phone call over 4G LTE
I have used the SIM800L module in the past, but with Ting shutting down their 2G network, I have been looking for alternatives. I have a SIM7000A, but I can't seem to find a microphone or speaker pin. Can this make calls, or will I have to find something else? I am using an Arduino Mega.

The SIM7000 doesn't have a microphone or speaker pin.  Instead it provides a PCM interface to connect to an external CODEC chip.
As it says in the Hardware Design Manual:

SIM7000 provides a PCM interface for external codec, which can be used in master mode with short sync and 16 bits linear format.

If you want to use it for phone calls then you will need a module that also incorporates said CODEC chip and all the associated circuitry to connect to a microphone and speaker.


text:
How far can a HC-SR04 can stand from the microcontroller?
I was wondering if I connect a HC-SR04 to an Arduino or any other microcontroller by normal cables, what would be the maximum length of this cable so that the measurements will still be true, and not affected by the length of this cable?

this problem consists of 2 things :

supply level drop (this one has severe effect)
signal level drop (a little more forgiving)

as the signals on the cables don't have high frequencies, the problem narrows down to just voltage level drop due to cable resistance.
supply level drop: the datasheet for SR04 says a maximum active current of 20mA is required for device to work properly. the supply voltage is 4.5~5.5v. so if you provide a 5v power for it, the cable must not drop it under 4.5v. the maximum resistance for the cable is calculated

R=V/I => R = (0.5/20)*10^3 = 25 Ohms

. you can use this value to find out maximum cable length using resistance tables provided by cable makers. e.g. if you have bought a 5ohms/meter cable, the maximum length should be under 5 meters to ensure a good power delivery.
the signals on the other hand, have very little current going between them. as the MCU/Module pins have a very high input impedance. so they are not as severe as the supply drop.
using a 100uF cap near SR04's supply pins would be great.

I have a couple measuring the liquid level of two tanks.
The units are distanced from the microcontroller by 12' of 18ga solid-core copper cable.
Testing was done with another microcontroller with the sensor attached by 6" cable to ensure accurate readings.
That's the longest I needed, so I haven't tested beyond that.

The signal of an HC-SR04 is the pulse on the "Echo" wire. The length of that pulse is directly proportionate to the distance from the object.
Since cable length does not affect the duration of that pulse, measurement accuracy isn't affected either.

Though that doesn't mean, that you can use any cable length. At some point the resistance of the cable might get too high, thus pushing the voltage too low for the Arduino to detect correctly. Also the increasing capacitance can smooth out the edges of the signal. But that can only be tested with the used cable, since there is no standard for a "normal cable".

Oh, absolutely. I don't think it'll have much influence in practise though - the input impedance on Unos is quite large, and so is the pull-up resistor. If all else fails, you could probably even analogRead the port.


text:
ESP8266 GPIO limitations with HC-SR04
I want to build a systems that measures if some parking spots are occupied or not. I chose to use an ESP8266 12-E NodeMCU Kit with multiple HC-SR04 ultrasonic sensors. In my project, it is essential to connect as many ultrasonic sensors to one ESP. Unfortunately, I have found out that if I connect the input/output of the HCSR04 to GPIO 10/9 and GPIO 1/3, The board can't boot. Can anyone explain to me why I cannot use those GPIO pins and what alternatives I have in order to connect more sensors to the ESP (other microcontrollers, pin extenders etc.)?

https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/

The ESP8266 is a very poor choice if you want to use multiple GPIOs. There are very few you can actually use. You are better off using something else. Even the ESP32 is better, though that is still somewhat picky with some GPIOs.


text:
PCF8575c changes address in I2C Scanner
I want to connect a PCF8575c pin extender to an ESP32, so that I can light 12 LEDs. The problem is that after the connection, when I try to use an I2C Scanner, it shows me a lot of different addresses, not a constant one. Could this happen from a pin fault? I am using this library:
https://github.com/xreef/PCF8575_library
Also, the I2C scanner can be found here: https://playground.arduino.cc/Main/I2cScanner/
And the pins that I use for the LEDs are defined this way:
  pcf8575.pinMode(P0, OUTPUT);
  pcf8575.pinMode(P1, OUTPUT);
  pcf8575.pinMode(P2, OUTPUT);
  pcf8575.pinMode(P3, OUTPUT);
  pcf8575.pinMode(P5, OUTPUT);
  pcf8575.pinMode(P6, OUTPUT);
  pcf8575.pinMode(P11, OUTPUT);
  pcf8575.pinMode(P12, OUTPUT);
  pcf8575.pinMode(P14, OUTPUT);
  pcf8575.pinMode(P15, OUTPUT);
  pcf8575.pinMode(P16, OUTPUT);
  pcf8575.pinMode(P17, OUTPUT);

The link to the exact PCF8575c:
https://www.aliexpress.com/item/2038559527.html?spm=a2g0o.productlist.0.0.3f8331ebu0zuwr&algo_pvid=5e9fc157-a422-4847-acf4-8618a2d365ea&algo_expid=5e9fc157-a422-4847-acf4-8618a2d365ea-2&btsid=0ab6f82415840969999872503e3228&ws_ab_test=searchweb0_0,searchweb201602_,searchweb201603_

What are the addresses it gives you?

Have you configured the A0/A1/A2 jumpers on the board?

I agree with Majenko. That really sounds like unconnected and thus floating address pins.

Look at the back of the module. There are 3 groups of 3 solder pads each, marked with A0, A1 and A2. With these pads you can set the 3 least significant bits of the address.
On the images in your product link these pads are unconnected. The middle pin is the address pin. The left pad (which is connected to a trace) is Vcc, the right pad (which is connected to the big trace area) is ground. By connecting the middle pad with ground, you set the address bit to zero. By connecting it to Vcc, you set it to 1.
As the pads are unconnected, the address pins are floating. In that state, the pin is reacting to random electrical noise, thus changing state randomly. So also the address changes randomly.
You need to connect every address pin to either ground or Vcc by adding a solder bridge to the pads.


text:
Ethernet Shield doesn't work at all
I connected corresponding pins of Arduino Nano and the Ethernet Shield, connected my computer to a router (the light indicated the connection) and Ethernet Shield to the same router. Nevertheless, there is no sign of connection on the router and the leds on the Shield don't light up either. I tried changing cables and Shields, but this didn't work. Here is my code example. What could be wrong?
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = {192, 168, 1, 3};
byte myDns[] = {192, 168, 1, 1};
byte gateway[] = {192, 168, 1, 1};
byte subnet[] = {255, 255, 255, 0};

EthernetServer server = EthernetServer(23);

void setup() {
// initialize the ethernet device
  Ethernet.begin(mac, ip, myDns, gateway, subnet);
  // start listening for clients
  server.begin();

  Serial.begin(9600);
  Serial.println(Ethernet.localIP());
  Serial.end();
}

try the examples of the Ethermet library. they have better diagnostic. what pins did you wire?

MISO, MOSI, SCK, CS to pin D10, RST, VCC to 3.3V and GND

the Ethernet shield is powered from 5V pin

Thank you, I think this will help


text:
Increasing ESP32 AP max connections
It has already been asked how many clients can connect to an ESP32 AP, but the answer is far from clear; the best one is from a year and half ago (ESP32 AP max connections: 4 or 10?) :

The answer is as clear as any other EspressIf configuration data, it is 4 or maybe 5, or 8, or 12, 16 or even 20 (the same as a ESP8266!)

As I'm trying to move a project from the ESP8266 because it does not have enough AP connections, two questions can be asked :

what is the maximum number of AP connections supported by the 4.0 ESP-IDF framework ?
can it be increased in any way ?

Thank you.

After some extensive testing with several modules (not just blindly trusting the documentation), here's what I found.
Short answer : maximum 10 AP connections for the ESP32 running ESP-IDF 4.0 (updated around 1st of march 2020), and no, it can't be increased (easily).
Details :

The maximum number of AP connections is defined somewhere in libnet80211, and can't be modified since I have no access to the source code.
when the 11th station tries to connect, libnet80211 prints I (39682043) wifi: max connection, deauth!, more or less like the ESP8266 for the 5th station
Changine the ESP_WIFI_MAX_CONN_NUM (defined in esp_wifi_types.h:258) from 10 to anything else ends up in unpredictable behavior (I'm labelling this as unpredictable since without the libnet80211 code, it can't be reliably assessed).

I'm not giving up on increasing the number of stations yet, so maybe there'll be an update to this answer.

According to the documentation:

uint8_t max_connection
Max number of stations allowed to connect in, default 4, max 4

The WiFi interface and AP can support up to 10 connections in its internal structures, but that is only practical for WiFi Mesh usage (which doesn't use all 7 layers of the ISO model), and for actual WiFi station connections, which entails the allocation of far more resources (IP addresses, ARP tables, etc) only a maximum of 4 are supported.
If you need more connections I suggest you invest in a real access point / router which can deal with the network management for you (i.e., an access point or router which can do the DHCP and other networking housekeeping for you, leaving your ESP32 free to be a simple station).

this is copy-paste from esp8266 doc

No, it's a quote from the ESP32 documentation. Hence the link to the ESP32 documentation.

Yes, it’s a quote from the documentation, but how reliable is the documentation ?

If you search in the ESP-IDF files you will find ESP_WIFI_MAX_CONN_NUM=10,

It looks like in 2016 they changed from a linked list to a static array for storage of connected stations. Since then the size of that static array has changed. For some reason the define started as 8, but the array was created as 8+2. Then the define changed to 10 and the array was also created directly from that define instead of adding 2. No idea what the significance of the "+2" was.  However, the 10 is not for wifi. The 10 is for mesh. How many connections it supports, and how many are allowed are different things. The WiFi itself can support 10, which is fine for mesh use, but ...

... for actual processing of connections it's limited to just 4 connections, since active connections to the IP stack use more resources.

Thank you for the explanation.
But the second question still stands ... can it be altered in any way ?

@stefanu Probably not. If the IDF limits it then there's not a lot you can do. You could try manually configuring the AP mode (incidentally I notice in the ESP-IDF code for doing that it's actually setting the number of connections to 5...) or adjust start_wifi_ap and see if that works. It may not though, since you may run out of memory

Thank you for the info; I'm in the process of replacing the ESP8266 with the ESP32 and I will soon be able to test the AP limits (as soon as I receive more chips to test with).
I will get back with the results.
What I've been able to test so far is that changing the
#define ESP_WIFI_MAX_CONN_NUM 10
to
#define ESP_WIFI_MAX_CONN_NUM 16
then rebuilding everything, does change the sizeof(wifi_sta_list_t), so ... maybe... just maybe ... there's a chance.

@Majenko : well...the documentation is WRONG ! Without any hacking at lower levels I was able to connect 8 stations in APSTA mode. On the other hand, changing the ESP_WIFI_MAX_CONN_NUM to a greater value produces strange behavior (for instance esp_wifi_ap_get_sta_list fails miserably). I will get back once I have more modules to play with.


text:
Task watchdog gets triggered during Bluetooth initialization
The board ESP32-Dev-WROOM-32D cannot establish a bluetooth connection due to the task watchdog. Here's my code:
#include "BluetoothSerial.h"
//check if Bluetooth is enabled
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32test");
  Serial.println("The device started!");
}

The program runs fine until SerialBT.begin("ESP32test"); where it freezes, and does not continue to run. The message The device started! is not printed. Instead, the task watchdog gets triggered after some time: E (24791) task_wdt: Task watchdog got triggered.
Is there any way to turn off the task watchdog? Or is there any other issue?

Try adding esp_task_wdt_reset(); before SerialBT.begin(...).

Nothing changes, watchdog still gets triggered

SerialBT.begin("ESP32test") is hanging, and because ESP32 doesn't deal well with code that hangs, so it complains about it.
ESP32 runs a Real-Time OS (FreeRTOS).
The fact that it is a real-time OS means that execution of code needs to be guaranteed to finish within a certain time-frame. You'll often see RTOS functions containing the time limit in which that a blocking function should finish executing, such as:
    uart_wait_tx_done(uart_num, 100); // wait timeout is 100 RTOS ticks (TickType_t)

(from ESP-IDF docs)
FreeRTOS comes with a task API. Each task can execute code, but they need to give other tasks the chance to execute code too. I think that when a task blocks, it doesn't allow other tasks to do work on the same CPU. (but I can't find sources to back this up)
setup() runs in one of the RTOS tasks, and when SerialBT.begin() blocks the task for too long, the task watch dog complains that the task is hanging.
If the task is blocked by some kind of looping code, then it generally helps to run vTaskDelay() to yield the task to the task watchdog for a bit.
Because your task is blocked by a single call, there isn't much to do about it, given that SerialBT.begin() doesn't seem allow you to specify when it should time out.


text:
Do the libraries of the Arduino Uno work with the Arduino Mega?
I did a project with the Arduino Due and the libraries for the VS1053 MP3 Shield were not compatable with the Due. Are the libraries that work with the Uno compatable with the Arduino Mega?

Are the libraries that work with the Uno compatable with the Arduino Mega?

Sometimes.
They have a higher chance of being compatible, due to them both using the same AVR core, but since internal peripherals differ slightly there is a chance that, depending on what the library does, it won't work right.
You just have to try it and see.

The main question is: Is that shield compatible with Arduino Mega as SPI is not located on pins 10-12?

@KIIV Do you know the answer to that question?

If it's this one then I would suspect that yes it is. Pins 11 to 13 are linked directly to the SPI header (note: this means you can't use pins 11-13 for other things on the Due/Mega).


text:
How to check whether my arduino-mega ADC is sampling correctly?
I have a code which samples the given input signals with sampling rate 256hz. I plotted the graph of FFT and was able to see the peaks at the expected frequencies.But I would like to know whether my ADC is sampling correctly or not?Is there a way to do it?`
    void setup()
{ Serial.begin(38400);
}

const unsigned long READ_PERIOD = 3906;  // 3906 us: 256 Hz
void loop() {
    static unsigned long lastRead;
    if (micros() - lastRead >= READ_PERIOD) {
        lastRead += READ_PERIOD;
        int val_a0 = analogRead(A0);
        int val_a1 = analogRead(A3);
        int val_a2 = analogRead(A5);
        int val_a3 = analogRead(A7);
       Serial.print(val_a0);
       Serial.print("  ");
       Serial.print(val_a1);
       Serial.print("  ");
      Serial.print(val_a2);
      Serial.print("  ");
        Serial.println(val_a3);
    }
}

In this case the baud rate will be real bottleneck. You have to send from 110 to 230 bits per reading (1 start bit, 8bits data, 1 stop bit)*(3*2 spaces + 4-16 number characters + 1 line feed).
That means best case (all numbers are less than 10) 349 readings per second. And worst case is 166 readings per second (all readings are more than 999).
So it's about 10% probability to be sampled correctly.
You can check if the next time (with misleading name lastReading) is less than current time. That means you are already too slow.


text:
Servo motor rotates back to 0 after reaching destination
I am using a XMG-996R servo motor. It is controlled by and Arduino Uno board. The problem is when I tell it to go to a certain angle, it will rotate to the desired position but then return to 0. The motor keeps rotating back and forth between the destination and 0 degrees. I tried this with different servos and they all do the same.
I am using 3 AA batteries as an external power supply. I have also tried using 4 AA batteries or a 9V battery. The same thing happens no matter the power supply.
My control wire is connected to the Arduino, positive is connected to the external power source. The negative is connected to the ground of the power source and the ground of the Arduino.
This is my code:
include <Servo.h>

Servo servo;

void setup(){
   servo.attach(9);
   servo.write(90);
}

void loop(){

}

I have also tried putting the write() into loop as well as putting servo.write() before servo.attach(). neither of these methods made a difference.
What can I do to make the servo rotate to the given degree and stay at that degree? Thanks.

This belongs in an Arduino forum, but I think you need to keep calling write to constantly send pulses to it. Move write into the main.

I put a ceramic capacitor on the motor, now it works fine.


text:
GPS Module don't provide full data
I connected my gps module (NEO-6M) with esp32doit-devkit-v1 board. The module provided data but many data are missing.
My pin configuration:
GPS ------- ESP32
VCC ------- 3v3
GND ------- GND
TX -------- RX2 (pin 16)
RX -------- TX2 (pin 17)
Baud Rate: 9600
My code:
#include <Arduino.h>
#include <TinyGPS++.h>

#define TXD2 17
#define RXD2 16

TinyGPSPlus gps;

void setup()
{
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
  Serial.println("Started......");
}

void loop()
{
  while (Serial2.available())
  {
    Serial.write(Serial2.read());
    // gps.encode(Serial2.read());
    // if (gps.location.isValid())
    // {
    //   Serial.print("Latitude= ");
    //   Serial.print(gps.location.lat(), 6);
    //   Serial.print(" Longitude= ");
    //   Serial.println(gps.location.lng(), 6);
    // }
  }
}

OUTPUT

The output looks perfectly fine. You just don't have a GPS signal.

@Majenko is right put your GPS outside (in open sky) then you will the latitude and longitude with other parameters as well.

GPS seems to be working and informing you that you have no signal.  Usually happens inside buildings, when far from a window or when antenna isnt properly connected.
Testing out of doors is many times not possible, so try placing your antenna next to a window with a partial view of the sky.  Wait for a couple of minutes until you get a fix on 4 or 5 satellites.

have also found this happens when the power to the module is lower than needed, for example 5v being shared with other modules such as a 1602 display


text:
Nodemcu 1.0 and boot mode (1,6) after soft reset
I have a problem with a nodemcu 1.0 (lolin) board. Sometime a soft reset is performed from the watchdog and the board freezes in boot mode (1,6) (I have to manually reset the board to restart it).
I have read many thinks on this topic and I have carefully avoided to use the GPIO0, GPIO2 and GPIO15. I have also verified that these pins are correctly pulled-up (GPIO0 and GPIO2) and pulled-down (GPIO15) but when the board frezes I have noticed that the voltage of the GPIO0 is not 3.3V but 2.0V.
Has anybody experienced a similar problem? Could you help me in solving it?
I wish you all a happy new year.
Cheers.

The esp8266 has a bug (documented). After Serial upload the program is started without reset and then at soft reset the state of "start bootloader" is still active.


text:
Checking/accessing Serial prevents clean upload of sketch via bluetooth?
I'm deploying some DIY home automation devices, built around a 3.3v pro mini, a HC-10 module, and a relay board. The arduino is able to be programmed over the bluetooth module, so once it's in the wall, upgrades are easy.
The HC-10 is connected to the RX/TX pins of the arduino. The reset pin of the arduino is tied to one of the PIO pins of the HC-10 via a 100nf cap. I have a device I built that sets up the bluetooth connection, and once the upload starts, it toggles the PIO pin, pulling the cap low, thus resetting the arduino. The code then uploads over the bluetooth link as if it were direct USB.
Everything works great. I can upload code, test it, upload more code, etc etc. Works great.
UNTIL I try and upload code that relies on Serial... the moment my code has a while(Serial.available()) or Serial.read() in it, the upload 'hangs' about 80% of the way through, the IDE reporting an error.
Weird thing is - the code DID upload correctly. It seems it failed during the verify stage. If I comment out the Serial.available and Serial.read, it uploads great. I thought maybe the code started running before the verify was done, so I added a delay in the setup() section to allow the upload to finish before any serial activity started. That didn't help. I tried moving the Serial code into another function. That didn't help. I set a new variable, int testing = 1, and enclosed the Serial functions inside if(testing > 2), an impossible condition. THAT WORKED. Long story short - after lots of testing, if there exists the possibility of the Serial code running, even if it does NOT, the upload verify hangs and fails. If the code is commented out, or placed in an impossible situation, the code uploads fine.
Why would the mere presence of Serial code, even if it's not running until way after the upload finishes, screw up my upload?
I can live with the error - the code uploads and runs fine. Just annoying to not see a clean 'Done uploading' at the end.
Any idea why it's doing this?

Strange thing. That it works, when you place the Serial code into an impossible condition, must be due to the compiler optimizing the code away, so that effectively there is no Serial code in the sketch anymore.

Thats what I figured, and why I tried the impossible condition - if int testing = 1, and it is never changed, then testing > 2 will never be true, and that code is likely optimized out. But what's weird and I cannot figure out is why, if there is a Serial.available() anywhere in the compiled code, the verify hangs and never finishes.

Decided to just disable verification for the custom board type I made for this sort of connection/upload. Disabling that makes the upload run without a problem. I'


text:
Use Low Power Arduino with Solar Panel
I am trying to create an arduino system with radio-transmitters and radio-receivers. The system runs from a rechargable battery that is charged with a solar panel. I am using a 1.1W 6V solar panel.
My problem is that I don't know how to make such a connection and I don't know what batteries to choose to power the arduino, assuming that I need it to run for 5-7 days without solar power and that the solar panel is good enough to recharge the batteries while they power the arduino. We are also assuming that the solar panel has 8 hours of sunlight.
To the arduino are connected the following sensors:

Flame Sensor
Light Resistor x2
Smoke Sensor
Radio Transmitter
Radio Receiver
DHT11 Temperature & Humidity Sensor

I am also looking to see if I can power down most sensors and power them on later if an event occurs. So probably all the sensors could be sleeping except the DHT11 and the Radio Receiver. Preferably though, if at all possible, the rest of the sensors should be on, if we can handle 5-7 days without the solar panel. I don't know if more information is needed but I'd be pleased to help out in the comments, or provide more information by editing the question. :)

Why do you want the DHT11 to be always on?

Have a look at https://thecavepearlproject.org/ . It goes into great detail on how to run the Arduino and sensors at very low currents.

@Gerben the DHT11 needs to be one because it will be the one providing information when asked to and alert when the temperature rises. So it always needs to be on

No. The Arduino needs to be "on". The Arduino polls the DHT11, say once per minute. You could remove the power from the DHT11 when it isn't used. Then re-apply power when you need a new temperature measurement. (Though you might need to add some delay between powering up, and getting a reading).

@Gerben Yeah that was the plan, although I measured the circuit without it and constantly reading from it and it was below 1mA, so I assumed that 1mA was the average draw just to be sure, before rewriting that part of the code, taking measurements every minute instead of taking every 2 seconds without powering off.

You have far too many variables and unknowns there. Primarily you need to know what the average current draw for your circuit is. Secondly you need to decide how long the solar powers are allowed to take to recharge the battery. You have to think not only about runtime but also charge time. The charge time dictates the maximum capacity of the battery, and that then dictates the runtime of the Arduino. So here's some napkin maths to illustrate:
Assuming you want the battery to charge from almost flat to full within 8 hours, and with a 1.1W 6V solar cell, that gives you a peak of 183mA.
Assuming the Arduino circuit takes 83mA on average (let's give ourselves nice round numbers here) that leaves 100mA peak for charging the battery.
If you're charging at, say, 0.2C, that gives a full charge in 5 hours. 100mA / 0.2C = 500mAh capacity (at peak sunlight and current).
At 500mAh capacity and 83mA average current draw that would give you (0.5/0.083) 6 hours of runtime without the solar panels.
So that's just not going to work.  It'll be dead by morning.
Now assume that you can turn off everything for 99% of the time.  That effectively reduces our average current draw to 0.083*0.01 = 830µA. Let's plug that into the same reasoning as above.

Current draw = 0.00083A
Incoming peak current = 0.183
Available charge current = 0.183-0.00083 = 0.18217
Charge at 0.2C = 910mAh.
1Ah battery would charge in about 5.5 hours of peak sunlight.
1Ah would last about 1200 hours, or 100 days.

None of this takes into account varying light levels or light incidence angles. As a rule of thumb, take the light as averaging 50% over the course of the 8 hour period. You will only get 1.1W when the angle of incidence is 90° to the solar panel. At all other times it will be reduced. So if we reduce the current from 183mA to, say, 100mA, the charge capacity changes to:

Incoming peak current = 0.100
Available charge current = 0.100-0.00083 = 0.099
Charge at 0.2C = 496mAh
A 500mAh battery would charge in about 5 hours.
A 500mAh battery would run for about 50 days at 830µA average current.

So you see everything really hinges around the current consumption of the Arduino. How much current it consumes dictates how much is available to charge the battery, which in turn dictates the size of battery you can support, which dictates the amount of current you can draw for your desired runtime, which in turn dictates the amount of charge current available, which determines the size of battery you can support, which dictates ... etc.  You get the idea.
You can support larger batteries, of course - I illustrated this at 0.2C charge rate (that's 20% charge per hour to give a 5 hour charge time). As long as the net charge over time increases (so during the periods between the 5-7 days of complete darkness you gain more charge than is expended during the dark period - something which has not been specified) then it should function fine.
Also note that your battery voltage should be below your solar panel voltage. A 6V solar cell would be able to charge a 4.5V lead acid battery (assuming low dropout schottky protection diodes). Also the capacity of the battery depends also on what you determine your "cut-off" voltage to be. That's how low the battery voltage is allowed to go before your system is determined to be unworkable. This could be at a point where the battery is in danger of being damaged by over-discharge, or at a point where your circuit no longer receives enough voltage to function (which could be linked to oscillator frequency on ATMega chips), etc. For this reason it is often better to choose a board that is designed to run at a lower voltage (3.3V) and use high efficiency switching regulation to get the most out of your battery. A 5V Arduino is seldom a great choice.
Finding that right balance is now entirely up to you.
And, in answer to your other question, yes there are ways to turn things on and off. You can "sleep" the Arduino. You can use high efficiency power circuits. You can add power switching circuits (P-MOSFETs) to switch power on and off to other modules. All things can (and mostly should) be done to save power when running on batteries.

Thank you for your answer it was really helpful. I think I have some more questions. What would you suggest to do, if I needed the receiver and temperature module to be on always but other sensors off? What ways are there to do this and how would I connect the solar panel to the battery and the battery to the arduino?

First: you would connect the solar panel to the charger, then the charger to the battery. The battery then connects (via the charger) to the power supply, which then connects to the Arduino. You can't just wire a solar panel to a battery and hope it will work - charging takes management.

Second: you choose an RF solution that has a low quiescent current in receive mode and has the ability to wake the Arduino from sleep when needed.

Ok I will look more into the charging part of the battery. I used the RadioHead library for the radio modules and looked into the docs and found a method that will sleep the receiver or transmitter, I believe. Would that be acceptable? Also how would I "Sleep" the rest of the sensors? digitalWrite(pin, LOW)?

It depends on the sensors. Some you won't need to, some you will be able to instruct to "sleep", and some you will need to cut the power to. A P-channel MOSFET can be used for that, which you can control with a digital IO pin.

Well in that case I have to first make the circuit, calculate it's Amp output and then calculate what battery will it need if the circuit runs as it is and the recalculate Amp output with most modules sleeping and then see what battery I could use. As you said the solar panel gives an output of 183mA so a battery of 183mAh will charge in 1 hour. How could I effectively charge the 500mAh battery you were talking about that would last about 50 days, if the dht11 and rf receiver are on?

Let us continue this discussion in chat.

Current consumption of DHT11 depends on how often you sample it. Receiver current depends on what the receiver is. Note that a solar panel is a current source, and batteries of different types may need a voltage source, current source, or a managed combination of the two. That's what the charge controller is for. For example you will need to convert the solar current source into a voltage source for lead acid batteries.

You just said a lot of stuff I am not familiar with :P Maybe I could sample the DHT11 every minute? So every 60 seconds the DHT11 sends me the current temperature and humidity and that is stored in my computer, so when I ask it to send me info about the weather then it just shows me the last input I got from the dht and not the actual current weather condition. So I guess the dht11 could be used only once every minute. The receiver is a 433mHz rf module, the most common one. Could you suggest a charge controller that will work in my situation?

So I found out that my circuit draws up to 1mA so I could use 2 batteries of 3.7V connected upside-down (that is 7.4V) and 500mAh to power the circuit for at least 500 hours, so 20.8 days.

You won't charge those with your solar panel.

Why won't they charge?

You said the solar cell will produce 183mA in 8 hours so, 183mA - 1mA = 182mA left for charging. 182mA / 0.2C = 910mAh capacity. So isn't that enough to power the 500mAh battery??

You would need to boost the voltage. You only have 6v max...

How would I boost the voltage?

With a boost regulator - however that then reduces your available current. This is why I suggested a 3.3V Arduino and a switching regulator since it is more suited to running from the kind of batteries that a 6V solar panel is capable of charging.

If I had an Arduino UNO R3, but only used it's 3.3V pin, would that be ok?

No. You can't run a 16MHz Arduino at 3.3v.

I still need batteries above 5V though and all I can do is get 5 1.2V batteries to get to 6V, to be able to power them with the solar cell. Could that work?

No. You need a higher voltage than the batteries in order to be able to charge them. I suggest you do a little reading and learning before you start this project.

I had to find out today what type of battery I needed, that's why I posted such a question here. Could I manage with 4 1.2V batteries to just make it work for a bit?

4.8V is fine for a 16MHz Arduino. Read the datasheet for the chip. In the electrical characteristics there's a graph that shows the relationship between the voltage and the maximum supported frequency.

I saw that the arduino regulates the power so anythin 4V-20V would anyways be regulated so it's fine until the battery drops below 4V?

No. You do not want to use the built in regulator. That is a terrible regulator and will waste lots of power, and won't allow you to run at anything under 6.2V.

What regulator would I have to use? I just need this to work in theory and probably for a smaller amount of time than days, maybe hours. Wouldn't I be able to charge the battery and run the arduino on 4.8V?

You don't need a regulator at all. 4.8v is within the specifications of the chip.

OK then the final circuit will consist of the solar panel connected to the lithium charger, that will be charging the 500mAh 4.8V battery, that will be powering the arduino's circuit that draw 1mA at max estimation. So that will work? Am I could after 1 day of searching for batteries? :P

The only problem with that scenario is that you shouldn't power a circuit from a lithium battery that is being charged. You risk confusing the charger and over-charging the battery.

What would you suggest? Charging the battery until it's full and simultaneously powering the arduino, from the solar cell? And if the solar cell goes out then the arduino should draw power from the batteries?

That is the normal way, yes. The circuit I usually use is the one shown in this question. Most of it is your Li-Ion charger. It's the portion around the battery - Rpull, Q1, and D1 - that forms the interesting part that switches the load's supply for you automatically.

Ok thank you so much for your help and patience. Would getting x2 3.7V batteries lowered down to 5.5V with like a potentiometer work?

No, but using a high efficiency switching regulator with them would. But then you can't charge them with just 6v.

So it still wouldn't work? My only option is to find Li-Ion 1.2V batteries?

No, you have plenty of options. The best one is to not use a 5v Arduino and instead pick one of the more modern 3.3v ones. Then you can use a single li-ion battery.

Could you name one? I am also in a budget and batteries go for like 9$ which is 27% of it.

I'm thinking maybe I could get 1 lithium battery and use a boosting circuit to get the voltage to 5V to power the arduino. Will the draw increase? Even if it does we should probably be good?

There are arduinos specifically designed for low power use of lithium batteries. Check the website.


text:
Can't find a #include
I'm using the Marlin 2.0.3 for a 3D printer project. I'd like to tear apart the code, but I don't see a #include to anything in the Marlin.ino, Configuration.h, Configuration_adv.h, nor Version.h.
If I use a verbose compilation, I see the ./src/HAL/HAL_AVR/HAL.cpp is the first thing it tries to include, but I don't see that writen in the code.
How does it know what to include?
Incase you can answer without downloading it:
Marlin.ino and Version.h is just comments.
Configuration.h and Configuration_adv.h are just a bunch of #defines.
Link to Marlin: https://github.com/MarlinFirmware/Marlin/releases/tag/2.0.3

The IDE compiles everything in the src/ folder too...

Ah, that makes a lot more sense. Thanks!


text:
Continue playing sound during interrupt routine
I'm trying to play a tone (on an Arduino Mega through the tone library) and have the tone not be interrupted if an interrupt routine is called while the tone is playing. I'm not sure it's possible. The code block is below. Relevant functionality is:
-A while loop runs indefinitely until Button S1 is pressed. Pressing Button S1 triggers an interrupt routine in which interruptFlag_s1 is set to 1.
-This starts a tone playing for 300ms.
-There's a possibility that another button press interrupt is triggered during the 300ms tone. This interrupts the tone for about 0.5ms, enough to make a perceptible break in the tone that I'd like to avoid.
-Ideal scenario is that the audible tone isn't interrupted by the interrupt routine.
    while (restart == 0) {
      if (interruptFlag_s1 == 1 || interruptFlag_s2 == 1) {
        if (interruptFlag_s1 == 1) {
          primary_sensor = 1;
          interruptFlag_s1 = 0;
          rBot = false;
          gBot = true;
          bBot = false;
        } else if (interruptFlag_s2 == 1) {
          primary_sensor = 2;
          interruptFlag_s2 = 0;
          rBot = false;
          gBot = false;
          bBot = true;
        }

        interruptFlag_rtc = 0;
        finish_id = 0;
        button_flag = 0;
        time_diff = 0.00;
        alt_finish_time = 0.00;
        tone(speakerPin, 3000, 300); // Start tone
        restart = 1;
      }
    }

Interrupts should not affect tone() unless the ISR takes too long to execute. Keep your ISR short and all should be good.

Did you try it and experience discontinuity?

The sound is itself generated by an interrupt routine. Since only one interrupt routine can happen at a time, if your own interrupt routine takes too long, then you will get interruption in the sound.
There is nothing you can do about that other than making your interrupt routine short enough that it doesn't cause any interruption in the sound.


text:
MIDI Keyboard control
I am relatively new to Arduino and I am looking to implement a simple system that uses a MIDI keyboard to
(i) detect key presses (via MIDI messages) from the keyboard
(ii) store the information of the MIDI messages (note pressed, velocity)
(iii) Light up LEDS on the keyboard based on what key was pressed
I am currently in the planning stage and I am considering using an Arduino Mega. I have two issues I am not sure about:
(i) My keyboard only has a Male USB A to Male USB B connection with the former connecting to the computer and the latter to the keyboard. So far in my search, I have seen that all Arduino-MIDI projects require a 5 pin MIDI cable to interface with the Arduino using the circuit in this webpage (https://www.instructables.com/id/Send-and-Receive-MIDI-with-Arduino/). Is there any way to detect MIDI messages that does not require the additional circuit and just uses the USB cable?
(ii) Although in theory control of the LEDs should be easy in the program, I am concerned that the delays in the serial communication and hardware interrupts would make it difficult to simultaneously receive the MIDI messages and control the LEDs.
One way I thought of avoiding these problems is to use MATLAB MIDI package (https://uk.mathworks.com/help/audio/ug/midi-device-interface.html#mw_80dc54f4-867c-43c0-a159-e56ee62ec4ab) to interface with the MIDI device and use the MATLAB Arduino package to control the Arduino. I am not sure, however, if MATLAB is suboptimal compared to the standard Arduino IDE.
This is my first question in Arduino StackExchange (or any StackExchange site), so I appreciate the answers and feedback on my question.

Is there any way to detect MIDI messages that does not require the additional circuit and just uses the USB cable?

You could probably do it with a "USB Host Shield", though I have no experience of them and don't know if they can handle MIDI - you'll have to research this.

Although in theory control of the LEDs should be easy in the program, I am concerned that the delays in the serial communication and hardware interrupts would make it difficult to simultaneously receive the MIDI messages and control the LEDs.

Highly unlikely. You'd have to be doing something very wrong to make it so slow to respond that you'd see any delay.

I am not sure, however, if MATLAB is suboptimal compared to the standard Arduino IDE.

I cannot comment, I have never used MATLAB. If you don't use a USB Host Shield then you will certainly require something that runs on a PC to forward the MIDI information over serial.  Whether you create that in MATLAB or some other programming language is neither here nor there as far as the Arduino is concerned - you'll still need to program the Arduino itself, and that can be done in the IDE and still use MATLAB for the PC portion of your setup.

I don't have experience with USB MIDI, but I'm (almost) sure it should work with a shield (as Majenko already writes).
I have experience with the following library. I used it for normal (DIN5) MIDI, not via USB, but it seems to support USB too: https://github.com/FortySevenEffects/arduino_midi_library
This library is interrupt based, try to keep the interrupts as short as possible, you can do the processing of the MIDI messages in the main function, together with driving the LEDs.
I created a (temporary) USB merger which worked quite well, so yes, with a Mega it's easy to use 3 (or 4) MIDI channels, using DIN5. It's more than fast enough. MIDI is just 31.250 baud.
I found it was very annoying to use the only UART of an Arduino Uno to use for both MIDI and debugging/uploading, so it's easier to use 3 UARTs from the Mega, and when your program works, use the main RX/TX for MIDI too (make it flexible).
In case you think about use the software serial: forget about it, at least for reading MIDI.


text:
Reading out two sensors via Com-Port at the same time
I have two Arduino Nano Every and a sensor connected to each of them. Here is what's happening:

I upload the sketch to the first Arduino on Com4 and see its output is correct via the Serial Monitor
I open a new instance of the Arduino-software, upload the same sketch to the second Arduino on Com6 and see its output is correct. However, in the meantime the Arduino on Com4 has stopped sending or receiving data
If I close the second IDE-instance and re-upload the sketch to the first Arduino on Com4, it starts working again.

So, essentially I have two Arduinos which I can't read out at the same time.
The sensors are not connected, so I don't know where the problem is. Shouldn't the Com-Ports be independent?

UPDATE, self answer:
It was a broken USB cable.

Shouldn't the Com-Ports be independent?

Not in the Arduino IDE, no. Basically the IDE is [expletive deleted] when it comes to using more than one board at a time.
You're better off using a proper serial terminal program, not the "serial monitor" in the IDE. Something like Teraterm or Putty, where you can have multiple instances on different ports at once.

Interestingly, the same happens with Putty..

you could write a monitoring sketch in Processing ... https://processing.org/

Or upgrade to UECIDE that has much much better port handling.

I actually used LabView in the first place which usually has no difficulties handling multiple ports at once. However, it doesn't work as well ... and you also see that the LED stops blinking, so I assume it's not just a software problem?

Maybe the firmware in the ATSAMD isn't handling a USB disconnection (LineState change) properly, or maybe the client software isn't opening the port right (Setting LineState).

It is kind of ironic that the chip they chose to implement the USB interface is far more powerful than the chip that you as a user get to program.

@Majenko, it is ATmega4809 20 MHz, 48kB flash, 6 kB SRAM; SAMD11 48 MHz, 16 kB flash, 4kB SRAM

Yes. Like I said. A slow 8 bit vs a faster 32 bit. More power in the USB interface.

I use multiple instances of the Arduino IDE open at once to solve this problem, and it works well for multiple serial connections from multiple boards at once. You get one serial connection per instance open. I used to have multiple versions of the IDE installed for this to work but I think it works fine just running multiple instances of the program at once now. If not, just run multiple zip-installed instances of the IDE from different unzipped folders.

Also, I have a Python demo to read serial data from an Arduino if anyone wants it (and if I won't be suspended for sharing a link to it, of course). It's on my GitHub I believe. It makes logging from Arduino really easy and versatile, and shows how to get a PC program and Arduino talking.


text:
Break a while loop with a push button (AccelStepper.h)
Disclaimer: This is my first Arduino project.
Background: I am building a "rapunzel tower" lantern for my daughter: the witch pays a visit to Rapunzel meanwhile my daughter can read a book (or still play a bit) before going to sleep.
Goal:If a button is pushed --> a stepper motor turns on and my daughter's lantern switches on (via a relay) --> the stepper motor spins to the left (+/- 5 minutes) to bring the witch to the tower--> a led in the tower room switches on and off (+/- 1 minute) --> the stepper motor spins to the right (+/- 5 minutes) to bring the witch down and the lantern switches off (and my daughter needs my sleep).
Issue If my daughter want to sleep before the witch gets down, she must be able to turn off the lantern while the witch is still on the move (up or down). However, I am unable to do so. That is, I am unable to break the while function when the button is pushed to turn off the latern.
Code
Right now, I use the following piece of code below (compiled from different sources).
I know that I use the delay function instead of the millis function, but that is for my next step. The same goes for the time the motor spins (which I still need to tweak).
Any help is welcome. Thanks.
/* Example sketch to control a 28BYJ-48 stepper motor with ULN2003 driver board, AccelStepper and Arduino UNO: continuous rotation. More info: https://www.makerguides.com */
// Include the AccelStepper library:
#include <AccelStepper.h>
// Motor pin definitions:
#define motorPin1  3    // IN1 on the ULN2003 driver
#define motorPin2  4    // IN2 on the ULN2003 driver
#define motorPin3  5    // IN3 on the ULN2003 driver
#define motorPin4  6    // IN4 on the ULN2003 driver
// Define the AccelStepper interface type; 4 wire motor in half step mode:
#define MotorInterfaceType 8
// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper library with 28BYJ-48 stepper motor:
AccelStepper stepper = AccelStepper(MotorInterfaceType, motorPin1, motorPin3, motorPin2, motorPin4);

// Code to trigger the light and motor
const int buttonPin = 1;   // the number of the pushbutton pin
const int ledPin =  7;     // the number of the LED pin

int relayPin = 2;          // Connected to relay
int buttonState = 0;       // variable for reading the pushbutton status

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin,INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, HIGH);
  // Set the maximum steps per second:
  stepper.setMaxSpeed(1000);
}
void loop() {
  buttonState = digitalRead(buttonPin);
  Serial.println(buttonState);

  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, LOW);
    digitalWrite(relayPin, LOW);
  } else {
    digitalWrite(relayPin, HIGH);
    // Let the witch go up.
      // Set the current position to 0:
      stepper.setCurrentPosition(0);
      // Run the motor forward at 500 steps/second until the motor reaches 4096 steps (1 revolution):
      while (stepper.currentPosition() != 8096) {
          stepper.setSpeed(500);
          stepper.runSpeed();
      }

    // Let the witch the light turn on and off in Rapunzel's room
      digitalWrite(ledPin, HIGH);
      delay(1000);
      digitalWrite(ledPin, LOW);

    // Let the witch let climb down.
      // Reset the position to 0:
      stepper.setCurrentPosition(0);
      // Run the motor backwards at 1000 steps/second until the motor reaches -4096 steps (1 revolution):
      while (stepper.currentPosition() != -8096) {
        stepper.setSpeed(-1000);
        stepper.runSpeed();
      }
  }
  delay(5);
}

while (stepper.currentPosition() != 8096) { is a loop that repeats many times ... you can check for a button press inside that loop .... btw, the stepper.setSpeed(500); should be outside of the loop

You can put a read for the button inside the while loop, but a better solution would be to get rid of the while loop entirely and let the loop function do the looping.

Thanks for the advice. I will try to get rid of the loop asap and come back to you... putting the button in the while loop did not work (the push event is registered [the led on the arduino blinks when the button is pushed and the while loop paused, but when the button is released the stepper continues instead of stopping).

Yes, it works! Thanks for the advice.


text:
LiquidCrystal swap lines with interrupt
#include <Wire.h>
#include <LiquidCrystal.h>
int temp;
const int rs = 13, en = 12, d4 = 11, d5 = 10, d6 = 9, d7 = 8;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
char Nick[15] = {' ', ' ', 'T', 'A', 'R', 'I', 'F', ' ', 'Z', 'I', 'N', 'E', 'D', ' ', ' '};
int butonPin = 2;

void setup() {
  Wire.begin(1);
  Serial.begin(9600);
  pinMode(butonPin,INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(butonPin), Rev, RISING);
  lcd.begin(16, 2);
}

void loop() {
  Wire.onReceive(data);
  lcd.setCursor(2, 1);
  lcd.print(temp);

  if (temp < 25) {
    lcd.setCursor(5, 1);
    lcd.print("NORMAL");
    lcd.print(" ");
    lcd.setCursor(12, 1);
    lcd.print(" ");
  }
  if (temp >= 25 && temp <= 30) {
    lcd.setCursor(5, 1);
    lcd.print("HOT");
    lcd.print(" ");
    lcd.setCursor(11, 1);
    for (int i = 0 ; i < 3 ; i++) {
      lcd.print(" ");
    }
  }
  if (temp > 30) {
    lcd.setCursor(5, 1);
    lcd.print("VERY HOT");
    lcd.print(" ");
  }
  lcd.setCursor(0, 0);
  for (int j = 15; j > 0 ; j--) {
    lcd.print(Nick[j]);
  }
  lcd.setCursor(0, 0);
  delay(70);
  int swap = Nick[15];
  for (int i = 15; i > 0; i--) {
    Nick[i] = Nick[i - 1];
  }
  Nick[0] = swap;
}
void Rev(){
   Wire.onReceive(data);
  lcd.setCursor(2, 0);
  lcd.print(temp);

  if (temp < 25) {
    lcd.setCursor(5, 0);
    lcd.print("NORMAL");
    lcd.print(" ");
    lcd.setCursor(12, 0);
    lcd.print(" ");
  }
  if (temp >= 25 && temp <= 30) {
    lcd.setCursor(5, 0);
    lcd.print("HOT");
    lcd.print(" ");
    lcd.setCursor(11, 0);
    for (int i = 0 ; i < 3 ; i++) {
      lcd.print(" ");
    }
  }
  if (temp > 30) {
    lcd.setCursor(5, 0);
    lcd.print("VERY HOT");
    lcd.print(" ");
  }
  lcd.setCursor(0, 1);
  for (int j = 15; j > 0 ; j--) {
    lcd.print(Nick[j]);
  }
  lcd.setCursor(0, 1);
  delay(70);
  int swap = Nick[15];
  for (int i = 15; i > 0; i--) {
    Nick[i] = Nick[i - 1];
  }
  Nick[0] = swap;
}

void data(int numBytes) {
  while (Wire.available()) {
    temp = Wire.read();
  }
}

In lcd's first line i have scrolling text.
Second line it shows current temperature and data from another master device.
My question is i want to change text line when button pressed and text shouldn't go back to old state it need to be stay in changed line and when the button repressed it change again
In my code when the button pressed several times lcd  gone weird :
I tried swap lines with lcd.setCursor() function :
In loop function :
lcd.setCursor(0, 0);
      for (int j = 15; j > 0 ; j--) {
        lcd.print(Nick[j]);
      }

In reverse function :
lcd.setCursor(0, 1);
  for (int j = 15; j > 0 ; j--) {
    lcd.print(Nick[j]);
  }

Thanks for answers guys

your ISR (interrupt service routine) is too long and complex ... a press of a button should call an ISR that only sets a flag and exits .... the flag should be checked and serviced during the execution of loop()

Catching humans pressing buttons is a poor use of an interrupt.  You could do this a lot easier if you just poll the button.  Your interrupt function contains way too much code and uses code like delay that just plain won't work in an interrupt context.  If you don't KNOW what you're doing with interrupts then it's probably best to leave them alone.  You really need a lot of study before you use them.  There's obviously a lot you don't know.

For one, inside an ISR all other interrupts are off.  So things like delay and serial comms and maybe even stuff to do with your LCD simply won't work at best or lock up the program at worst.

I readed all answers and %100 you guys right if i have chance i leave alone this interrupt madness but this project is my final assignment in college and my instructor was made a working one. Actually i am not expert in arduino like you guys said.