text:
Serial Data Formatting not Correct?
I am writing two Arduino Uno programs. One is a remote with a joystick and the other has five LED's indicating which direction the joystick is pointing. They are Bluetooth, so everything is sent and received through Serial. I am sending three variables by joining them into one string, separated by colons. Then I separate them back into three variables on the other arduino The joystick, Bluetooth, and LED's part of the programs work, I'm having trouble receiving the data and separating it. I have included both programs below. As it is now, it doesn't work. In the slave code, you can change the int xPosition = getValue(input, ':', 0).toInt(); to int xPosition = getValue(input2, ':', 0).toInt();( also change yPosition and buttonState) and everything works. What is the difference between that string and what I'm receiving?
Slave code:
#include <SoftwareSerial.h>
#define RxD 7
#define TxD 6
SoftwareSerial BlueToothSerial(RxD,TxD);
char flag=1;
String input;
int xPosition;
int yPosition;
int buttonState;
char outstring[30];
char *input2 = "510:609:1\r\n";

void sendBlueToothCommand(char *Command)
{
  BlueToothSerial.print(Command);
  Serial.print(Command);
  delay(100);
  while(BlueToothSerial.available())
  {
     Serial.print(char(BlueToothSerial.read()));
  }
}

String getValue(String data, char separator, int index)
{
 int found = 0;
  int strIndex[] = {0, -1  };
  int maxIndex = data.length()-1;
  for(int i=0; i<=maxIndex && found<=index; i++){
  if(data.charAt(i)==separator || i==maxIndex){
  found++;
  strIndex[0] = strIndex[1]+1;
  strIndex[1] = (i == maxIndex) ? i+1 : i;
  }
 }
  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

void setup()
{
   pinMode(12, OUTPUT);
   pinMode(11, OUTPUT);
   pinMode(10, OUTPUT);
   pinMode(9, OUTPUT);
   pinMode(8, OUTPUT);
   Serial.begin(38400);
   BlueToothSerial.begin(38400);
   delay(500);
   Serial.println("Starting...");
}

void loop()
{
    if(BlueToothSerial.available())
    {
      input = char(BlueToothSerial.read());
      int xPosition = getValue(input, ':', 0).toInt();
      int yPosition = getValue(input, ':', 1).toInt();
      int buttonState = getValue(input, ':', 2).toInt();
      Serial.println("xPosition");
      Serial.println(xPosition);
      Serial.println("yPosition");
      Serial.println(yPosition);
      Serial.println("buttonState");
      Serial.println(buttonState);
      if ((xPosition == 507)&&(yPosition == 506)){
        clear();
        digitalWrite(8, HIGH);
      } else if ((xPosition == 507)&&(yPosition == 0)){
        clear();
        digitalWrite(12, HIGH);
      } else if ((xPosition == 507)&&(yPosition == 1023)){
        clear();
        digitalWrite(10, HIGH);
      } else if ((xPosition == 1023)&&(yPosition == 507)){
        clear();
        digitalWrite(11, HIGH);
      } else if ((xPosition == 0)&&(yPosition == 1023)){
        clear();
        digitalWrite(9, HIGH);
      }
    }
}

void clear() {
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
  digitalWrite(8, LOW);
}

Master code:
#include <SoftwareSerial.h>
#define RxD 7
#define TxD 6
SoftwareSerial BlueToothSerial(RxD,TxD);
int xPin = A1;
int yPin = A0;
int buttonPin = 2;
char outstring[30];
int xPosition = 0;
int yPosition = 0;
int buttonState = 0;

void sendBlueToothCommand(char *Command)
{
  BlueToothSerial.print(Command);
  Serial.print(Command);
  delay(100);
  while(BlueToothSerial.available())
  {
     Serial.print(char(BlueToothSerial.read()));
  }
}

void setup()
{
   Serial.begin(38400);
   BlueToothSerial.begin(38400);
   delay(500);
   pinMode(xPin, INPUT);
   pinMode(yPin, INPUT);
   pinMode(buttonPin, INPUT_PULLUP);
   BlueToothSerial.println("Hello");
}

void loop()
{
  joy();
  sprintf(outstring, "%d:%d:%d\r\n", xPosition, yPosition, buttonState);
  BlueToothSerial.println(outstring);
  Serial.println(outstring);
}

void joy() {
  xPosition = analogRead(xPin);
  yPosition = analogRead(yPin);
  buttonState = digitalRead(buttonPin);
}

The problem is you are only reading one character and trying to split that single character into other smaller units. It just isn't going to happen.
Instead you need to append each character to the end of a string until you receive the end-of-line characters (\r\n). Then you can split that entire string into parts.
Alternatively you can read numbers until you hit a : or a \r\n and build up the numbers directly without having to store anything.
My preferred method is the first, but I know Nick Gammon prefers the second, so I shall leave it to him to describe his favourite Finite State Machine for you.
To store all the data in a string I use a C string, not one of Arduino's dodgy String objects.
char input[15];
int ipos = 0;

Then you read the data:
if (BlueToothSerial.available()) {
    char c = BlueToothSerial.read();
    if (c == '\r') continue; // Skip the carriage return
    if (c == '\n') { // We have the line ending
        // Split the data on :
        char *xtxt = strtok(input, ":");
        char *ytxt = strtok(NULL, ":");
        char *btxt = strtok(NULL, ":");
        // Convert the text to integers
        if (xtxt) xPosition = atoi(xtxt);
        if (ytxt) yPosition = atoi(ytxt);
        if (btxt) buttonState = atoi(btxt);
        ipos = 0; // Reset the string to the start
    } else {
        // If there is still room in the array
        if (ipos < 14) {
            // Add the incoming character
            input[ipos++] = c;
            // and terminate the string.
            input[ipos] = 0;
        }
    }
}

In the slave's loop(), when you say
input = char(BlueToothSerial.read());

I'd expect just the first character of the serial stream to be read and stored.  Without further investigation, I don't know just what a String class does when you assign a character to it, but I doubt that any of the following code ever has more than one character at a time to work on.  This will keep your getValue() calls from working like you want.
Instead of using String objects and your getValue() code, consider using code like the following to handle the serial input.  The data format that this code expects is nnnxnnnynnnb, where each nnn is a series of digits, and x, y, b are literal characters.
This code shortens two of the overly-verbose parts of your code by:
• Use of an array and subscripting to replace the long list of if statements that sort out the combinations of low/medium/high x and y values.
• Use of Streaming.h (which you can install by unzipping Streaming5.zip from arduiniana.org into your sketchbook/libraries directory) to clean up long lists of Serial.println() statements, without increasing code size.
#include <Streaming.h>
int numVal = 0;

void doAction() {
  byte pins[] = { 9,0,0, 12,8,10, 0,11,0 };
  byte xy = 3*(x/500)+y/500;
  byte pin = pins[xy];
  if (pin) {
    clear();
    digitalWrite(pin, HIGH);
  }
  Serial << "xPosition =  " << xPosition << endl;
  Serial << "yPosition =  " << yPosition << endl;
  Serial << "buttonState = " << buttonState << endl;
  numVal = 0;
}

void loop() {
  while (BlueToothSerial.available()) {
    byte c = BlueToothSerial.read();
    if ('0' <= c && '9' >= c) {
        numVal = 10*numVal + c - '0';
    } else {
      switch (c) {
      case 'x':  xPosition = numVal;   break;
      case 'y':  yPosition = numVal;   break;
      case 'b':  buttonState = numVal; doAction(); break;
      }
      numVal = 0;
    }
  }
}

authors: Алексей Валл


text:
Arduino join multiple strings and numbers and then seperate them
OK, I'm working on a remote controlled robot. Both the robot and the remote use Arduino with a Bluetooth shield. The Bluetooth is working and I need to send something similar to this over Bluetooth:
X:1026,Y:1026,Button:1
There may be more buttons added and X,Y can be between 1026 and 0. How can I build that string from:
xPosition = 1026;
 yPosition = 1026;
 buttonState = 0;
I also need to be able to separate that string back into variables on the 2nd Arduino.
EDIT: I have seen other questions similar to this but they involved Serial. I am using Bluetooth.
EDIT AGAIN: I am sending the data over Bluetooth with the BlueToothSerial.print command from the SoftwareSerial.h library. (BlueToothSerial is SoftwareSerial BlueToothSerial(RxD,TxD);)

Have a look at the Serial.parseint function and format your output and input so the come in correct order.

You do realise, don't you, that the fact that you're using Bluetooth is a complete red-herring? It is just being used as a bridge between two serial ports. What you read pertaining to Serial is the same as your bluetooth.

Indeed, serial-interfaced Bluetooth is just serial... with one catch for the unwary.  Because the bluetooth portion will be packetized, data may arrive at the far end in bursts, potentially with gaps between them at arbitrary points, such as the middle of a word rather than in any logical place. Well written receiving software won't care about that, as it should read across delays until finding a known end-of-message condition such as a newline character. But badly written software that makes invalid assumptions (such as assuming that a full message will be received at once) could be confused.

To make the string you can:
char outstring[30];
sprintf(outstring, "X:%d,Y:%d,Button:%d", xPosition, yPosition, buttonState);

Be sure to make the outstring big enough to store it all.
That is, of course, if you actually need to have the whole thing in one string all the time.  You haven't said how you are sending it (yes, I know, bluetooth, but there is bluetooth and there is bluetooth, and there are different ways of it working.)
Splitting a string like that can be done with strtok() then looking for the location of the colon in each returned token. Or, depending on how the string data actually arrives, could be parsed on a character-by-character basis, which would be better. Again, because you haven't told us how the data is actually being transferred it's impossible to elaborate on that.

I edited the post with how I am sending the data. I can send it separately and receive it as one string, but I don't know how too separate the string into multiple variables.

@Starwarsfan2099 Majenko hinted on using strtok() which is a C++ function and is well documented:  http://www.cplusplus.com/reference/cstring/strtok/ you might also use the Arduino indexOf function to find the comma's "," in your text string, see this tutorial: https://www.arduino.cc/en/Tutorial/StringIndexOf

source: Stack Exchange

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

sort: votes


text:
Arduino array length
So I have a programme that loads a text file from an sd card into a string array. Each line in the text file is stored in a different string in a string array. Well its supposed to be.
file = SD.open("/classes/basic.txt", FILE_READ);
Serial.print("Reading, Checking and Compiling \n\n\n");

for(int i = 0; i < sizeof(result)-1;i++){
 while(file.available()) {
  character23 = file.read();
  content.concat(character23);

}
if (content != "") {
  result[i] = content;
    Serial.println(content);

}

}
I want each line in the txt file to be stored in a different string in the array, in chronological order and each string has to be accessible individually. The problem with this code is that it stores the whole text file in one string. How can I fix this?
EDIT: here is what I have now
  file = SD.open("/classes/basic.txt", FILE_READ);
  Serial.print("Reading, Checking and Compiling \n\n\n");

 for(int i = 0; i < sizeof(result)-1;i++){
   while(file.available()) {
  character23 = file.read();
  if (character23 == '^') break;
  content.concat(character23);

}
if (content != "") {
  result[i] = content;
  Serial.println(content);

  delay(1000);
}

}
 Serial.println(result[3]);

To do that, you need to read the file until you reach a line break.
Replace this code:
while(file.available()) {
  character23 = file.read();
  content.concat(character23);
}

by this:
while(file.available()) {
   character23 = file.read();
   if (character23 == '\n') break;
   content.concat(character23);
}

I'm trying to debug and I'm trying to find what is stored in a certain string of the array is this correct: Serial.println(result[1]); because it keeps returning nothing

Can you show your complete code rather than a snippet?

ye ill edit the above code

where is the declaration of the array? Also, this line is wrong if (character23 == '^') break;. It should be \n not ^.

ye but all the lines in the txt file end in ^

The array is at the top of the class

string Array[4];

what if you print the first line? like this: Serial.println(result[0]);

it prints nothing

if I rpint content I get

println("sharkByte OS v1.1)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)

Let us continue this discussion in chat.

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


text:
Arduino IDE Display Code Line Numbers
In the Arduino IDE: How can I get the line numbers shown in a sidebar of the editor?
It is hard to find which line my errors are referring to without them...
I am using Arduino IDE on a form of Windows.

@crabman84, how do you know that the the person who posted this question > 2 years ago was using Windows?

Go to File > Preferences. Under the Settings tab, click the checkbox for Display line numbers.

Keep in mind that this option is available in the latest version of the Arduino Integrated Development Environment (v1.6.6). In case you are using GNU/Linux distribution is recomended to use the one that is NOT in the distribution's repositories but the one that is offered in https://www.arduino.cc/en/Main/Software
If you are using a Linux OS this solution may not work. Look at the 'preferences.txt' where you can edit your preferences in a file without a GUI.It will display all possible options available for your current version of Arduino IDE on your OS. It is usually in the '.arduino' folder which may be in your 'home' folder.

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


text:
Can I integrate Arduino in a CI/CD setup?
While it seems less valuable to emulate Arduino in a CI/CD setup, are there any experiences/best practices for collaborative teams to automate their acceptance tests where a real Arduino is integrated into a CI/CD toolchain (or, what are comparable practices)?
Minimal example of acceptance testing:

compilation is successful for a given compiler version.

Step one: Define what acceptance means in your project workflow.

added a minimal example.

For that: run arduino-builder in a script run by a cron job.

There are different approaches around. I can only point you to some of them:

GitLab CI approach A
GitLab CI approach B
Your specific solution: To build pipelines for Arduino (although its Azure) but you can use this technique on Linux with Jenkins

As a valuable commenter mentioned on your previous question - this does not cover the attached hardware testing (sensors/ motors) - this has to be "integrated" via a test lab station, which you have to control manually (or semi-automated via lab equipment) on defined release/version changes

thank you so much @Codebreaker007! Trying out approach A to compile the controller code for an open source ventilator project :-)

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


text:
Arduino loading from file
Hello I have a programme that loads a piece of text from a file. In this case it loads "drawrect(4,10,20,20);" from the txt file and stores it in a string. I then use substrings to change the string into just "4,10,20,20" which is good but I need to simplify it down even more to four strings each with one of those 4 numbers in it.
Currently I use:
void drawRectMethod(String s){
  String var1,var2,var3,var4;
  s = s.substring(s.indexOf('(') + 1);
  s = s.substring(0, s.lastIndexOf(')'));
  Serial.println(s);
}

to simplify the string down to "4,10,20,20" but this wont work to store each number in a separate string. How can I can I store each variable in a separate string. The numbers will be stored in var1 - var4.

This is not nearly related to Arduino at all?

ye it is an Arduino based project the string is loaded from an sd card that is attached to an arduino

Ah, okay, an Arduino is sending text over USB. But what is receiving it at the moment?

the sd card sends text to a string on the Arduino the Arduino then reads it and if it says drawrect(4,10,20,20) it will draw a rectangle on my nokia 5110 screen. I just cant figure out how to store each of the 4 numbers in a separate string hopefully using the substring method like I have been doing before

Why is the title: "Java loading from file"?

You meant that you're searching for the Arduino equivalent of the Java code above?

Want some help with this as well? Soon I will have written most of your sketch. No seriously I was hoping that the previous question-answer would help you understand how to parse strings.

oops it should be arduino

@MikaelPatel I have  written quite a lot of the sketch, there is just a few things I didn't understand and I am trying to learn like these things I've asked because this is all new to me but I want to understand it

Need some more help? As I previously wrote that snippet I might as well continue until you understand how to use indexOf() and substring().
  String s = "draw(10,20,30,40)";

  // Parse the argument list
  s = s.substring(s.indexOf('(') + 1);
  s = s.substring(0, s.lastIndexOf(')'));

  // Parse comma separated arguments
  String arg[4];
  for (int i = 0; i < 3; i++) {
    int ix = s.indexOf(',');
    arg[i] = s.substring(0, ix);
    s = s.substring(ix + 1);
    Serial.println(arg[i]);
  }
  arg[3] = s;
  Serial.println(arg[3]);

There is absolutely no error handling in this. You will have to add that. You can also improve the parse of the right parenthesis. That could be added last instead.
Later in the game we will come to why using String is a bad idea and why a character buffer and the standard library functions such as strtok() is a much better solution strategy both performance and memory footprint and especially heap.
  char* s = (char*) "draw(10,20,30,40)";
  s = strtok(s, "(),");
  Serial.println(s);
  while ((s = strtok(NULL, "(),")) != NULL)
    Serial.println(s);

Maybe the simplest solution is to use sscanf(). That will also do the conversion from text to binary.
  const char* s = "draw(10,20,30,40)";
  int x, y, w, h;
  int n = sscanf(s, "draw(%d,%d,%d,%d)", &x, &y, &w, &h);
  Serial.print(F("n="));
  Serial.println(n);
  Serial.print(F("x="));
  Serial.println(x);
  Serial.print(F("y="));
  Serial.println(y);
  Serial.print(F("w="));
  Serial.println(w);
  Serial.print(F("h="));
  Serial.println(h);

Cheers!


text:
Arduino drawing a bitmap on nokia 5110 lcd
Hello I finally got my nokia 5110 lcd working, I have tested it by displaying bitmap images other people have made. I made my own image and then used lcd assistant to turn it into an array. First look at my code.
#include "U8glib.h"

U8GLIB_PCD8544 u8g(8, 4, 7, 5, 6);  // CLK=8, DIN=4, CE=7, DC=5, RST=6
int x = 5;
int y = 5;
int level = 5;
const uint8_t rook_bitmap[] U8G_PROGMEM = {
0x7E, 0x82, 0x04, 0x8E, 0x7A, 0x42, 0xB4, 0x24, 0x08, 0xD8, 0x48, 0x08, 0x08, 0x0C, 0x02, 0x22,
0xD9, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x1E, 0x11, 0x21, 0x22, 0x14, 0x3B,
0xD4, 0x25, 0x29, 0x68, 0xA8, 0xA8, 0x74, 0x0C, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
void draw(void) {
  // graphic commands to redraw the complete screen should be placed here
  u8g.drawBitmapP( 5, 5, 3,18, rook_bitmap);
}
void setup(void) {
}
void loop(void) {
  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );
// y++;
  // rebuild the picture after some delay
  delay(1000);
}
The part that goes wrong is at u8g.drawBitmapP(5,5,21,18, rook_bitmap);
I know it is to do with the 21 and 18 being wrong because I don't know where to get those numbers. Is it the width and height of the image when it is in paint.net or what is it?

The 21 and 18 are the dimensions of the image. It's not just pixels though.
The first number (21) is the number of bytes in a row of the image - that is one eighth of the width in pixels.  The width must be a multiple of 8.
The second number is the number of rows in the image - basically the height in pixels.
The two numbers, when multiplied together, must equal the number of bytes in your array.
From the documentation:

Description
Draw a bitmap at the specified x/y position (upper left corner of the bitmap). Parts of the bitmap may be outside the display boundaries. The bitmap is specified by the array bitmap. A cleared bit means: Do not draw a pixel. A set bit inside the array means: Write pixel with the current color index. For a monochrome display, the color index 0 will usually clear a pixel and the color index 1 will set a pixel.
Arguments:

u8g : Pointer to the u8g structure (C interface only).
x: X-position (left position of the bitmap).
y: Y-position (upper position of the bitmap).
cnt: Number of bytes of the bitmap in horizontal direction. The width of the bitmap is cnt*8.
h: Height of the bitmap.

It would appear your image data is complete gibberish.  This is what I decode it to be:
 ######  #     #  #
 ###   # # ####  #    #
  # ## #  #  #     #
   ## ##   #  #    #
   #      ##     #
 #   #  #  ## #####

        #        ####
#   #   #    #   #   #
  # #   ## ###    # # ##
# #  #  #  # #     # ##
   # # #   # # #  # ###
  ##    ##

so how do I find the width 21/ 8 because that isn't a multiple of 8

You will have a multiple of 8 regardless. The extra bits will be padded with 0 (or they should be if the converter you used is any good). Count the number of bytes in your array, divide it by the number of pixels your image is high, and that is the value to use. If your source image is 21 pixels wide I would put money on the answer being 3.  3x8 = 24, so 21 + three blank pixels for padding.

ok I'm a little confused what number do I put into u8g.drawBitmapP(x,y,?,8); do I put 3 or 24

3 since that is the number of bytes that would make up a row.  3x8 should equal the size of your array.

I don't know why it dosnt work heres what ive done

u8g.drawBitmapP( 55, 5, 3,18, rook_bitmap); the real image is 24*18 now and it still looks really weird on the screen

With those figures here should be 54 entries in your array, but I only count 47.

I resized the image and now it has 54 but still dosnt work

Then maybe the converter doesn't handle images that aren't a multiple of 8 pixels wide properly. Try using an image that is exactly 24 pixels wide.

no that dosnt seem to work do you want me to send u the code and image

Not really, no. I don't have a display. Update your question with your current version of the code so all can see it.

it is done by the way

Your data is gibberish. It doesn't convert into any form of a recognizable image.

I got it to wrok by using a different image to hex converter I will accept ur answer since u helped me and I did learn a bit

That's good. I was beginning to suspect your converter was either bad or configured wrong.


text:
Relays just switch ON and OFF on delay(), not on millis()
I use fuzzy logic for the running time of relays, but the relays just switch ON and OFF at the interval of the delay() I put at the end of loop.
This is my code:
void loop () {
  ph = -180/100.0;
  hasilec = -1.2;
  unsigned long now = millis();

  Serial.print("pH    ");
  Serial.print(ph);
  Serial.print("  ");
  Serial.print("EC ");
  Serial.print(hasilec);
  Serial.println("");
  Serial.print(ph);
  Serial.print(" ");
  Serial.print(hasilec);
  Serial.print(" ");
  Serial.println(" ");

  fuzzy->setInput(2, hasilec);
  fuzzy->setInput(1, ph);
  fuzzy->fuzzify();

  float pompa01 = fuzzy->defuzzify(1); //pHDOWN
  float pompa02 = fuzzy->defuzzify(2); //pHUP
  float pompa03 = fuzzy->defuzzify(3); //ABMIX

  long int pompa1 = pompa01 * 1000;
  long int pompa2 = pompa02 * 1000;
  long int pompa3 = pompa03 * 1000;

  Serial.println("Result= ");
  Serial.println("");
  Serial.print(" Pompa1 pHDOWN: ");
  Serial.println(pompa1);
  Serial.print(" pompa2 phUP  : ");
  Serial.println(pompa2);
  Serial.print(" pompa3 ABMIX : ");
  Serial.println(pompa3);
  Serial.println("");
  Serial.println("");
  Serial.println("");

  pump_periods[0] = pompa1;
  pump_periods[1] = pompa2;
  pump_periods[2] = pompa3;

  for (int i = 0; i < jml_pump; i++) {
    if (now - pump_last_actuations[i] >= pump_periods[i]) {
      pump_states[i] = (pump_states[i] == LOW) ? HIGH : LOW;
      digitalWrite(pump_pins[i], pump_states[i]);
      pump_last_actuations[i] = now;
    }
  }
  delay (20000);
}

The relay just switch ON and OFF on this delay delay (20000);.
What should I do?

Check the values of pompa1, pompa2, and pompa3 to see if they are always smaller than 20000. What is the delay for, anyway? It could well be messing up your timing of the toggling of the pump_states by delaying longer than the values in pompa1, pompa2, and pompa3.

i got it i just replace my delay after fuzzy, its work, let me debugging more for perfection my project thx

I will turn the comment into an answer; please accept it (if you accept it) so the question doesn't stay open.

Check the values of pompa1, pompa2, and pompa3 to see if they are always smaller than 20000 (I suspect they are).
The delay(20000) (why is it there anyway?) could well be messing up your timing of the toggling of the pump_states by always delaying longer than the values in pompa1, pompa2, and pompa3.
This would make the relays toggle every 20 s (on every loop).

i got it thx for it


text:
How to stop the relay after it is getting on and let the sensor get the result
I want to provide a delay in the following iteration reading so that the sensor can read the condition after the pump starts.
void loop() {
  //-------------Fungsi Read sensor-----------
  // sensorAll();

  hasilec = (ppmcensor - inputec);
  ph = (phcensor - inputph);

  //  hasilec = random(-200, 0) / 100.0;
  //  ph = random(-200, 200) / 100.0;

  //  ph = -180/100.0;
  //  hasilec = -1.2;

  unsigned long now = millis();

  Serial.print("pH    ");
  Serial.print(ph);
  Serial.print("  ");
  Serial.print("EC ");
  Serial.print(hasilec);
  Serial.println("");
  Serial.print(ph); Serial.print(" ");
  Serial.print(hasilec); Serial.print(" ");
  Serial.println(" ");

  //  delay (500000);

  fuzzy->setInput(2, hasilec);
  fuzzy->setInput(1, ph);
  fuzzy->fuzzify();

  float pompa01 = fuzzy->defuzzify(1);//pHDOWN
  float pompa02 = fuzzy->defuzzify(2);//pHUP
  float pompa03 = fuzzy->defuzzify(3);//ABMIX

  Serial.println("Result= ");
  Serial.println("");
  Serial.print(" Pompa1 pHDOWN: ");
  Serial.println(pompa01);
  Serial.print(" pompa2 phUP  : ");
  Serial.println(pompa02);
  Serial.print(" pompa3 ABMIX : ");
  Serial.println(pompa03);
  Serial.println("");
  Serial.println("");
  Serial.println("");

  delay (2000);

  long int pompa1 = pompa01 * 1000;
  long int pompa2 = pompa02 * 1000;
  long int pompa3 = pompa03 * 1000;

  pump_periods[0] = pompa1; //PHdown
  pump_periods[1] = pompa2; //PHup
  pump_periods[2] = pompa3; //ABMIX

  for (int i = 0; i < jml_pump; i++) {
    if (now - pump_last_actuations[i] >= pump_periods[i]) {
      pump_states[i] = (pump_states[i] == LOW) ? HIGH : LOW;
      digitalWrite(pump_pins[i], pump_states[i]);
      pump_last_actuations[i] = now;
    }
  }
}

If I put the delay after millis iteration it causes the pump to only turn on based on the delay, not the timer millis. What should I do?

Sorry, I don't understand your question. What exactly keeps looping? The loop() function always loops, that is what is is meant for. Or what do you mean? And what does "not making space for my environment getting stabilize" mean?

why are you using fuzzy logic?

I mean let the wave pump mix all Ph and AB mix, and fet stabilize on set point, because im trying using fuzzy for it

sorry, i have no idea what you said

Please [edit] you question and provide some context. If would help if you translate your variables and texts, too.

You can't put a large delay() anywhere in the loop without messing up the millis() timing you use in your for loop when pump_periods[i] are smaller than your delay. Please explain what needs to wait for what; what sensor reads what condition; what makes the pump start and where in the code that happens.

i want to wait a couple of minute for let the liquid mixed after im adding some pH up or down and AB-mix, the sensor read a ppm and pH and i got the value of them,the pump start base on my fuzzy rules.

If all the pumps have to work for pump_periods[i] time on every loop, and you will have a long delay() anyway, you could replace the for loop with:
for (int i = 0; i < jml_pump; i++) { // For every pump:
  digitalWrite(pump_pins[i], 1);     // Start pump i
  delay(pump_periods[i]);            // Wait for pump_periods[i] ms
  digitalWrite(pump_pins[i], 0);     // Stop pump i
}
delay(120000);                       // Wait 2 minutes until mixed

This will block the loop, but you will have a long delay anyway. The pumps will work sequentially, and not at the same time.
Is that what you want?


text:
Potentiometer motor system is not working
I am setting up a potentiometer system that includes a motor that is supposed to spin with the potentiometer changing the speed of the spin and a button to reverse it. I checked the coding and it is correct, the potentiometer, button, and motor are all functioning, but the system does not run. Can anyone propose any solutions to this issue?
int enablePin = 11;
int in1Pin = 10;
int in2Pin = 9;
int switchPin = 7;
int potPin = 0;

void setup() {
  Serial.begin(9600);
  pinMode(in1Pin, OUTPUT);
  pinMode(in2Pin, OUTPUT);
  pinMode(enablePin, OUTPUT);
  pinMode(switchPin, INPUT_PULLUP);
}

void loop() {
  int speed = analogRead(potPin) / 4;
  Serial.println(speed);
  boolean reverse = digitalRead(switchPin);
  setMotor(speed, reverse);

}
void setMotor(int speed, boolean reverse)
{
  analogWrite(enablePin, speed);
  digitalWrite(in1Pin, ! reverse);
  digitalWrite(in2Pin, reverse);

}

I think the problem is that your "code" is an image. You can't compile an image.

@Majenko if that is an issue, it is no longer an image... :D

It looks, in the first image, like you have edited the picture to wipe out the markings on the L239D. Maybe it's not an L239D and you're trolling us? I can't see anything immediately wrong at first glance...

Or maybe it's just that the JPEG compression is so high it's hard to make out details any more.

BTW you should really connect all the GND pins of the L239D.

@Majenko I have confirmed that the pins follow the diagram correctly and the controller is in fact an L293D.

@Majenko Could you clarify further on the GND pin statement, please? We are both somewhat new to Arduino and are following the diagram supplied to us. Is it wrong?

The L239D has four pins labelled GND. All four of them should be connected to the GND of the Arduino (through the GND rail of the breadboard of course). It shouldn't matter, and it's doubtful that it is causing your problem, but it's good practice.

Measure the voltage on pin D9, D10, and D11. Also, it looks like motor supply uses USB supply. That's bad idea, you can potentially damage the USB port. If you can, use an external supply.

Does it run, whem you introduce a delay(100) into the loop function? When the motor function is called too fast, the PWM signal will restart constantly


text:
Arduino PID controller for Triac
I am designing a new soldering station which will use a 24 V ac soldering iron.
I started to make some research and I designed a few steps of the soldering station. I will use a 24Vac/100VA toroidal transformer. I will use a 24V/50W soldering iron with K type thermocouple. For the thermocouple I will use a LM358 amplifier. Please have a look at the attached schematic and code. The code is not ready yet and I need some help in making the connection between the PID library and output in the code.
The voltage on the soldering iron looks like: https://ibb.co/CMF1gQ0
If I rotate the pot, nothing happens on the screen of the scope.
https://ibb.co/vdDRmnJ
I wrote a few lines of code but I don't know how to make the connection between the PID library functions and the interruption function and the other variables in my code.
Please have a look at the code and at the schematic and tell me what you think...
I am waiting for your help.
#include <PID_v1.h>

int AC_LOAD = 1;    // Output to Opto Triac pin
double set_value = 0;
double input = 0;
double output = 0;

PID aaa_PID(&input, &output, &set_value, 1, 0.05, 0.25, DIRECT);

void setup()
{
  aaa_PID.SetOutputLimits(0, 128);
  aaa_PID.SetMode(AUTOMATIC);
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
  // For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65
  int dimtime = (75*output);    // For 60Hz =>65
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay (for 60Hz use 8.33)
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {
  int set_point = analogRead(A1);
  set_point = map(set_point, 0, 1023, 150, 400);
  int in = analogRead(A0);
  input = map(in, 0, 550, 25, 400);
  set_value = set_point;
  aaa_PID.Compute();

}

Seems legit to me, though you might want to disable the interrupt while executing myPID.Compute(), since you can get garbled data in your interrupt, when it happens while the Output variable gets assigned. What exactly is your problem with the code?

the problem is that I don't know if I correctly wrote the zero_cross_int() function and I don't know where is the relationship between the output of the PID calculations and the output waveform of the Arduino. I meant in the zero_cross_int() function the read value should be the one from the zero crossing detector or the one from the potentiometer ?

It is not clear to me, what you mean. You changed your code again. Now you are reading a second analog input in the interrupt. Why? With your old code the logic was the following: analogread the potentiometer for the setpoint, calculate output of PID, use PID for driving the triac signal. Only missing was the reading of the input for the PID (since you are creating a soldering station, here you would have to measure the temperature) and assigning it to Input. The additional analogRead in the new code is meaningless (you don't use the value anywhere)

I modified the code again: A1 input is for the potentiometer and A0 is for the temperature sensor.

I have tried the code above and I am stuck at the potentiometer. I checked it in particular and it is working. But when I am rotating the knob, then nothing happens. I only see on the oscilloscope this waveforms: https://ibb.co/mBBnmk3

I see several issues here.
The most serious is in the wiring of the Arduino. The first argument of
attachInterrupt() is an interrupt number. On the Uno, “interrupt 0” is
wired to the pin “digital 2”. This is where you should connect the
output of the zero-crossing detector (ZERO_OUT).
Then, as noticed by Juraj, there is the issue of the interrupt handler
taking too long to execute. This is generally considered bad practice,
and it has some negative consequences on the working of the Arduino core
like, e.g., the millis() function will be completely off. I do not
think, however, that this is a serious issue for you. There is one
single time-critical bit in your program, which is the generation of the
triac trigger pulses. You really do not care about millis() or any
other time-related things. Thus, at least for the initial version of the
program, I would not care too much, and just let the interrupt handler
delay as needed.
The third issue has been noted by chrisl in a comment: there is a race
condition with both the main program and the interrupt handler accessing
the same output variable. Race conditions are a nasty kind of bug
because usually things work fine “most of the time” and then fail at
unexpected times. I would not recommend, however, to run
myPID.Compute() with interrupts disabled: that may throw off the
timing of your triac pulses. Instead, compute the delay required by the
interrupt, save it to a temporary variable, then copy it to a variable
shared with the handler. Only the copy needs to be done with interrupts
disabled, and that takes only a handful of CPU cycles:
// Variable used by zero_crosss_int().
// Do not forget the `volatile' qualifier.
volatile int dimtime;

void loop() {
    // PID and associated computations.
    set_value = map(analogRead(A1), 0, 1023, 150, 400);
    input = map(analogRead(A0), 0, 550, 25, 400);
    aaa_PID.Compute();
    int tmp_dim_time = 75*output;

    // Critical section executed with interrupts disabled.
    noInterrupts();
    dimtime = tmp_dim_time;
    interrupts();
}

Edit: If things do not work, you should try to debug piece by piece.
Sending debug messages to the serial port should help, although serial
communication is likely to be significantly slowed down by the
long-running interrupt handler. As an alternative, you can use the triac
control pulses as a debug aid, maybe with the heating element unplugged.
For example:

In loop(), set dimtime to a value proportional to set_value.
Turn the pot and look at the FIRING_PULSE signal. Does the pulse
width vary proportionally to the pot position? Is it in sync with the
Vin zero-crossings?
Set dimtime proportional to input. Heat the thermocouple by some
external means. Does FIRING_PULSE vary as expected?
Set dimtime proportional to output, but keep the heating element
unplugged. How does the pulse change as you move the pot or heat the
thermocouple?

I added the code into my program and I run it, but on the scope screen appears something like this: https://www.youtube.com/watch?v=rAK9ounINAQ , and the heating of the soldering iron does not stop. As the temperature increases, the voltage on the soldering iron heater also increases...

@mike_mike: did you fix the wiring?

Yes, the “interrupt 0” is wired to the pin “digital 2”, as you said.

@mike_mike: Are you sure the PID parameters are sensible for your system? How did you tune them?

The PID parameters are from another soldering station, which used a mosfet instead of a triac.

I need some help in making the connection between the PID library and
  output in the code

PID calculates the value of output and it is used in int dimtime = (75*output);.
The aaa_PID object gets the reference to variable output with & so when the PID algorithm sets the output value it sets the value of this variable in your sketch.
output should be volatile double output = 0; because it is used in interrupt.
EDIT 2:
I hope you wired the zero crossing detector to pin 2, because that is the pin for external interrupt 0. And don't use pin 1 for Triac, it is wired to USB chip too.
EDIT:
Your code stays too long in interrupt. You exit the interrupt only in the time after firing the TRIAC and the next zero crossing.
In this Arduino SE answer I offer two sketches which demonstrate Triac control. This is one of them:
#include <TimerOne.h>

const byte INTERRUPT_PIN = 2;
const byte TRIAC_PIN = 4;
const byte TRIAC_PULSE_MICROS = 30;

const int FADE_MAX = 9800;
const int FADE_MIN = 2000;

volatile bool triacOn;
volatile int period = FADE_MIN; // microseconds cut out from AC pulse

int fadeAmount = 10;

void zeroCrossing() {
  triacOn = false; // triac tuns off self at zero crossing
  Timer1.setPeriod(period); // to call triacPulse() after off period
}

void triacPulse() {
  if (triacOn) { // stop pulse
    digitalWrite(TRIAC_PIN, LOW);
    Timer1.stop();
  } else { // start pulse
    digitalWrite(TRIAC_PIN, HIGH);
    triacOn = true;
    Timer1.setPeriod(TRIAC_PULSE_MICROS);
  }
}

void setup() {
  pinMode(TRIAC_PIN, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), zeroCrossing, RISING);
  Timer1.initialize();
  Timer1.attachInterrupt(triacPulse);
}

void loop() {
  period = period + fadeAmount;
  if (period <= FADE_MIN || period >= FADE_MAX) {
    fadeAmount = -fadeAmount;
  }
  delay(25);
}

the other uses direct registers access o AVR.
EDIT 3: mike's oscilloscope output of the sketch above: https://www.youtube.com/watch?v=dnfy_EsPlVI
EDIT 4: the PID outputs high values for high power and small values for lower power. but the Triac period is the off time. so the period should be something like period = 11000 - (75 * output)
here are the input and output values of mike's code based on this answer (blue is temperature, red is output for the Triac period):

The PID control gets smoother over time as it finetunes its parameters,
but I think a simple PID has some problems with the sine relation between the output (time) and the resulting heating power.

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


text:
SIM7000E Waveshare can't do anything
Can someone help me? I'm using a sim7000e from Waveshare. One week ago it was working normally, but now it doesn't work at all; it even can't read the RX-TX communication.
#include <SoftwareSerial.h> //koneksi ke modem

#define TINY_GSM_MODEM_SIM7000
#define TINY_GSM_DEBUG SerialMon
#define BAUD 9600
#define SerialMon Serial

const byte rxpin = 2;
const byte txpin = 3;

SoftwareSerial SerialAT(rxpin, txpin); // RX, TX

That's  my code for connecting to the Arduino. I believe it from my Arduino, but I don't know if something wrong from Arduino.
My 5V (sim7000E) to 5V (arduino mega2560), GND to GND.
Because I'm using Putty on USB for reading my AT-cmd it doesn't and has some trouble.

Your rxpin on Arduino Mega2560 connect to which pin on SIM7000E?

Rx2=TX sim
Tx3=RX sim

I'm having similar issues, although it could well be my fault!
I can't see any coding sending AT commands, or waiting for responses in your example.
Try running your TX pin to your RX pin on your Arduino (take the SIM7000e out of the equation completely).  If your code works, then the issue is elsewhere.
I've tried connecting via USB and that seems through a terminal.  I was able to connect to a mobile network using the AT command
AT+CSTT="cmnet"

Just to add further context, the Raspberry PI header pins use a lower TTL voltage.   Connecting to the other headers at the end of the board will give you compatible UART levels.
Why your board has stopped working suddenly is a bit of a mystery, without proper context of pinouts,connectivity, power, etc.


text:
4004 (NOT_FOUND) ON MQTT
I tried to send random data to MQTT but it's not working and I get:

{
   "m2m:rsp" : {
      "rsc" : 4004,
      "rqi" : "123456",
      "pc" : "Resource not found",
      "to" : "5a185cedc6ad749b:edb0b82be780ba6d",
      "fr" : "/antares-cse"
   }
}

This is from mqtt.fx
This is my payload what should I do
    #include <SoftwareSerial.h> //koneksi ke modem

    #define TINY_GSM_MODEM_SIM7000
    #define TINY_GSM_DEBUG SerialMon
    #define BAUD 9600
    #define SerialMon Serial

    SoftwareSerial SerialAT(10, 8); // RX, TX ke modem

    const char apn[]  = "nb1internet"; //untuk gprs gunakan "internet"
    const char user[] = "";
    const char pass[] = "";
    byte randomValue = random(0, 37);
    const char *mqtt_server = "mqtt.antares.id"; //server antares
    const char *mqtt_user = "";
    const char *mqtt_pass = "";
    const int mqtt_port = 1883;
    const char *mqtt_client_name = "KEKW" + randomValue; // random

    //dibawah ini sesuaikan dengan akun atares kamu
    #define TOPIKPUB "/oneM2M/req/5a185cedc6ad749b:edb0b82be780ba6d/antares-cse/json"
    #define accessKey "5a185cedc6ad749b:edb0b82be780ba6d"
    #define projDev "ECSENSOR/pHnEC"

    // library modem dan mqtt
    #include <TinyGsmClient.h>
    #include <PubSubClient.h>

    #ifdef DUMP_AT_COMMANDS
      #include <StreamDebugger.h>
      StreamDebugger debugger(SerialAT, SerialMon);
      TinyGsm modem(debugger);
    #else

    TinyGsm modem(SerialAT);
    #endif
    TinyGsmClient client(modem);
    PubSubClient mqtt(client);

    long lastReconnectAttempt = 0;
    int val;

    void setup()
    {
      // Set debug console dan modem
      SerialMon.begin(9600);
      delay(10);
      SerialAT.begin(9600);
      delay(3000);

      String modemInfo = modem.getModemInfo();
      SerialMon.print("Modem: ");
      SerialMon.println(modemInfo);

      SerialMon.print("Waiting for network...");
      if (!modem.waitForNetwork(240000L)) {
        SerialMon.println(" fail");
        delay(10000);
        return;
      }
      SerialMon.println(" OK");

      if (modem.isNetworkConnected()) {
        SerialMon.println("Network connected");
      }

      SerialMon.print(F("Connecting to "));
      SerialMon.print(apn);
        if (!modem.gprsConnect(apn, user, pass)) {
        SerialMon.println(" fail");
          delay(10000);
          return;
      }

        SerialMon.println(" OK");

       // MQTT Broker setup
      mqtt.setBufferSize(512);
      mqtt.setServer(mqtt_server, mqtt_port);
    }

    boolean mqttConnect() {
      SerialMon.print("Connecting to ");
      SerialMon.print(mqtt_server);

      // koneksi ke MQTT Broker
      boolean status = mqtt.connect(mqtt_client_name,mqtt_user, mqtt_pass);

      if (status == false) {
        SerialMon.println(" fail");
        return false;
      }
      SerialMon.println(" OK");

      return mqtt.connected();
    }

    void loop()
    {

      //cek jika koneksi mqtt gagal maka ulang lagi
       if (!mqtt.connected()) {
        SerialMon.println("=== MQTT NOT CONNECTED ===");
        // Reconnect every 10 seconds
        unsigned long t = millis();
        if (t - lastReconnectAttempt > 10000L) {
          lastReconnectAttempt = t;
          if (mqttConnect()) {
            lastReconnectAttempt = 0;
          }
        }
        delay(100);
        return;
      }

      int val = random(0-450);  //TEST RANDOM DATA

      String pubString ;
     //JSON yang panjang untuk kirim data ADC ke antares
        pubString +=  F("{");
        pubString += F("\"m2m:rqp\": {");
        pubString += F("\"fr\": \"");
        pubString += String(accessKey) ;
        pubString += F("\",");
        pubString += F("\"to\": \"/antares-cse/antares-id/");
        pubString += String(projDev);
        pubString += F("\",");
        pubString += F("\"op\": 1,");
        pubString += F("\"rqi\": 123456,");
        pubString += F("\"pc\": {");
        pubString += F("\"m2m:cin\": {");
        pubString += F("\"cnf\": \"message\",");
        pubString += F("\"con\": \"{\\\"level\\\":");
        pubString += String(val);
        pubString += F("}\"");
        pubString += F("}");
        pubString += F("},");
        pubString += F("\"ty\": 4");
        pubString += F("}");
        pubString += F("}");

      // kirim atau publish ke antares
      SerialMon.println(pubString);
      char message_buff[pubString.length() + 1];
      pubString.toCharArray(message_buff, pubString.length() + 1);
      mqtt.publish(TOPIKPUB, message_buff);

    delay(5000);
    }

what you should do is to include the whole sketch


text:
I can't find what I did wrong
int lightPin = 13;
int buttonPin = 2

void setup() {
  pinMode(lightPin, OUTPUT); //red
  pinMode(buttonPin, INPUT);
}

void loop() {
  int buttonValue = digitalRead(buttonPin);

  if (buttonValue == HIGH) {
    digitalWrite(13, HIGH);
  }  //red

  digitalWrite(13, LOW);//red
}  //red

Are you getting some sort of error message?  Please provide more information.  Also, please edit your question and use the formatting tools to format the code as code.

why do you think that you did something wrong?

What is going wrong? Only thing I can see is that your LED will only light for a very brief period when you press the button because you immediately turn it off. That is addressed in @rjuzzle’s answer. Or maybe something else is wrong. You have not given any details so we can only guess.

See rjuzzle's answer. Your code will only set the LED pin to high for less than a millisecond on each pass through your loop when the button is pressed - the flickering will be so short that you probably won't be able to see it.

Your question needs work. See how to ask.

In this example your missing a semi-colin after int buttonPin = 2, and your if statement should probably look like this
if (buttonValue == HIGH){
  digitalWrite(lightpin, HIGH);
}//red

else{
  digitalWrite(lightpin, LOW);//red
}//red/*

Also if you go into the examples in the Arduino IDE, under "digital", this sketch is called button.

Assuming the problem is that the LED doesn't appear to light at all, the answer is moving the code that turns the LED off to the else clause as you have shown in your answer. Otherwise the LED will only be lit for less than a millisecond - probably such a short time that it wouldn't be visible to the human eye.


text:
FreeRTOS library (AVR_ATmega328PB_Xplained_mini_GCC) versus FreeRTOS for Arduino boards
I am researching different IoT development boards and found that Espressif uses the IDF framework. When I looked at the source code it uses FreeRTOS libraries.
I have an Arduino Uno and I want to use FreeRTOS for programming it. I found that FreeRTOS has multiple libraries that support different microcontrollers. Arduino Uno has an ATmega328P and FreeRTOS has libraries for it.
I also found libraries for the Arduino family of boards.
What is the difference between these two libraries?

One is a demo, the other is a library. One is not for Arduino but for "bare metal" programming, the other is for Arduino. They're both FreeRTOS.

Thank you Majenko for the clarification

ATmega328PB is not the same MCU as used by Arduino boards. Those use ATmega328P (no B). ATmega328PB is a mostly compatible successor and offers more timers, built-in touch functionality and more but does not come in large DIP packages. Arduino uses the older ATmega328P.


text:
Why is it I need transistors and resistors to turn a DC motor with an Arduino but I can connect it directly to a battery?
As the question says: I'm building a circuit to run a DC motor whenever motion is detected by a motion sensor. Now as this image suggests:

I need a diode + resistor + transistor to get this thing to turn with an Arduino, but I can do the same with a battery and connecting each of the terminals to the + and - of the battery. I understand this might be for speed control? Or turning the motor different ways?
But if I just need it to spin at 100%, would all this be needed?
I tried hooking up the motor directly with a resistor to the 5 V + GND of the board while it was on, but no joy. I am (obviously) doing something wrong but I want to use this problem as a way to learn circuits better.

For the resistor: https://electronics.stackexchange.com/questions/122312/why-is-a-resistor-put-before-the-gate-of-a-transistor ; the diode is a flyback diode, also for protection

Please draw a "real" schematic of this circuit, and do some research on the matter. Keywords are "voltage", "current", "inductive load", and/or "drive DC motor from microcontroller". Look up the documentations of motor and AVR, and compare needed current and provided current.

because the io pin is not a power supply. it can provide only limited current. it is for TTL logic state

One word: impedance.

Too get the maximum out your motor should use a MOSFET, you will eliminate t.7 or 1.4 volt collector emitter voltage drop.  If the MOSFET is logic level and avanchlated you do not need the diode. Although probably not necessary I would put a 50 ohm resistor in the gate circuit. As previously mentioned use a seperate power supply for the motor, the Arduino is not a power supply.

If you want the motor to rotate continuously, without using PWM, and without switching the motor on and off from the Arduino, you can connect the motor straight to 5 V and ground. If you then add a large resistor like you tried, not enough current will pass through the motor to rotate it; in the image the resistor is there to limit the current into the transistor, not to limit the current into the motor.
You can't connect a motor directly to an IO pin because an IO pin can only deliver about 20 mA, which isn't enough for a motor. So, if you want to control a motor from an IO pin, you need a transistor as a switch and you operate that transistor from the IO pin. The transistor does the heavy lifting and switches the larger current the motor needs. The resistor is there to limit the current into the transistor.
Note that it is generally better to wire a motor directly to a 5 V power source and not to the 5 V pin on the Arduino, as the current you can get from that pin is limited; it will do for small motors, though, if they don't pull more than, let's be safe, about 300 mA. In other words, it is preferred not to use the Arduino 5 V pin as a power source, but to use a 5 V power source directly.
Also note that you always need the diode across the motor, however you wire it. It keeps inductive spikes away from the rest of your circuit.


text:
How do I know when a filter coffee machine is finished by using any sensor?
I have a filter coffee machine that looks like this one and I would like to send a message to the machine users by using any development board (like Arduino or NodeMcu) when the machine is finished.
I haven't found a way to detect when the machine is finished. (I also don't want to do any physical change on the machine, like adding any cable or opening in the machine. I can use any sensor or so on.)
How can I do that? Any advice?

Maybe a capacitive level sensor at the side of the pot? That might work. Or maybe a reflective light sensor on the pot (LED plus phototransistor, which senses the change in reflected light, when the coffee reaches a specific level)

measure the power consumption

Ultrasonic: measure the height of the water. Will be hard to fix inside the machine and probably hard to get a water proof version.

Easiest and cheapest: measure the maximum time it takes to make coffee and then use a timer. The coffee will be kept warm anyways, so just come back after x minutes.

weight sensor under the cup? are there some LEDs to indicate status?

(Just a note...) This was done many, many years ago: Trojan Room coffee pot -- However, a camera might be a bit exaggerated.

The normal method is by temperature. When you heat the water you can never get above 100C as the water boiling takes the extra energy away in the phase change to steam. But once all the water has been removed from the heating tank the heater can get higher that 100C. So when that happens the heater shuts off as it's got no more water to heat up.  Basic physics.  So monitor the temperature of the heater then allow a certain amount of extra time for the last bit to filter (determined by experimentation).

Just two ideas, both non-invasive:
The machine moves water from the reservoir at the back to the coffeepot at the front of the machine, so its weight distribution will change while making coffee.
If you put a thin pressure pad (like this one, or something similar) under the whole machine at the back you should see the pressure at that point become smaller while coffee is being made.
If the effect isn't pronounced enough, you could make the whole machine tilt forward while making coffee by putting a narrow and thin strip of plastic under its centre from left to right so it can swivel forward and back just a little depending on the location of the bulk of the water.
If the pressure on the pressure pad at the back stops dropping, the coffee is ready. You can also detect when the coffee can is empty again this way, or maybe even how many cups of coffee are still available in the coffee can.
Or maybe you could detect with a contact microphone when the machine goes silent, assuming it makes sufficient noise when making coffee. Mine does.

I'd use two load cells instead of those pressure pads. But other than that, this is a nice solution.

Added benefit it that it can notify you when there is less that a cup of coffee left in the pot, and thuse requiring a refill.

Even easier would be to only measure the entire weight of the machine. A sudden increase of weight, indicates it's just filled up. Start a timer for, say, 2 minutes, plus 1 minute for every 100ml (i.e. 100gr). You'd have to do some test runs to measure the amount of time needed for different amounts of water. (You could even make it help you measuring out the right amount of ground coffee.)

If the machine has a Brewing- or a Done Brewing LED, a light sensor can detect this without no changes or connections to the machine. This would also have the advantage of working for a short or full pot.


text:
Displayng 2 error messages on a 16x02 display
I am trying to display on a 16x02 LCD display 2 error codes. The error message is when one or both thermocouple wires get disconnected and the second error message is when the soldering iron temp goes higher than 432 C. I am using MAX6675 module.
The problem is that when I disconnect one thermocouple wire (the + or the -) sometimes the displayed message is "Overheating !!!" instead of "No tc conn !!!".
Is there any way to display the correct error ?
heaterTemp = thermocouple.readCelsius();
  Input = heaterTemp - 100;
   //No TC connection
  if (isnan(Input)) // No TC Connection
  {
    while (true) {
      digitalWrite(relay_pin, LOW);
      digitalWrite(11, LOW);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("NO TC CONN !!!");
      delay(1000);
    }
  }

  //Soldering Iron overtemperature
  if (Input >= 432)
  {
    while (true) {
      digitalWrite(relay_pin, LOW);
      digitalWrite(11, LOW);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("OVERHEATING !!!");
      delay(1000);
    }
  }

Edit: I finally decided to use the same message for both errors - no TC connection and overheating. I used the code below:
heaterTemp = thermocouple.readCelsius();
  Input = 0.779828 * heaterTemp - 10.3427;
  if (isnan(heaterTemp) or Input >= 432) // No TC Connection OR over-temperature
  {
    while (true) {
      digitalWrite(relay_pin, LOW);
      digitalWrite(11, LOW);
      for (int i=0; i<=1; i++){
      lcd.clear();
      lcd.setCursor(0, i);
      lcd.write((byte)0);
      lcd.setCursor(1, i);
      lcd.write((byte)0);
      lcd.setCursor(5, i);
      lcd.print("ERROR!");
      lcd.setCursor(14, i);
      lcd.write((byte)0);
      lcd.setCursor(15, i);
      lcd.write((byte)0);
      delay(1000);
      }
    }
  }

and
byte thermometer[8] = //icon for termometer
{
  B00100,
  B01010,
  B01010,
  B01110,
  B01110,
  B11111,
  B11111,
  B01110
};

The code displays the thermometer symbol at the beginning and at the end of the row and the text (including the symbols) are moving from one to another row.
Now it is sufficiently to display a error message when the thermocouple gets disconnected or when the iron temperature goes above 432 *C.
I have also left the 2 while(true) loops because I need the program to stay in the loop and display the error message until I turn off the power and start again the soldering station.

What is the type of Input? an int? float? unsigned?

The type of Input is a double

You should get rid of the while(true) loops, because when you enter one of them, you'll never get out.
void loop()
{
    heaterTemp = thermocouple.readCelsius();
    Input = heaterTemp - 100;

    //No TC connection
    if (isnan(Input)) // No TC Connection
    {
        digitalWrite(relay_pin, LOW);
        digitalWrite(11, LOW);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("NO TC CONN !!!");
    }

    //Soldering Iron overtemperature
    if (Input >= 432)
    {
        digitalWrite(relay_pin, LOW);
        digitalWrite(11, LOW);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("OVERHEATING !!!");
    }

    delay(1000);
}

EDIT: code below is needed to cut of the power

Don't know the purpose of
digitalWrite(relay_pin, LOW);
digitalWrite(11, LOW);

Maybe it's better to move these lines to setup()

The relay_pin is the relay that cuts down the power to the soldering iron's heater, and the pin 11 is the PWM output pin, which controls the power mosfet. Making them "low" will turn off the power mosfet and the relay will cut the power to the iron's heater.

I thought that I need the 2 while(true) loops to stop the loop() until I turn off the power and turn it again on

@mike_mike, you are correct in your thinking

I think before the disconnection is detected, it goes into overheating (maybe just for some milliseconds).
However, because there is a while (true) loop within the overheating part, it will never show the NO TC CONN error.
If you consider the NO TC CONN error to be higher than the OVERHEATING error, than check within the while loop of the OVERHEATING error also for the NO TC CONN error and display NO TC CONN when it is detected.

According to MAX6675 datasheet page 5, it will set Bit 2 of SPI register to HIGH when the thermocouple is open. Adafruit's MAX6675 library however changed this to return a NAN when Bit 2 is set when you call the readCelsius() method of the library, so what you should do is to check is isnan(heaterTemp) instead of innan(Input).
heaterTemp = thermocouple.readCelsius();
if (isnan(heaterTemp)) // No TC Connection
{
    while (true) {
      digitalWrite(relay_pin, LOW);
      digitalWrite(11, LOW);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("NO TC CONN !!!");
      delay(1000);
    }
}
else
{
  Input = heaterTemp - 100;
  //Soldering Iron over-temperature
  if (Input >= 432)
  {
    while (true) {
      digitalWrite(relay_pin, LOW);
      digitalWrite(11, LOW);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("OVERHEATING !!!");
      delay(1000);
    }
  }
}

I'd reserve line #1 for one message, line #2 for the other
  heaterTemp = thermocouple.readCelsius();
  Input = heaterTemp - 100;
  lcd.clear();
  //No TC connection
  if (isnan(Input)) // No TC Connection
  {
    while (true) {
      digitalWrite(relay_pin, LOW);
      digitalWrite(11, LOW);
      // lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("NO TC CONN !!!");
      delay(1000);
    }
  }

  //Soldering Iron overtemperature
  if (Input >= 432)
  {
    while (true) {
      digitalWrite(relay_pin, LOW);
      digitalWrite(11, LOW);
      // lcd.clear();
      // lcd.setCursor(0, 0);
      lcd.setCursor(1, 0);
      lcd.print("OVERHEATING !!!");
      delay(1000);
    }
  }


text:
Arduino "Phantom Powering"
I am using an Arduino Uno in my project. I recently found that if I disconnect the power from my Arduino (I am powering it by USB port, from a 5V regulator - 7805), then it remains under power from the input pins. I also found that if I disconnect the 3 digit 7 segment common anode display (which is also powered from same 7805) and if I remove the LM358 (which is again powered from the same 7805) from the socket, then my Arduino is not powered anymore.
My questions are:

Is my setup correct - if I am powering it from the 5V regulator (7805) through the USB port ?
My Arduino and the other components from the schematic - the display, the LM358, the mosfet - will be powered on at the same time, when the 230V switch that is placed on the mains input of the 24V SMPS is closed. Could this be a problem in terms of "phantom powering" ? Is there any better way to power the Arduino when I have 5V regulated supply on the schematic ? I will always keep connected the Arduino to the 5V output of the 7805 to the USB port.

Please find attached 2 schematics, one is the main PCB (the one with Arduino) and the other schematic is the one with the display, which is placed on the front panel. The J2 connector from first schematic is connected pin to pin to the J2 from second schematic.
https://ibb.co/QnLHsM0
https://ibb.co/KxLFKsQ

Is my setup correct - if I am powering it from the 5V regulator (7805) through the USB port ?

Yes.

My Arduino and the other components from the schematic - the display, the LM358, the mosfet - will be powered on at the same time, when the 230V switch that is placed on the mains input of the 24V SMPS is closed. Could this be a problem in terms of "phantom powering" ? Is there any better way to power the Arduino when I have 5V regulated supply on the schematic ? I will always keep connected the Arduino to the 5V output of the 7805 to the USB port.

Not really.
Your problem only occurs when you "break" the system by separating the 5V from the Arduino - at which point current flows from the output of the op-amp and through the LED displays, through the IO pins, up through the clamping diodes inside the IO pins, and to the Arduino's 5V.
Since it only happens if you disconnect the 5V and you don't intend to disconnect the 5V then it's not a problem. However if you wanted to improve it then you could take the output of the 5V reguator and feed that direct into the Arduino's USB port. You could then power all the other devices that run at 5V from the Arduino's 5V pin.  That way if you remove the 5V from the Arduino then you also remove it from all the other 5V devices that potentially feed power back in.

When you disconnect the arduino from 5V you must also remove either

disconnect any other device that is connected to the arduino and has its own power supply
or disconnect every device that is connected to the arduino from its power supply

When you disconnect 5V from the arduino while devices connected to a gpio are still powered, this gpio might see a voltage larger than zero. But the voltage at any pin must not exceed the arduino's actual supply voltage by more than 0.3V. Otherwise the atmega's supply rail will be pulled high through esd protection diodes and the atmega will try to operate. It will then probably draw more current than what the esd diodes are rated for and they will eventually fail (destroying that gpio).


text:
MQTT connection not being recognised in void loop()
I am trying to publish MPU 9250 readings in the Adafruit IO sending the data from ESP32. The WiFi connection is being established, but the code is not going inside the if(mqtt.connected()) inside the void loop() whereas it's going inside the same command inside the void setup().
I am sure there are no connection issues because once I change if(mqtt.connected()) to while(mqtt.connected()) inside setup(), code is going inside the while loop continuously.
Why is the code not going inside the if command and how can this be solved?
#include <WiFi.h >
#include <Adafruit_MQTT_Client.h>
#include <MPU9250.h>

#define wifi "********"
#define password "********"
#define server "io.adafruit.com"
#define port 1883
#define username "*******"
#define key "********"

WiFiClient esp;
MPU9250 IMU(Wire,0x68);
Adafruit_MQTT_Client mqtt(&esp, server, port, username, key);
Adafruit_MQTT_Publish feed = Adafruit_MQTT_Publish(&mqtt, username"feeds/accelerodata");

void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println("Adafruit MQTT Demo");
  Serial.println("Connecting to");
  Serial.println(wifi);
  WiFi.begin(wifi,password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting...");
  }
  Serial.println("Connected");
  Serial.println("IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Connecting to MQTT");

  if (mqtt.connect()) {
    Serial.println("MQTT Connected");
  }
}

void loop () {
  Serial.println("Test line to check if code reaches inside loop");
  delay(1000);

  if (mqtt.connected()) {
    int data=IMU.getAccelX_mss();
    Serial.println("\nSending accelero data");
    Serial.println(data);
    Serial.println("....");
    if (feed.publish(data)) {
      Serial.println("Success");
    } else {
      Serial.println("Fail");
    }
    delay(800);
  }
}

I believe there should be a / betweeen the username and the "feeds/..." portion in your feed definition. I.e.: Adafruit_MQTT_Publish feed=Adafruit_MQTT_Publish(&mqtt,username"/feeds/accelerodata");

I think it should not matter as long as they are inside "   ". Anyways I tried changing that too...

It does matter because username and the quoted string form a (longer) single string. Adafruit IO uses the first part of the string (up to the first / ) to identify the individual users using their service. The part after the first / is used to find the feed you (as an Adafruit IO user) have defined yourself. Look at the examples provided with the Adafruit IO library. They all use the /.

I believe your problem is that you are attempting to use the MQTT connection before it's actually connected.  So your check:
if(mqtt.connected())

is always FALSE since it's not really connected.  The Adafruit library information here:
Adafruit MQTT
Says to initialize MQTT as:
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

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

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

  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
  }
  Serial.println("MQTT Connected!");
}

Thanks for the link.. But the connection is not being established. The above function outputs "connection failed". What could be the possible issues? How to troubleshoot the problem

Did you use the correct username and key? Try some of the example code from the Adafruit IO library.

If you have a free Adafruit IO account, also take care not to exceed the maximum data rate (30 data points per minute).

The key is correct.. In-fact the collection frequency was higher initially(higher than 30 points per minute) which I reduced. No improvement in the state though.


text:
How to connect two devices via i2c?
I am working with 2 Pololu Altimu-10 V6 connected to the same ESP32 board. Both of them are connected via i2c protocol and have different addresses. The addresses are 0x1C and 0x1E.
I have this code to calibrate the magnetometer of one. How can I change it to measure both of them?
I don't know how to specify the address of each one.
#include <Wire.h>
#include <LIS3MDL.h>

LIS3MDL mag;
LIS3MDL::vector<int16_t> running_min = {32767, 32767, 32767}, running_max = {-32768, -32768, -32768};

char report[80];

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

  if (!mag.init()) {
    Serial.println("Failed to detect and initialize magnetometer!");
    while (1);
  }

  mag.enableDefault();
}

void loop() {
  mag.read();

  running_min.x = min(running_min.x, mag.m.x);
  running_min.y = min(running_min.y, mag.m.y);
  running_min.z = min(running_min.z, mag.m.z);

  running_max.x = max(running_max.x, mag.m.x);
  running_max.y = max(running_max.y, mag.m.y);
  running_max.z = max(running_max.z, mag.m.z);

  snprintf(report, sizeof(report), "min: {%+6d, %+6d, %+6d}   max: {%+6d, %+6d, %+6d}",
    running_min.x, running_min.y, running_min.z,
    running_max.x, running_max.y, running_max.z);
  Serial.println(report);

  delay(100);
}

I guess you are using this library from pololu. In the Readme file under "Library reference" you can find the following entry:

`bool init(deviceType device, sa0State sa0)
Initializes the library with the device being used (device_LIS3MDL or device_auto) and the state of the SA1 pin (sa1_low, sa1_high, or sa1_auto), which determines the second-least significant bit of the I²C slave address. Constants for these arguments are defined in LIS3MDL.h. Both of these arguments are optional; if they are not specified, the library will try to automatically detect the device address. A boolean is returned indicating whether the type of device was successfully determined (if necessary).

I'm interpreting this as the following: You can create 2 LIS3MDL objects like this:
LIS3MDL mag1;
LIS3MDL mag2;

Then in setup() you init both of them, but providing the optional parameters of the init function:
if(!mag1.init(LIS3MDL::device_LIS3MDL, LIS3MDL::sa1_low)){
  Serial.println("Failed to detect and initialize magnetometer 1!");
  while (1);
}
if(!mag2.init(LIS3MDL::device_LIS3MDL, LIS3MDL::sa1_high)){
  Serial.println("Failed to detect and initialize magnetometer 2!");
  while (1);
}

The first parameter is the device type. It would probably also work with the value LIS3MDL::device_auto, though just setting it makes it more explicit. The second parameter represents the state of the address pin (SA1) on the corresponding module. In the above code the module, whose SA1 pin is at LOW, will be mag1; the one with SA1 pin HIGH will be mag2. Note, that you of course need to actually connect the SA1 pins of the modules to ground/Vcc respectively for this to work.
Then everything, that you previously did with only one LIS3MDL object, you can do with each of these two LIS3MDL objects consecutively.

I tried but I got this error: 'device_LIS3MDL' was not declared in this scope.

@hcheung If I use mag1.init(0x1C) I have this error: error: invalid conversion from 'int' to 'LIS3MDL::deviceType'. Also I tried in binary (as in the documentation) mag1.init(0b0011110)  and the error was the same.

@sonlas10 Sorry, had not seen, how exactly that is defined. It is actually an enum inside of the class. The documentation does not mention this. I could compile when adding LIS3MDL:: in front of the names device_LIS3MDL and sa1_high/sa1_low. That tells the compiler, that this is a member of the class LIS3MDL

@sonlas10, my apology, i re-read the source code in more detail, I was wrong. Maybe you should consider to raise an issue at the library GitHub.


text:
How do I control the onboard LEDs of my Arduino Nano 33 BLE Sense?
I picked up my Arduino Nano 33 BLE Sense for the first time in a while and ran the classic "Blink" sketch to make sure it was alright. After slight usage, I wanted to play with the onboard LEDs. When I run the following code, the onboard LED does not turn on:
#define RED 22

void setup() {
    pinMode(RED, OUTPUT);
}

void loop() {
    digitalWrite(RED, HIGH);
}

However, when I run the following code, the onboard LED does turn on and stays on - it doesn't blink:
#define RED 22

void setup() {
    pinMode(RED, OUTPUT);
}

void loop() {
    digitalWrite(RED, LOW);
    delay(1000);
    digitalWrite(RED, HIGH);
}

What's happening? Is my Nano busted?

The LED is probably active-LOW, that is,it will only light when you send a LOW signal to the appropriate LED pin. The fact that it doesn't blink in the second sketch is because you turn the LED on (LOW), wait one second, turn it off again (HIGH) but it will immediately (within a few microseconds) turn on again in the next loop() iteration. If you want it to stay on for longer, you should place a delay() after it's turned off (digitalWrite(RED,HIGH);).

There are 3 LEDS on the Nano 33 BLE:

A power LED on pin 25 (yes, you can turn off the power LED programmatically);
A built-in LED on pin 13;
An RGB LED with red on pin 22, green on pin 23, and blue on pin 24.

In the variant file, they are given names:
#define PIN_LED     (13u)
#define LED_BUILTIN PIN_LED
#define LEDR        (22u)
#define LEDG        (23u)
#define LEDB        (24u)
#define LED_PWR     (25u)

The power LED and the built-in LED are active-high, i.e. you need to set their pin to HIGH to turn these LEDs on. The three LEDs in the RGB LED, however, are active-low.
This isn't well-documented as far as I know, and some example code snippets have it wrong too. A quick look at the schematic helps.
Also, as StarCat mentioned, you need two delay()s to make an LED blink.


text:
Weird behavior when 2 functions are trying(?) to run at the same time
So I just finished my weak project which is a remote controlled car.
My problem is that when I press the button for going reverse (as an example) while the opposite action is currently in progress, going forwards the built_in led flashes in the exact same pattern when the Arduino is restarted (you know, pressing the reset button) and the car just stops and becomes responsive again after the led stops doing it's thing.
I believe the problem might be with the functions that I made, those being Forward(), Reverse(), Left(), Right(), Stop();
Note that if i press 5 (which translates to Stop() in this case) it is behaving as expected.
Here's the code: (functions at the bottom)
#include <IRremote.h>

const int RECV_PIN = 7;
IRrecv irrecv(RECV_PIN);
decode_results results;

int IN1 = 12;
int IN2 = 11;
int IN3 = 10;
int IN4 = 9;

void setup()
{
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);

  Serial.begin(9600);

  irrecv.enableIRIn();
  irrecv.blink13(true);
}

void loop()
{
  if (irrecv.decode(&results)){
        Serial.println(results.value, HEX);
        switch(results.value){

          case 0xFF18E7: // in fata  - 2
          Forward();
          break;

          case 0xFF4AB5: // in spate - 8
          Reverse();
          break;

          case 0xFF10EF: //   stanga - 4
          Left();
          break;

          case 0xFF5AA5: //  dreapta - 6
          Right();
          break;

          case 0xFF38C7: //   stop  - 5
          Stop();
          break;

        }
        irrecv.resume();
  }
}

void Forward()
{
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  Serial.print("Motor 1 Forward");
  Serial.println();

  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("Motor 2 Forward");
  Serial.println();
}

void Reverse()
{
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  Serial.print("Motor 1 Reverse");
  Serial.println();

  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Motor 2 Reverse");
  Serial.println();
}

void Left()
{
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  Serial.print("Motor 1 Reverse");
  Serial.println();

  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Motor 2 Forward");
  Serial.println();
}

void Right()
{
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  Serial.print("Motor 1 Forward");
  Serial.println();

  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("Motor 2 Reverse");
  Serial.println();
}

void Stop()
{
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, LOW);
    Serial.print("Motor 1 Stop");
    Serial.println();

    digitalWrite(IN3, LOW);
    digitalWrite(IN4, LOW);
    Serial.println("Motor 2 Stop");
    Serial.println();

}

How are you powering the setup?

lol ... did you mean week project, as in seven day project, instead of weak project as in wimpy project?

the power supply may be getting shorted for the time needed to run this command Serial.print();   .... make sure that IN1 and IN2 actually control one motor


text:
Parsing Data from local websever
i´m trying to build a little monitor of an ESP8266 and an OLED display that displayes the Status of a Robotarm.
The robotarm is controled by a RAMPSboard that has a webserver, so i can check the status from a browser.
For that i´m trying to use the BasicHttpClient Sketch from Arduino to read the status and progress.
The problem is i.... don´t know how?
I guess i know where the data is in my HTML document, but i dont know how to call it via GET request.
With the modified BasicHttpClient Sketch i can read the whole html site and print it out on serial, but after weeks of reading and watching tutorials i´m still stucked.
Long story short.
i want to read "just" the status and progress off of that webserver, with a GET request
this is the part of HTML code where my data is...i guess:
here are 3 different times of the informations i´d like to "extract" and displayed on my little ESP8266 monitor
Idle
Working
Done

0% Complete
   //äusseresHTML

1% Complete

22% Complete

and i just need to change that part of the sketch as it now prints out everything of the page:
void loop() {...

     ... Serial.print("[HTTP] GET...\n");
      // start connection and send HTTP header
      int httpCode = http.GET();

      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
----->          String payload = http.getString();   <---as i understand here i ask for everything
          Serial.println(payload);
        }
      } else {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

      http.end();
    } else {
      Serial.printf("[HTTP} Unable to connect\n");
    }
  }

Hopefully someone has the time to take a look at that and point me to String i need to call.
BTW, i think the main problem why i couldn´t find the answer myself is my english isnt that professional for that kind of stuff, so im doin hard to understand similar tutorials

how is the progress bar updated?  ... are you able to see the update if you use a web browser on a PC?

you cannot get just a part of a web page by using the GET call ... pethaps you could use an XMLHttpRequest ... google http xhr ... as it stands, your question is not really related to the arduino at all

Good morning(from Germany), thank you for your fast answer.   i looked for http xhr and edited my question, i think i clarified my question a little more.as far as i understand this http xhr is for a Server to send status to a client, am i right?

Check the documentation of the RAMPSboard server. There may be a JSON endpoint that provides the data you are looking for in a format more amenable to being consumed by  a program. Failing that, you may want to search for a regex library for your ESP: that is the Swiss knife for parsing text strings.

Thank you, ill have a look at that

open the web page with a web browser ... press F12 (should work for most browsers) .... examine the data that is being sent by the server .... it may already be using xhr ... if it is, then you will see the GET request URL

i would loop though line-by-line, and if i see a smoking gun, process the line further to parse out the values encoded in the html markup using string commands.


text:
Interacting with a video game - Keyboard & LUFA
I have an Uno and Leonardo that I am trying to have it interact with the GTA V video game. Using the Keyboard library, it works within the OS. But it ocassionally works within the GTA V process. It seems that the transfer speed may be too slow, as the game sometimes registers the key press and does the assigned command.
For instance, I can have a pushbutton that when pressed, it activates Keyboard.Write('J'). While in GTA V, I can rapidly press the pushbutton for 3 seconds and the game will only detect one J within that time frame and do the assigned game command.
Yet, if I rearrange the code to be momentary to where the pushbutton is active, it'll constantly send Keyboard.Write('J'), this will work for commands that are momentary ingame, like the vehicle horn.
Below is the code I used for my Uno. It works fine within programs.
/*
  Keyboard Message test

  For the Arduino Leonardo and Micro.

  Sends a text string when a button is pressed.

  The circuit:
  - pushbutton attached from pin 4 to +5V
  - 10 kilohm resistor attached from pin 4 to ground

  created 24 Oct 2011
  modified 27 Mar 2012
  by Tom Igoe
  modified 11 Nov 2013
  by Scott Fitzgerald

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/KeyboardMessage
*/

#include "Keyboard.h"

const int buttonPin = 4;          // input pin for pushbutton
int previousButtonState = HIGH;   // for checking the state of a pushButton
int counter = 0;                  // button push counter

void setup() {
  // make the pushButton pin an input:
  pinMode(buttonPin, INPUT);
  // initialize control over the keyboard:
  Keyboard.begin();
}

void loop() {
  // read the pushbutton:
  int buttonState = digitalRead(buttonPin);
  // if the button state has changed,
  if ((buttonState != previousButtonState)
      // and it's currently pressed:
      && (buttonState == HIGH)) {
    // increment the button counter
    counter++;
    // type out a message
    Keyboard.write('J');
    //Keyboard.print("You pressed the button ");
    //Keyboard.print(counter);
    //Keyboard.println(" times.");
  }
  // save the current button state for comparison next time:
  previousButtonState = buttonState;
}

I also tried this same test using LUFA but the same issues were encountered.
I believe it has to do with the game, not my code.
Does anyone have a clue of why this might be?

Please post your code that is doing what you don't want it to do. For your game, it's likely that either that the game only wants one J, or that it can detect when J is pushed down, and when J is released. You will have to adjust your Arduino code to do the same.

Your button is not debounced. It may be registered as pressed several times for just one physical press.

Have you tested not in the game? (e.g. in notepad) Do you intend it to send SHIFT-J (capital J) or do you want just the j key?

When I tested in Notepad, It sends one Capital J. And it does work within the game, it's just that I have to rapidly press it (for 3 seconds for example) just for it to register once within the game as a command.

It is quite common for games to be quite slow at reading the keyboard.
The Leonardo's Keyboard.write() command is quite rapid. The OS can pick it up with its interrupt driven buffering, but games tend not to use that buffering so they can get more realtime key control.
The trick here is actually to slow down the Leonardo's sending, by not using Keyboard.write(). Instead you need to press the key, wait a moment, then release the key:
Keyboard.press('j');
delay(1);
Keyboard.release('j');

Increase the delay until it becomes reliable. It's hard to say what the delay should be.

Okay, I'll give that a try.

This definitely resolved my issue. Somewhere between 30-40 ms delay is the spot. Now I need to somehow figure if LUFA can achieve this.


text:
Understanding global variables on Arduino
I am rewriting a set of LED manipulation functions to be more object oriented, and I have found that, mysteriously, my global variable memory space has been over consumed, despite a reduction of the use of global variables.
I played around with a number of things, and found something curious.
Here is a fragment of a function that does not live in an object, and is called directly from loop():
Animation *getNewAnim(int index)
{
    switch(index)
    {
        case 0:
            return new RedClouds();
        case 1:
            return new TwoLayerClouds();
        case 2:
            return new LavaLamp1();
        case 3:
            return new Bubbles1();

        ...  (20 or so more cases)
     }

This is a function that lets me switch between display modes based on the value of index.  Only one of these objects is ever created at a given time; I delete the old one before calling this, so there will never be multiple instances in use simultaneously.
Now the curious thing is that if I remove a few of these return statements, collapsing the block into something like this:
Animation *getNewAnim(int index)
{
    switch(index)
    {
        case 0:
        case 1:
        case 2:
        case 3:
            return new Bubbles1();
}

The amount of global memory space used falls considerably.
My hypothesis is that the Arduino build environment is pre-allocating space for each of these objects in the global memory space before the program is even run, rather than doing so dynamically as needed.
Is my hypothesis correct?  And if so, is there any way to tell the build environment not to do this, as I'd rather use the same memory for my new object that was used by the old one.
To clarify: When I build I see this sort of output:
Sketch uses 6,550 bytes (21.3%) of program storage space. Maximum is 30,720 bytes.
Global variables use 1,167 bytes (57.0%) of dynamic memory, leaving 881 bytes for local variables. Maximum is 2,048 bytes.

When I refer to "global memory" I am referring to the Global variables number on that output.  I'll also note that when I compile with the second example, the program storage space reported also falls dramatically.
NEW HYPOTHESIS
Here is what I think may be going on.  When I omit the classes from the switch statement, the compiler seems to optimize them out of the codebase, which is what I expect, and is consistent with seeing the program storage space shrink.  Each class has a method that returns it's name.  This method contains an embedded string, and I now believe that this string is stored in the global variable space.  Therefore, if the class is included, more global variable space is consumed to hold the name, and if it is optimized out, less is consumed.  This theory is consistent with all the facts I have, and makes more sense than my previous hypothesis.

Are you referring to PROGMEM or RAM? Please post a Minimal, Complete, and Verifiable example. I don't see how the "build environment" (basically g++) could possibly pre-allocate space for objects which are going to be dynamically allocated anyway. How are you measuring "global memory space", and what do you mean by that precisely?

return new Bubbles1(); - why the brackets? Why not: return new Bubbles1; ?

@Nick: I added a bit at the bottom of my question that I hope clarifies.  As to the ()... good question.  I'll look into that.

Without seeing the rest of your code, but only a snippet it is hard to say. Maybe the other classes have static variables. If the compiler does not ever see them instantiated it might omit the static variables.

The shrinking program storage makes sense; if the class is never instantiated, the linker probably doesn't bother include the code.  However, I tried adding more statics to both a class and some of its methods, and that didn't affect the global memory space at all (which is what I would expect).  If I can get an unrelated problem solved, and make sure I'm ok license-wise, I could probably upload the whole thing to github.

It's common for people to ask "how come the program gets much bigger when I call a function?". From their viewpoint, they only added one line of code. From the compiler's viewpoint the things that were called are now needed, whereas before they were not.

I should point out that this is a bit of a made-up problem. You are asking: "If I omit some code (which in practice I cannot) why does the executable get smaller and use less RAM?". It's a hypothetical problem. You won't be omitting the code. And, there is no compiler switch along the lines of "don't waste memory". It is already a highly optimizing compiler. It tends to do things which look strange if you don't realize that.

It's theoretical in one sense, but if I can understand why what I'm seeing is happening, I can design around the problem.  As it is, I am just guessing at what's going on in the compiler, and, as you say, it doesn't always behave as expected.  What I need is a tool to tell me what the compiler is putting into the global variable space.

The Animation class defines a number of virtual member functions. The linker has a hard time removing virtual member functions that are not used/called as there is a reference in the virtual table. If the functions use string literals these are all allocated in "global variables". That is why it is important to use the F() macro.

http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_flashstrings

see also http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_varinit

Try running avr-nm -Crtd --size-sort on your elf file. Look for symbols of type 'D' (initialized data), 'B' (BSS) and 'V' (vtable), in either upper or lower case. The list you get is sorted by size. Literal strings may be missing from this list, but you see them with avr-objdump -s -j .data.

I suggest you take a look at https://stackoverflow.com/questions/16274451/operator-new-for-arduino the new operator is not coming from the c++ libraries, it is coming from the Arduino libraries.  It's a wrapper for malloc Is using malloc() and free() a really bad idea on Arduino?