text:
AccelStepper Library Help - Simultaneous Motor Driving
I’m working on a 4 wheeled robot driven with stepper motors. I have a Raspberry Pi that sends a random (based on input image) pulse count to the Arduino board serially and then steps that amount. I’m using an Arduino CNC board to drive all 4 stepper motors, just FYI. My problem is that currently my steppers will not simultaneously move. I’ve read over the documentation for the AccelStepper library pretty well and tried some of the example code with no luck. I have a lot of function/ parsing code prior to the actual stepper code. It’s almost at the end, the function called ‘yMovement’.
Currently, the int value is received then yStepper moves, then yStepper1 moves after.
My updated code now makes them move simultaneously but the done command does not behave as before.
#include <AccelStepper.h>

const int stepperCount = 4;
AccelStepper FLStepper(AccelStepper::FULL2WIRE, 2, 5);
AccelStepper FRStepper(AccelStepper::FULL2WIRE, 3, 6);
AccelStepper BRStepper(AccelStepper::FULL2WIRE, 4, 7);
AccelStepper BLStepper(AccelStepper::FULL2WIRE, 12, 13);

bool movementComplete = false;

// defines pins numbers

//Front left wheel
const int stepX = 2;
const int dirX  = 5;

//Front right wheel
const int stepY = 3;
const int dirY  = 6;

//Back left wheel
const int stepZ = 4;
const int dirZ  = 7;

//Back right wheel
const int stepA = 12;
const int dirA  = 13;
const int enPin = 8;

char split = ':';         //this is the character that would be used for seperating the different parts of your commands
                          //the syntax for commands would be:   command:value1:value2

int listSize = 5;                                     //the amount of commands in the list
String commands[] = {"hello", "add", "sub", "YMOV", "XMOV"};     //the list of every command name

void setup()
{
  Serial.begin(115200);     //sets the data transfer rate for the serial interface
                          //9600 is good for basic testing, but should be as high
                          //as possible for both devices.
  FRStepper.setMaxSpeed(500);
  FRStepper.setAcceleration(400);
  BRStepper.setMaxSpeed(500);
  BRStepper.setAcceleration(400);

  FLStepper.setMaxSpeed(500);
  FLStepper.setAcceleration(400);
  BLStepper.setMaxSpeed(500);
  BLStepper.setAcceleration(400);

  pinMode(stepX, OUTPUT);
  pinMode(dirX, OUTPUT);

  pinMode(stepY, OUTPUT);
  pinMode(dirY, OUTPUT);

  pinMode(stepZ, OUTPUT);
  pinMode(dirZ, OUTPUT);

  pinMode(enPin, OUTPUT);

  digitalWrite(enPin, LOW);
  digitalWrite(dirX, HIGH);
  digitalWrite(dirY, HIGH);
  digitalWrite(dirZ, HIGH);
  digitalWrite(dirA, HIGH);

}

void loop()
{
  CommCheck(); //checks serial buffer for data commands
  runMotors();
}

void runMotors()
{

  if ((FLStepper.distanceToGo() != 0) || (FRStepper.distanceToGo() != 0) || (BLStepper.distanceToGo() != 0) || (BRStepper.distanceToGo() != 0))
  {

    FLStepper.run();
    //BLStepper.run();
    FRStepper.run();
    //BRStepper.run();
    movementComplete = true;
  }
  if (movementComplete == true)
  {
    CommConfirm();
    movementComplete = false;
  }
  //if ((FLStepper.distanceToGo() == 0) && (FRStepper.distanceToGo() == 0) && (BLStepper.distanceToGo() == 0) && (BRStepper.distanceToGo() == 0))
  //if ((FLStepper.distanceToGo() == 0) || (FRStepper.distanceToGo() == 0) || (BLStepper.distanceToGo() == 0) || (BRStepper.distanceToGo() == 0))
  //{
    //movementComplete = true;
  //}
}
void CommCheck()
{
  if(Serial.available())                    //checks to see if there is serial data has been received
  {
    //int len = Serial.available();           //stores the character lengh of the command that was sent
                                             //this is used for command parsing later on

    String command = Serial.readString();   //stores the command as a text string
    int len = command.length();
    //Serial.println(command);
    Serial.flush();
    //command.remove(len-2,1);                //removes characters added by the pi's serial data protocol
    //command.remove(0,2);
    //len -= 3;                               //updates the string length value for parsing routine

    int points[2] = {0, 0};                 //offset points for where we need to split the command into its individual parts

    for(int x = 0; x < len; x++)            //this loop will go through the entire command to find the split points based on
    {                                       //what the split variable declared at the top of the script is set to.
      //Serial.print("Char ");
      //Serial.print(x);
      //Serial.print("- ");
      //Serial.println(command[x]);
      if(command[x] == split)               //this goes through every character in the string and compares it to the split character
      {
        if(points[0] == 0)                  //if the first split point hasn't been found, set it to the current spot
        {
          points[0] = x;
        }
        else                                //if the first spot was already found, then set the second split point
        {                                   //this routine is currently only set up for a command syntax that is as follows
          points[1] = x;                    //command:datavalue1:datavalue2
        }
      }
    }
    CommParse(command, len, points[0], points[1]);      //now that we know the command, command length, and split points,
  }                                                     //we can then send that information out to a routine to split the data
}                                                       //into individual values.

void CommParse(String command, int len, int point1, int point2)
{
  //Serial.print("Command Length: ");
  //Serial.println(len);
  //Serial.print("Split 1: ");
  //Serial.println(point1);
  //Serial.print("Split 2: ");
  //Serial.println(point2);

  String com = command;                 //copy the full command into all 3 parts
  String val1 = command;                //this is needed for the string manipulation
  String val2 = command;                //that follow

  com.remove(point1, len - point1);     //each of these use the string remove to delete
  val1.remove(point2, len - point2);    //the parts of the command that aren't needed
  val1.remove(0, point1 + 1);           //basically splitting the command up into its
  val2.remove(0, point2 + 1);           //individual pieces
  val2.remove(val2.length()-1,1);

  CommLookup(com, val1, val2);    //these pieces are then sent to a lookup routine for processing
}

void CommLookup(String com, String val1, String val2)
{

  int offset = 255;                   //create a variable for our lookup table's offest value
                                      //we set this to 255 because there won't be 255 total commands
                                      //and a valid command can be offset 0, so it's just to avoid
                                      //any possible coding conflicts if the command sent doesn't
                                      //match anything.

  for(int x = 0; x < listSize; x++)   //this goes through the list of commands and compares
  {                                   //them against the command received
    if(commands[x] == com)
    {
      offset = x;                     //if the command matches one in the table, store that command's offset
    }
  }

  switch(offset)                //this code compares the offset value and triggers the appropriate command
  {
    case 0:                                 //essentially a hello world.                       |  Syntax: hello:null:null
      CommHello();                          //this activates the hello world subroutine        |  returns Hello!
      break;
    case 1:                                 //adds both values together and return the sum.    |  Syntax: add:value1:value2
      CommAdd(val1.toInt(), val2.toInt());  //this activates the addition subroutine           |  returns value1 + value2
      break;
    case 2:                                 //subtracts both values and return the difference  |  Syntax: subtract:value1:value2
      CommSub(val1.toInt(), val2.toInt());  //this activates the subtraction subroutine        |  returns value1 - value2
      break;
    case 3:
      yMovement(val1.toInt(), val2.toInt());
      break;
    case 4:
      xMovement(val1.toInt(), val2.toInt());
    default:                                        //this is the default case for the command lookup and will only
      Serial.println("Command not recognized");     //trigger if the command sent was not known by the arduino
      break;
  }
}

void CommHello()                               //each of these routines are what will be triggered when they are successfully processed
{
  Serial.println("Hello!");
  CommConfirm();
}

void CommAdd(int val1, int val2)
{
  Serial.println(val1 + val2);
  CommConfirm();
}

void CommSub(int val1, int val2)
{
  Serial.println(val1 - val2);
  CommConfirm();
}

void yMovement(int val1, int val2)
{
  if (val1 < 0) {
    int yMoveNew = (val1 * (-4));
    //Serial.println(val1 * (-1));
    //delay(500);

    FRStepper.moveTo(-yMoveNew);

    BRStepper.moveTo(-yMoveNew);

    FLStepper.moveTo(-yMoveNew);

    BLStepper.moveTo(-yMoveNew);

    //delayMicroseconds(500);
  }

  else {

    int yMoveNew = (val1 * 4);
    //Serial.println(val1);
    //delay(500);
    FRStepper.moveTo(yMoveNew);

    BRStepper.moveTo(yMoveNew);

    FLStepper.moveTo(yMoveNew);

    BLStepper.moveTo(yMoveNew);

    //delayMicroseconds(500);

  }
}

void xMovement(int val1, int val2)
{
  if (val1 < 0) {
    int xMoveNew = (val1 * (-4));
    //Serial.println(val1 * (-1));
    //delay(1000);
    FLStepper.moveTo(-xMoveNew);

    BLStepper.moveTo(-xMoveNew);

    FRStepper.moveTo(-xMoveNew);

    BRStepper.moveTo(-xMoveNew);

    //delayMicroseconds(500);
  }

  else {

    int xMoveNew = (val1 * 4);
    //Serial.println(val1);
    //delay(1000);
    FLStepper.moveTo(xMoveNew);

    BLStepper.moveTo(xMoveNew);

    FRStepper.moveTo(xMoveNew);

    BRStepper.moveTo(xMoveNew);

    //delayMicroseconds(500);

  }
}
void CommConfirm()
{
  Serial.println("Done");

}

With the AccelStepper.move() function, you are setting the target position of the motor. Then you run the motor with AccelStepper.runToPosition(). But that is a blocking function. It will not exit, until the motor reached it's target position. So you just picked the wrong function from the AccelStepper library.

Small adjacent about simultaneous action on microcontrollers: Since most microcontrollers, like in the Arduino, only have one core, they can only do exactly one thing at a time. But you can still execute things one after another, but so fast, that a human would say, they where happening at the same time. For this we need to divide down the actions into small chunks, that are executed very fast. In your case we have the big actions of running multiple motors to their target positions. Each of these big actions take long in total, but we can divide them down. And with stepper motors that is really easy, because one step would be one small chunk of that action.
So we want to go through our code very fast, successively checking for each motor, if it is time to do a step with it. If yes, we only do that one step. Then we proceed further to the next motor.

The AccelStepper library helps you in doing this checking if it is time to do a step. This is what happens in the AccelStepper.run() function. You just need to call it regularily, fast enough to not miss the time for a step.
So the solution is to remove all the calls to AccelStepper.runToPosition() and instead call the AccelStepper.run() function for all your stepper motors directly in the loop() function.

Thanks for the help!
The problem now is that my commConfirm() function does not send at the right time. I tried adding it in the loop with run() but now realize why it doesn't work like that because technically run() is being ran every step. So the done command is send as soon as the motors start.

You have if (movementComplete == true) for executing commConfirm() with the variable set in the if statement above. Make it an else if clause of the if statement above (but checking for false instead of true) and set movementComplete = true; in that if else clause. The else will cause that part to only be executed, when the distances to go are zero, and only executes once. So something like else if(movementComplete == false){ commConfirm(); movementComplete = true;}. Also make sure to reset movementComplete to false, when you start another movement via Serial.

Thanks for the help! Shortly after I figured it out!


text:
Discrete H-Bridge very low current output
I have built two parallel H-bridges from "Design 1" on this page as you can see in the attached schematic.
However when I apply the external power (VCC1 in the center of the diagram) the two motors do not spin.
Using my multimeter, I can see that the entire circuit is working: the motor is getting a 'forward' and 'backward' current as the Arduino sets the pins high. The multimeter is reading +/- 5.54V with the motor replaced by the multimeter. (Across the motor this drops to 0.13V)
So then I measure the current by putting my multimeter both in series with the motors and replacing the motors. There's only 40mA available! Looking around the web I found the suggestion to reduce the 220Ω resistors at R2, R3, R5 and R6. So I switched in (randomly) 27Ω resistors and the output current is still only 40mA.
What else should I try to bring up the current enough to drive the motors?
Edit: So my uneducated guess is that it's likely that the limitation is coming from the transistors. The Ns are BC549 and the Ps are BC559. The datasheets list "low current" as a feature, but I figured that was the collector.
Edit 2: The motor is this one which requires 70mA when running (and presumably more during startup)

Edit 3: Code driving the Arduino:

// Pin setup
int pinLeftMotorFwd   = 5;
int pinLeftMotorBck   = 6;
int pinRightMotorFwd  = 10;
int pinRightMotorBck  = 11;

// Directions for the {left, right} motors to achieve the four directions
int FORWARD[]   = {  1,  1 };
int BACKWARD[]  = { -1, -1 };
int RIGHT[]     = { -1,  1 };
int LEFT[]      = {  1, -1 };

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

    pinMode(pinLeftMotorFwd,  OUTPUT);
    pinMode(pinLeftMotorBck,  OUTPUT);
    pinMode(pinRightMotorFwd, OUTPUT);
    pinMode(pinRightMotorBck, OUTPUT);
}

void loop() {
    go( FORWARD, 10 );
    go( RIGHT,    3 );
    go( FORWARD, 10 );
    go( LEFT,     6 );
}

// Move the bot in a particular direction from the array above for a given number of seconds
void go ( int dir[], int dur ){
    leftMotor(  dir[0] );
    rightMotor( dir[1] );
    delay( dur * 1000 );
}

// Sill both motors (OK, so stop both motors. But stop is a keyword in C)
void still(){
    leftMotor(  0 );
    rightMotor( 0 );
}

// Set the left motor to Backward (-1), Forward (1), or Stop (0)
void leftMotor( int dir ){
    // Pull both pins low
    digitalWrite(pinLeftMotorFwd, LOW );
    Serial.println("pinLeftMotorFwd LOW");
    digitalWrite(pinLeftMotorBck, LOW );
    Serial.println("pinLeftMotorBck LOW");

    // If we're going forward, pull the Fwd pin high
    if( dir == 1 ){
        digitalWrite(pinLeftMotorFwd, HIGH);
        Serial.println("pinLeftMotorFwd HIGH");
    }

    // otherwise, pull the Bck pin high
    else if( dir == -1 ) {
        digitalWrite(pinLeftMotorBck, HIGH);
        Serial.println("pinLeftMotorBck HIGH");
    }
}

// Set the right motor to Backward (-1), Forward (1), or Stop (0)
void rightMotor( int dir ){
    // Pull both pins low
    digitalWrite(pinRightMotorFwd, LOW );
    Serial.println("pinRightMotorFwd LOW");
    digitalWrite(pinRightMotorBck, LOW );
    Serial.println("pinRightMotorBck LOW");

    // If we're going forward, pull the Fwd pin high
    if( dir == 1 ){
        digitalWrite(pinRightMotorFwd, HIGH);
        Serial.println("pinRightMotorFwd HIGH");
    }

    // otherwise, pull the Bck pin high
    else if( dir == -1 ) {
        digitalWrite(pinRightMotorBck, HIGH);
        Serial.println("pinRightMotorBck HIGH");
    }
}

Design 1 would not have been my first choice.

What is the VCC1's power source. Is it a battery? By the way, 220 Ohm is pretty low value. That will result in 22mA of current (at 5v) going into the base. With a gain of 270 that would result in a collector current of around 6A. I'd try using increasing the resistors to 1 kOhm to 5 kOhm.

@Gerben: Ahh .. I see I may have messed up. I reduced the resistance. I'll try increasing it before I switch to a different circuit per Mark Williams below

Design 1 wouldn't be my first thought on how to do this either! The transistors aren't a great choice, but are cheap & common.
The layout here is more conventional, and you can physically link 1-2, & 3-4 to connect to your arduino without the risk of short circuits.
I suspect your code may be setting both lines high together - the only advantage I can see to the posted circuit is that this does not necessarily cause smoke (but may well do as you describe). This is why posting the code is recommended!

Thanks for the suggestion. The transistors were on-hand. Ultimately once I understand the concepts from "first principles" / discrete components, then I'd just replace the whole lot with either a motor driver circuit or a dedicated H-bridge.  The table at the bottom of the circuit you suggest indicates I need to switch pins between VCC/GND/Disconnected. How can linking 1-2 attached to a pin and 3-4 attached to another pin give me full control? (Code isn't setting both high, but I'll attach it anyway)

The point of the H-Bridge is that the transistors work in pairs - so you would have 1&2 or 3&4 on together, but never 1&3 or 2&4 - if you go back to 'Design 1' you will observe that a single input has been put through an inverter stage to ensure this doesn't happen - your re-design replaces that with software - OK 'til a bug sets up a short.. So with the standard arrangement on that link, the truth table at the bottom (disregard the not-connected options) shows you the combinations. You have off/brake/forward/backward and possibly PWM as well..

No diodes at home, so I built it on circuit.io: http://123d.circuits.io/circuits/511807-h-bridge where I had the exact same problem as my original circuit. Until I realised the NPNs were in backwards. Then everything came good. Going to check my original circuit tomorrow and see if I did the same there before I rebuild.

Turns out my actual problem was having the transistors around the wrong way. I couldn't get my circuit to work so I built yours and got exactly the same thing. The above circuits.io result gave me a clue so I played with them and got them around the right way. Turns out that the side that appears flat in Fritzing is the round side and vice-versa.

source: Stack Exchange

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

sort: votes


text:
Why does it say "Servo" does not name a type
#define pingTrig 6
#define pingEcho 7

#include

Servo myservo;

void setup()
{
pinMode(pingTrig, OUTPUT);
pinMode(pingEcho, INPUT);
myservo.attach(9);
}

void loop()
{
long duration, inches, cm;

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

duration = pulseIn(pingEcho, HIGH);

cm = duration / 29 / 2;

if(cm < 10 ){
myservo.write(90);
delay(100);
}else{
myservo.write(0);
}
delay(2000);
}

Your include statement seems to be incomplete; add "Servo.h" to your include to make it look like this:
#include "Servo.h"

Without including "Servo.h", the compiler doesn't know what a servo is, and thus "Servo does not name a type".

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


text:
ATtiny85 minimum setup to blink led
What would be the (very) minimum schematic to make a ATtiny85 blink a led?
Restrictions are:

There must be a C program compiled and uploaded to it, just like an Arduino board would have. The code would use a simple "delay" to wait a little bit before changing the LED state.
The LED must be controlled by a "digital output port" just like an Arduino board would be.

This is the main question. Although I thought to ask a similar question with the restriction of "blinking exactly once per second", that would change completely the schema (not being a MINIMAL after all). So lets restrain to the main question. Maybe some day we can discuss the version 2.0!

I don't get the question. You set up the pin, toggle the pin, delay the appropriate length, and then go back to the toggle.

I'm talking about the protoboard components needed on it. Lets (fairly) assume that this is a pedagogical question to those who grab one chip for the first time. A small explained minimal schema would be greatly appreciated.

Oh, the schematic? The IC, a power supply, a resistor, and an LED.

Oh, sure. Let me edit my english. Thanks.

Also, support Proposition 12.

This schematic shows a complete connection of a blinking led.

Red cable = +5V (pin 8)
White cable = Ground (pin 4)
Resistor = 1 end at pin 5 (IO 0) and the other in the LED anode (+)
Led anode (+) in the resistor, cathode (-) (small leg) in the ground
Resistor = 330 Ohms

The arduino in the picture is not necessary, just used to give power. But in the video linked below its used to burn the ATtiny85. The resistor can be a 330 ohms for a simple project like this.

Youtube Video with a simple explanation
I hope this explanation will enlighten who wants to start on it.
--
Edited:
If you want to record your ATtiny85 using Arduino UNO as ISP, then you will also need:

10 uF electrolytic capacitor

Here a picture of the pins:

You forgot the decoupling.

@Klaus Warzecha , what is the hardware port (pin?) you're writing about?

You want a 100nF capacitor as well, right by the supply pins.

Ignacio Vazquez-Abrams has already outlined the schematics.

There must be a C program compiled and uploaded to it, just like an Arduino board would have.

There are however some differences between a fully equipped Arduino board with an ATMega328P and a bare ATtiny85 you would have to care for in your code:

A bare ATtiny85 runs at 1 MHz (8 MHz internal oscillator, CKDIV8). Define F_CPU accordingly.
The ATtiny85 only has one hardware port, PB. There's a reason Ignacio used PBx in his scheme ;)

On the plus side, the ATtiny85 allows to toggle a pin by setting the corresponding bit in PINB.
PINB |= (1 << PB0);

Here is the absolute minimal schematic required to blink a LED beyond power and decoupling:

Refer to "Which resistor to use for this LED" to calculate the appropriate value for R1.

Would you be kind to expand all pin connections in that little box called PBx? Without that, the mystery would be solved only by google.

It's one of the GPIOs on the IC.

Correct me if I'm wrong: pins: 1=reset, 2,3=free, 4=gnd, 5=LED, 6,7=free, 8=+5V.

It's all in the datasheet.

My setup would be:

a 10k resistor between Vcc and reset pin (pull-up)
a 330k put in serial with a led,  connected between, e. g. PB0 and gnd.

That's all.
For programming, I use an ISP programmer.  I use a cheap Arduino Nano clone board for that.
I can run my ATtiny85 at 16Mhz internal oscillator,  but important: I remarked that I had better results after having burnt the bootloader onto the ATtiny85, even if it is not needed because there is no USB serial chip besides the MCU.
But perhaps using avrdude to program the ATtiny85 fuses bits could avoid to burn this useless bootloader (taking 1/4 of flash memory). If someone has a solution, he is welcome.

What would that 10k resistor be used for? Thanks.

http://electronics.stackexchange.com/questions/58673/reset-pin-on-attiny84-85-2313-clarification


text:
Garbled serial on custom arduino UNO
I built my own Arduino UNO for a project at school. I think I have got the USB bootloader and Windows drivers all situated as the UNO shows up as an UNO in the device manager. When I try to load a sketch I get the error: avrdude: stk500_getsync(): not in sync: resp=0x10. (previously I received the same message with the message ending with resp=0x00)
I loaded a serial echo program using the ICSP and sent the message "serial test" to the UNO. I received this message back: {u{m}o¿wu{w
Can anyone help me troubleshoot this problem as I have ran out of things to test or look into.
Thanks in advance.
Edit: Added requested pictures of TX and RX. These were taken at Pin 0 and 1 of the headers. The scope showed the same results at the pins of the 328P but I couldn't operate the scope and hold the probe at the same time.

Can you receive the correct serial string, if you use a different baud-rate?

Did you use existing gerber files or did you lay it out yourself?

@Gerben I have tried all of the Baud rates and none work.

@IgnacioVazquez-Abrams I did the schematic and PCB myself.

Find an oscilloscope and connect it to the TX and RX lines, right at the MCU. Based on the bit patterns I suspect that there is a lot of ringing or noise on the lines.

What USB-to-Serial chip are you using? The ATMega8u2?

@Gerben No, the 16U2.

@IgnacioVazquez-Abrams Scope results edited into original post.

HOLY CRAP. You need to take this serial connection issue to EE.SE now.

@IgnacioVazquez-Abrams Is it really that bad?

Subsequent to finding the solution on EE.SE, I recommend that we remove this question from here since it's not actually Arduino-related.

Could be an issue with the 16u2 or the 328. Try connecting pin 0 and 1 (Tx and RX) (also add a empty sketch to the 328). Try typing in the console. If all is well with the 16u2 the typed text should be echoed right back.

Related: http://arduino.stackexchange.com/questions/17/some-dude-named-avr-wont-let-me-upload-my-program-aka-avrdude-stk500-getsync

See this post. There are suggestions there for checking various things. I suspect you might have the "divide clock by 8" fuse bit set. Please post your test code. What is the horizontal scale on that scope image?

Sorry for the delay. I posted this question on the EE board as suggested and forgot to come back here and close this out. It was an issue with the fuses. My initial attempt to setup the 16u2 missed the step where I was supposed to change the fuses. I thought this was accomplished when loading the firmware, but was mistaken.

From the scope picture it appears you have a ground problem. All the grounds must be connected together even the scope. It appears like you have a pseudo phantom ground via the mains power system. Did you set the baud in the uno with Serial.begin(your baud rate);? The baud must be the same on both ends. For a check you should get a UNO and see if it works with that the problem is your board. Also be sure Tx on the UNO goes to RX on the receiving end and visa versa.

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


text:
Cannot convert 'int (*)[size]' to 'int**'
Analyzing this and this answers under Arduino, which should be the proper way to pass a 2D array into a function?
The function should be applicable to different sizes of 2D arrays.
// NOT COMPILING EXAMPLE
void f(int** x,const int m, const int n){
// access x as x[0][0], x[0][1], etc...
}

void main{}{
    int x1[16][128];
    f(x1,16,128);
    int x2[64][16];
    f(x2,64,16);
}

the compiler must know the second dimension's size. one option is void f(int x[][128],const int m){

I'd rather use one dimensional array. It's not so hard to transform two dimensional indexes to one dimension.

According the prototype of f and the usage pattern for its x
argument, the function expects this argument to be a pointer to the
first element of an array of pointers to the first elements of arrays of
int. However, the matrix in main() is defined as an array of arrays
of int. If you try to pass this to a function, the matrix will decay
into a pointer to an array of int. That's not what you want.
If you want both dimensions of the matrix to be variable, the only
simple solution I see is to build an extra array of pointers (pointing
to the matrix rows) and pass that array to the function
int main() {
    int x[16][128];

    // Build an array of pointers to rows.
    int *px[16];
    for (int i = 0; i < 16; i++)
        px[i] = x[i];

    f(px, 16, 128);
}

For more information on this, see the section Arrays and Pointers in
the C FAQ, and more specifically the questions 6.16 (How can I
dynamically allocate a multidimensional array?) and 6.19 (How do I write
functions which accept two-dimensional arrays when the width is not
known at compile time?).

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


text:
Arduino Due ADXL345 Interference
I am working with an Arduino Due and the Analog ADXL345 through a module following this tutorial, with the wire.h library at Fast Speed (400kHz), the Accelerometer Sampling at 800Hz (for the Maximum Reccomended Limit), and the Serial Monitor at 115200 bps.
The cable is 24AWG solid wire, 6in length, two pairs, for 3.3V, GND, SCL and SDA pins.
When the accelerometer is starting up, it generates a high pitched noise is generated!. Possibly by the 5V-3.3V regulator or by the accelerometer itself.
Under 400kHz|800Hz, the readings are unstable: by simply touching some open terminals in the Due, the Accelerometers readings toggle between strong oscillations and the correct ones (Figure 1).

After some "taps", the oscillations stops and the proper measures can be captured at the expected sampling rate (Figure 2). Note the mean values are modified for plotting only.

What should I do to prevent such behavior?, and what is causing that, considering the device is indeed working at the expected speed?

Please add the wiring of the module and information about cable length, type, etc. The wires should be as short as possible and there should be common ground.

I edited the question with the tutorial  followed, 15cm length cable, 24 AWG solid wire.


text:
Proteus - How to Debug Invalid Opcode?
While running a program compiled in the Arduino IDE 1.8.5 and then using the .ELF file inside LabCenter Proteus 8.0, for an Arduino Nano ATMEL Mega 328P, for a code involving the use of the SoftwareSerial.h Library, hence involving several loops, without user interaction, I am getting the following error:
Invalid opcode 0x0024 at PC=0x0096

Now I am completely lost. According the AVR Instruction Set Manual such opcode should (not sure about this?) be RETI - Return From Interrupt at the Program Line (?) no.150 = 0x096. The full code has 779 lines plus several library calls, and the line 150 happens to fall just before the loop() function (?), which should never repeat, being just a declaration.
So, how should I debug this error? Evidently I am not asking to solve the problem for me but, how should I proceed for debugging it and find the real error?
I have been unable to find in Proteus a tool for "Debug Stop if Error"
I have been unable to isolate the error in a simple way to share. It should be related someway with interruptions used by the library SoftwareSerial.h, because at some modifications of the program, the code freezes at an interruption return. I am working on that, but advancing really slowly actually.

Related question No.1.

PC=0x96 has no relation to any lines in your source code. So, no, there's no point in looking at line 150. Line 150 is completely irrelevant here. And where exactly in the manual did you read that 0x0024 is RETI?

I am not understanding the situation for debugging this...

Where's the program? Errors like that might easily be caused by out-of-bounds local array modification. Stack damage smashes the stored function's return address, making it "return" to a completely wrong location (e.g. 0x96), hitting "invalid instructions" stored there.

PC=0x96 means the program counter is pointing to that memory location and it is trying to execute the instruction at that location  ..... the last picture shows code at 0x1ab4

I have the same problem. Would you tell me please, if you have solved the problem, and how?

@RamiMa I absolutely forgot what i had to do to fix that. I vaguely remember, I had to avoid something cumbersome I was making, such as using a version or a library or an array. Everything I tried with Proteus with real Arduino code worked fine, serials, ports, logics, analog & digital simulations, etc. In this case, please roll back some steps, and try to keep simple and elliminate the bad step you made. For sure, I did not debug anything. I had to roll back to something understandable to Proteus. I guess: this was cause because Mega become short for my code, and then I think I had to move...

Guys if you are facing the error of invalid opcode 0xffff at pc = 0x3e402 in proteus using Arduino, the GO to Arduino IDE software, and from the top menu, click on 'tool' and change the board type, e.g., Arduino UNO to Arduino Mega 2560.

First: Use the ino.hex file instead of the  .ELF file
Second: this error is showing because you are compiling your code with a different board. Make sure you are using the correct board over at the Arduino IDE. My advice is: switch your board to Arduino Uno both in proteus and over at the Arduino IDE and see if it works. Later on, you can try different boards.


text:
Nextion won't update text using data passed in Arduino Uno serial print
Q: Is it possible to send data in variables from Arduino to Nextion through SerialPrint? If so, what is the correct syntax?
I have an Arduino Uno connected to a Nextion NX4024T032 and a Sunfounder RC522, with a USB run from my PC into the Uno. I want the Nextion to show the name associated with an RFID card from simple if/then statements in the .ino file.
I created what I thought was a simple set of .ino and .tft files to test the Nextion updating from data sent from the Arduino by serial print. I have confirmed in Serial Monitor on the PC that the RFID reader is functioning and that the Uno is sending out the information I am asking it to print. But the Nextion is not changing text to match what I am trying to send it. It just displays the value entered for .txt in the HMI editor.
I am trying to do this without nextion libraries.
Pinout for the RC522 is as in the .ino below (9-13); plus GND and 3.3V on the Uno.
Pinout for the Nextion is Nextion TX to Uno 1, Nextion RX to Uno 0, plus GND and 5V on the Uno.
Here's the .ino:
/*
 *-----------------------------------------------------
 * Aggiunti pin per arduino Mega
 * add pin configuration for arduino mega
 * http://mac86project.altervista.org/
 ---------------------------------------------------Nicola Coppola
 * Pin layout should be as follows:
 * Signal     Pin              Pin               Pin
 *            Arduino Uno      Arduino Mega      MFRC522 board
 * ------------------------------------------------------------
 * Reset      9                5                 RST
 * SPI SS     10               53                SDA
 * SPI MOSI   11               51                MOSI
 * SPI MISO   12               50                MISO
 * SPI SCK    13               52                SCK
 */

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

void setup() {
    Serial.begin(9600); // Initialize serial communications with the PC
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
    Serial.println("Scan PICC to see UID and type...");
}

void loop() {

//condensed to remove RFID code
  if (UID_string == "4294935680")
  {
    Serial.println("va0.txt=\"Maia\"");
  }

  if (UID_string == "31615")
  {
    Serial.println("va0.txt=\"Claire\"");
  }

  if (UID_string == "24498")
  {
    Serial.println("va0.txt=\"Jack\"");
  }
}

The .tft I loaded to the Nextion using an SD card is just a text box (t0) on page0, a timer event and a value. The timer should update t0.txt on the display to equal most recent va0.txt in the serial print every 400 ms.

UPDATE:
While trying to understand syntax for commands to send from Arduino Uno to Nextion, I came across directions for sending data a character at a time. So, a very new version below, with all RFID parts removed.
 * Pin layout should be as follows:
 * Signal     Pin              Pin               Pin
 *            Arduino Uno      Arduino Mega      MFRC522 board
 * ------------------------------------------------------------
 * Reset      9                5                 RST
 * SPI SS     10               53                SDA
 * SPI MOSI   11               51                MOSI
 * SPI MISO   12               50                MISO
 * SPI SCK    13               52                SCK
 */

#include <SPI.h>
#include <SoftwareSerial.h>
#define SS_PIN 10
#define RST_PIN 9
SoftwareSerial mySerial(0,1);

void setup() {
    Serial.begin(9600); // Initialize serial communications with the PC
    SPI.begin();            // Init SPI bus

  while (!Serial) { // wait for serial port to connect. Needed for native USB port only
    ;
  }

  Serial.println("Serial On"); //Print this messages when the serial port is connected
  mySerial.begin(9600); // set the data rate for the SoftwareSerial port

}

//NOTE:Credit to RamjetX : http://forum.arduino.cc/index.php?topic=89143.0

void writeString(String stringData) { // Used to serially push out a String with Serial.write()

  for (int i = 0; i < stringData.length(); i++)
  {
    mySerial.write(stringData[i]);   // Push each char 1 by 1 on each loop pass
  }

  mySerial.write(0xff); //We need to write the 3 ending bits to the Nextion as well
  mySerial.write(0xff); //it will tell the Nextion that this is the end of what we want to send.
  mySerial.write(0xff);

} // end writeString function

void loop() {
  String sendThis = "";
  sendThis = "t0.txt=\"working\""; //Declare and initialise the string we will send

  delay(300); //

  writeString(sendThis); // Use a function to write the message character by character to the Nextion because
  mySerial.write(sendThis) gives you an error due to a datatype mismatch*/
}

Conclusion: The SerialPrintln() statements still send text to the serial monitor, but mySerial.write does not show in the serial monitor and the Nextion screen still does not update to show "working" as passed in t0.txt .

I have condensed the RFID code and added explicit questions at the top of the post. Please clarify what 'fixed text' would look like?

Thank you for the direction and replies. I am pretty sure I want to use variables if possible, because later I want to use the Nextion to show multiple buttons showing text strings coming from a MySQL cloud-based db. My understanding is that Nextion is useful for storing much of what will be displayed on screen (.e.g, graphics), and so my plan is to send variables to Nextion and change only the .txt values of the buttons. At the moment, I am simply trying to get started with Arduino directing Nextion at all, while keeping in mind the pins that will be used by the RFID module.

I see your point - well said. I will take another run at it and post an update. Thanks again.

use software serial for the Nextion ... see software serial example sketch that passes input from serial monitor to the device ... type the Nextion comnands into serial monitor

read the instruction set info at the Nextion website ... you missed something

I've tried to send data a character at a time (see new code below UPDATE) but Nextion is still not updating.

you cannot use pins 0 and 1 for software serial ... those are hardware serial ... use the software serial example at the arduino website


text:
How can I get an integer from an RFID tag from Arduino Mega to NodeMCU 1.0 over serial communication?
I want the number from an RFID tag read by a reader connected to an Arduino Mega to end up as a string on a NodeMCU connected to the Mega. I am trying to confirm that the string is on the NodeMCU using the serial monitor. With the code below, the serial monitor for the NodeMCU prints "receivedChars:" only and not the number from the tag. What am I missing?
Code for Arduino Mega

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

String sent = "n";
String UID_string = "";

void setup() {

    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
    Serial.begin(115200); // Initialize serial communications with the PC
    Serial.println("Running Version Jan5a");
    Serial.println("Mega:Serial Monitor initialized at 115200 baud...");
    Serial3.begin(9600); // Initialize serial communication with ESP
    Serial.println("Mega:Serial Port 3 for NodeMCU initialized at 9600 baud...");
    Serial.println("Mega: Scan PICC to see UID and type...");
}

////////

void SendUIDtoESP() {

if (sent == "n") {
  Serial.print("sent= ");
  Serial.print(sent);
  //if (UID_string.length() > 0)  {
  UID_string = "Hello World"; //test line
  Serial3.print("<");
  Serial3.print(String(UID_string));
  Serial3.print(">");
  Serial.println("Mega:Sending UID string to ESP");
  sent = "y";
  Serial.print("after sending, sent= ");
  Serial.print(sent);
//  } else {
 //   Serial.println("Mega: Error: UID-string not set yet!");
  //}

}
} // end Send UID to ESP

void loop {
SendUIDtoESP() ;
}

Code for NodeMCU

int numChars = 0;
String receivedChars = "";
boolean newData = false;
String tag = "";
unsigned long lastTime = 0;
unsigned long timerDelay = 5000;

SoftwareSerial s(D1,D2);// assign pins to send data to and receive data from NodeMCU to Arduino Mega rx, tx

void setup() {
Serial.begin(9600);
    s.begin(9600);
    Serial.println("NodeMCU: Waiting for serial connection with Mega to be available over s");
  while (! s.available() >0){
    Serial.print("."); // waiting
    return;
  }
  Serial.println("NodeMCU: Looks like Mega is available.");
} // end void setup

 void recvWithStartEndMarkers() { //listen to Mega
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (s.available() > 0 && newData == false) {
        rc = s.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                Serial.println(rc);
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }
        else if (rc == startMarker) {
          Serial.println("startMarker received");
            recvInProgress = true;
        }
    }
} // end recvWithStartEndMarkers()

void loop() {
recvWithStartEndMarkers();
}

why the Mega? NodeMcu has SPI too

what is this?: String UID_string =  (String)UID_unsigned;

I think I took the block containing that line from here: https://github.com/miguelbalboa/rfid/issues/63#issuecomment-66874814

I'm using the NodeMCU for Wifi for the Mega (not reflected here to cut down on code length); I'm using the Mega because I plan on adding an unknown number of components down the road and think I need the ports.

determine if the serial comm actually works as expected ... start with simple hello world sketch

@jsotola are you suggesting testing the Mega sending 'hello world' to the NodeMCU?

yes, that would make certain that the two devices are able to communicate ... one other thing, when printing receivedChars, print the length of receivedChars also ... some characters are nonprinting

@jsotola Thanks for pointing me back to this level of basics. It does not seem to be working with hardcoded Uid_string = "Hello World" in the Mega code (nothing seems to be coming through, and no value for length is prining). I'll work on that. I read somewhere that using the SerialMonitor on the NodeMCU's USB micro-B port could interfere with the serial communications (ESP D1, D2 / Mega 15,14) with the Mega. Might that be an issue here?

Your nodemcu code would print "receivedChars" also, if nothing was received. You might wanna move that code into the if statement of the end marker (so only printing, when a full message was received). How did you connect the mega and the nodemcu?

@jsotola Update: I have focused on getting just 'Hello World!' to transmit and displayed on Serial Monitor for the ESP, and that is now working. I have removed the RFID section because I think the real challenge is converting a character array to string on the ESP, not the RFID reading on the Mega. The serial monitor for the ESP, however, prints "startMarker received" on one line, and then each character of "Hello World!" on a different line. If someone can help me to get 'Hello World!' on the ESP as a string I can append to a URL as a parameter, I should be set (I think).


text:
Phantom reading
my project is to control led diode and dc motor, test shield buttons, and check system run time.
Testing buttons and run time i have done.
Deal is with led and dc motor control.
I'm getting phantom reading, that means,when i'm scrolling main menu, diode and dc motor starts working, when they shouldn't.
Dc motor or led diode should work only when i enter their control menu, not when i'm in main menu.
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

int masterKey = A0;
int keypadKey = 0;
int buttonPress = 0;

char push;

byte menu = 1;
byte menuOld = 1;
byte menuAll = 4;

//_______LED/MOTOR_________________
int speedall;
int mtor = 5,
   led = 6,
   error = 7;
const int Upstep = 3;
const int maxspeed = 255;

void setup() {
 pinMode(led, OUTPUT);
 pinMode(mtor, OUTPUT);
 lcd.begin(16, 2);
 mainMenu();
 delay(100);
 Serial.begin(9600);
}

void loop()
{
 push = readKeypad();
 menuContr();
 if (push == btnSELECT) //enter selected menu
 {
   waitKey();
   switch (menu) {
     case 1:
       lcd.begin(16, 2);
       lcd.setCursor(0, 0);
       lcd.print("Push the buttons");
       ButtonTest();
       break;
     case 2:
       lcd.clear();
       lcd.setCursor(0, 0);
       lcd.print("Speed 0 to 255:");
       MotorControl();
       break;
     case 3:
       lcd.clear();
       lcd.setCursor(0, 0);
       lcd.print("Brightness 0 to 255:");
       LEDControl();
       break;
     case 4:
       SystemTime();
       break;
   }
   mainMenu();
   waitKey();
 }
 delay(10);
}
//____________________________
void ButtonTest() {
 while (readKeypad() != btnSELECT) {
   lcd.setCursor(9, 1);
   lcd.print(millis() / 1000);
   lcd.setCursor(0, 1);
   int lcd_key = readKeypad();
   switch (lcd_key) {
     case btnRIGHT:
       lcd.print("RIGHT ");
       break;
     case btnLEFT:
       lcd.print("LEFT   ");
       break;
     case btnUP:
       lcd.print("UP    ");
       break;
     case btnDOWN:
       lcd.print("DOWN  ");
       break;
     case btnSELECT:
       lcd.print("SELECT");
       break;
     case btnNONE:
       lcd.print("NONE  ");
       break;
   }
 }
}
//____________________________
void MotorControl() {
 while (readKeypad() !=  btnSELECT) {
   if (readKeypad() == btnUP) {
     speedall <= maxspeed;
     speedall += Upstep;
     lcd.setCursor(5, 2);
     lcd.print("                ");
     lcd.setCursor(5, 2);
     lcd.print(speedall);
     delay(100);
     analogWrite(mtor, speedall);

   }
   else if (readKeypad() == btnDOWN) {
     speedall <= maxspeed;
     speedall -= Upstep;
     Serial.print(speedall);
     lcd.setCursor(5, 2);
     lcd.print("                ");
     lcd.setCursor(5, 2);
     delay(100);
     analogWrite(mtor, speedall);
   }
 }
}
//____________________________
void LEDControl() {

 while (readKeypad() != btnSELECT) {
   if (readKeypad() ==  btnUP) {
     speedall < 255;
     speedall += Upstep;

     lcd.setCursor(5, 2);
     lcd.print("                ");
     lcd.setCursor(5, 2);
     lcd.print(speedall);
     delay(100);
     analogWrite(led, speedall);

   }
   else if (readKeypad() == btnDOWN) {
     speedall > 255;
     speedall -= Upstep;

     lcd.setCursor(5, 2);
     lcd.print("                ");
     lcd.setCursor(5, 2);
     lcd.print(speedall);
     delay(100);
     analogWrite(led, speedall);

   }
 }
}
//____________________________
void SystemTime() {
 lcd.clear();
 while (readKeypad() != btnSELECT) {
   lcd.setCursor(6, 0);
   lcd.print("TIME");
   lcd.setCursor(7, 1);
   lcd.print(millis());
   lcd.print("s");
   delay(100);
   lcd.clear();
 }
}
//______________________________

void mainMenu() {
 lcd.clear();
 lcd.setCursor(0, 0);
 switch (menu) {
   case 1:
     Serial.print(speedall);
     lcd.print("Button test");
     break;
   case 2:
     Serial.print(speedall);
     lcd.print("Motor contr");
     break;
   case 3:
     Serial.print(speedall);
     lcd.print("LED contr");
     break;
   case 4:
     Serial.print(speedall);
     lcd.print("Syst run time");
     break;
 }
}
//____________________________
void executeAction() {
 switch (menu) {
   case 1:
     ButtonTest();
     break;
   case 2:
     MotorControl();
     break;
   case 3:
     LEDControl();
     break;
   case 4:
     SystemTime();
     break;
 }
}
void menuContr() {
 waitKey();
 if (push == btnUP) {
   menu++;
   if (menu > menuAll)
     menu = 1;
 }
 else if (push == btnDOWN) {
   menu--;
   if (menu == 0)
     menu = menuAll;
 }
 if (menu != menuOld) {
   mainMenu();
   menuOld = menu;
 }
}
int readKeypad() {
 keypadKey = analogRead(masterKey);
 if (keypadKey > 1000) return btnNONE;     // about 1023
 if (keypadKey < 50)   return btnRIGHT;    // about 0
 if (keypadKey < 195)  return btnUP;       // about 99
 if (keypadKey < 380)  return btnDOWN;     // about 255
 if (keypadKey < 555)  return btnLEFT;     // about 409
 if (keypadKey < 790)  return btnSELECT;   // about 640
 return btnNONE;
}
void waitKey() {
 while ( analogRead(masterKey) < 800) {}
} ```

what have you done to debug your code? ... i see a few serial.print statements ... use more of them to trace the program flow

yeah, i have used some to track phantom readings. But still can't find where is the problem

please do not make an assumption that the problem is caused by phantom reading ... making such an assumption will hinder you in detecting the actual cause .... please present the sketch with the debugging code included and add the content of the serial monitor to your post

ok, tnx for feedback

a couple of observations ... waitKey() should be named waitKeyRelease() ...... the MotorControl() function does not wait for key to be released ... the UP or DOWN key is still pressed when the function is first executed


text:
Servo retaining its position every time I send some value
I wanted to control my servo with a Bluetooth module.
I gave certain values for rotating it. When I press those values the servo rotates, but then retains its original position and the PC also makes the sound of the Arduino board disconnecting because I powered the board with my PC (tried with powerbank also). Even my Bluetooth disconnects.
This is my code:
#include <Servo.h>

Servo myservo;
int pos = 0;
char data = 0;

void setup() {
  myservo.attach(9);
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    data = Serial.read();
    if (data == 'F') {
      // for (pos = 0; pos <= 180; pos += 1)
      myservo.write(180);
      delay(1);
    }
  }
  else if (data == 'B') {
    // for (pos = 180; pos >= 0; pos -= 1)
    myservo.write(0);
    delay(1);
  }
}

Connections:
Servo:
red wire -- 5 V (not working at 3.3 V)
orange wire -- pin9
brown wire -- gnd

Bluetooth (hc05):
5 V -- 5 V
gnd -- gnd
rx -- tx
tx -- rx

I fixed your indentation. You are missing 2 closing curly brackets at the end. Also your for loop for the character F is not doing anything except waiting (you are not writing to the servo there). If your USB connection fails when the servo moves that can indicate a power issue. What type of servo do you have exactly? Have you tried powering the servo seperately from a more capable power source?

There's no servo positioning line for when 'F' is pressed (myservo.write), I'm guessing that's an accidental omission in the code you posted. Your description of the symptoms indicates the arduino board is resetting, presumably a power issue. A full circuit diagram would help diagnose your issue.

@chrisl i powerd it with a charger but still dosent work.

How exactly did you power it with a charger? Through the USB port of the Arduino? Depending on the power draw of the servo you might overload the diode in there. Please try powering the servo directly from the charger (not through the Arduino). And tell us what kind of servo you have

i have 9g servo

your code should never contain }}, unless you are an expert programmer ... always position } at the correct indentation level for each block that they delimit ... prepare yourself for a world of hurt if you do not learn to format your code properly

I tried changing the USB B cable with a better quality one and it worked.

It is OK to answer your own question. Now, please, mark it for future visitors with a similar problem.


text:
Interrupt protection in ESP32 from interference signals
When my ESP32 is powered with an external 5V adapter or 12V power (2596 DC-DC to 5V), and my water meter (reed switch) is connected with the ESP32, the pulse start running wild and keeps increasing at each interval (of the debounce delay).
When I connect thd ESP32 to my laptop's USB port, there are no random pulses on the ESP32 with the reed switch wires connected.
I'm reading 4 pulses, storing those counter in EEPROM, using interrupt on GPIO 25, 26, 27 and 35.
Code:
#include <EEPROM.h>
#define PULSE_ADDRESS 200

#define pin35  35
#define pin25  25
#define pin26  26
#define pin27  27

const int Pulse1 = pin25;
const int Pulse2 = pin26;
const int Pulse3 = pin27;
const int Pulse4 = pin35;

int PulseHit = 1;
const int debounceDelay = 5000;  // Adjust this value based on your requirements

volatile unsigned long lastDebounceTimePulse1 = 0;
volatile unsigned long lastDebounceTimePulse2 = 0;
volatile unsigned long lastDebounceTimePulse3 = 0;
volatile unsigned long lastDebounceTimePulse4 = 0;

volatile unsigned long pulse1Count = 0;
volatile unsigned long pulse2Count = 0;
volatile unsigned long pulse3Count = 0;
volatile unsigned long pulse4Count = 0;

void IRAM_ATTR handlePulse1() {
  if ((millis() - lastDebounceTimePulse1) > debounceDelay) {
    PulseHit = 1;
    lastDebounceTimePulse1 = millis();
    pulse1Count++;
  }
}

void IRAM_ATTR handlePulse2() {
  if ((millis() - lastDebounceTimePulse2) > debounceDelay) {
    PulseHit = 1;
    lastDebounceTimePulse2 = millis();
    pulse2Count++;
  }
}

void IRAM_ATTR handlePulse3() {
  if ((millis() - lastDebounceTimePulse3) > debounceDelay) {
    PulseHit = 1;
    lastDebounceTimePulse3 = millis();

    pulse3Count++;
  }
}

void IRAM_ATTR handlePulse4() {
  if ((millis() - lastDebounceTimePulse4) > debounceDelay) {
    PulseHit = 1;
    lastDebounceTimePulse4 = millis();
    pulse4Count++;
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(Pulse1, INPUT);
  pinMode(Pulse2, INPUT);
  pinMode(Pulse3, INPUT);
  pinMode(Pulse4, INPUT);

  attachInterrupt(digitalPinToInterrupt(Pulse1), handlePulse1, RISING);
  attachInterrupt(digitalPinToInterrupt(Pulse2), handlePulse2, RISING);
  attachInterrupt(digitalPinToInterrupt(Pulse3), handlePulse3, RISING);
  attachInterrupt(digitalPinToInterrupt(Pulse4), handlePulse4, RISING);

  lastDebounceTimePulse1 = millis();
  lastDebounceTimePulse2 = millis();
  lastDebounceTimePulse3 = millis();
  lastDebounceTimePulse4 = millis();

  EEPROM.begin(512);
  EEPROM.get(PULSE_ADDRESS, pulse1Count);
  EEPROM.get(PULSE_ADDRESS + sizeof(pulse1Count), pulse2Count);
  EEPROM.get(PULSE_ADDRESS + 2 * sizeof(pulse1Count), pulse3Count);
  EEPROM.get(PULSE_ADDRESS + 3 * sizeof(pulse1Count), pulse4Count);
  EEPROM.end();
}

void loop() {
  // Print the results
  if (PulseHit == 1) {
    Serial.print("RISING Pulse on pin 25: ");
    Serial.println(pulse1Count);

    Serial.print("RISING Pulse on pin 26: ");
    Serial.println(pulse2Count);

    Serial.print("RISING Pulse on pin 27: ");
    Serial.println(pulse3Count);

    Serial.print("RISING Pulse on pin 35: ");
    Serial.println(pulse4Count);

    Serial.println(" ");

    PulseHit = 0;

    // Save pulse counts to EEPROM
    EEPROM.begin(512);
    EEPROM.put(PULSE_ADDRESS, pulse1Count);
    EEPROM.put(PULSE_ADDRESS + sizeof(pulse1Count), pulse2Count);
    EEPROM.put(PULSE_ADDRESS + 2 * sizeof(pulse1Count), pulse3Count);
    EEPROM.put(PULSE_ADDRESS + 3 * sizeof(pulse1Count), pulse4Count);
    EEPROM.commit();
    EEPROM.end();
  }
}

I have gone through the similar questions below; I haven't tried the capacitor, but I added a debounce of 2 seconds in the code which should be enough, but if not, please let me know.
I have tried 1k, 10k, and 330 resistors to PULL-UP as well as PULL-DOWN.

How to avoid electromagnetic interference on ESP32 input
https://forum.arduino.cc/t/pulse-counting-with-an-external-device/316432/11
https://forum.arduino.cc/t/rain-gauge-reed-switch-interference/466087/6
https://forum.arduino.cc/t/interrupt-problems-on-arduino/496335/11
Measure revolutions per second with reed switch

Are there any other ways to suppress the interferences on thd ESP32?
Edited:
void setup() {
  for (int i = 0; i < numleds; i++) {
    pinMode(ledPins[i], OUTPUT);
  }

  pinMode(Pulse1, INPUT);
  pinMode(Pulse2, INPUT);
  pinMode(Pulse3, INPUT);
  pinMode(Pulse4, INPUT);
}

void loop() {
if (digitalRead(Pulse1) == HIGH) {
  digitalWrite(ledPins[0], HIGH);
} else {
  digitalWrite(ledPins[0], LOW);
}

start at the begining ... write simple code that turns on an LED when the switch is closed and turns off the LED when the switch is open ... please report back with the frequency with which the LED cycles

@jsotola without any delay? on turning on and off

what would be the reason to use a delay? ... just have the LED show the state of the switch ... that way you can tell how often the switch gets activated

do you have access to an oscilloscope?

The issue happens onsite, can't hook the oscilloscope there. But I will try the LED on/off.

@jsotola Okay the led is blinking way too fast, can only notice in dark.
added test code in original question

blinking too fast ... what does that mean? ... blinking too often? ... of turns off too quickly? ... BTW, all you need is one program line digitalWrite(ledPins[0], digitalRead(Pulse1));

Yes, turn on and off so quickly that, barely see it turning on.

run less water through the water meter ... see if the pulse repeats at a slower rate

The meter was not running at all, it was taking EMI from a nearby meter which is powered on AC and also a router module.
I tried with 220 Ohm Pull-up resistor it seems to improve the EMi impression to some extent.


text:
Send values from Arduino Uno to Wemos D1 R1
I have a weather project in which I have to measure the temperature and humidity (DHT22 sensor), the pressure, and other things, and then show them on a local web page (using a Wemos D1 R1) in either my phone or PC (I have both an Arduino Uno and a Wemos D1 R1 for this project)
I wanted to use only the Wemos D1 R1 since it works the same as an Arduino Uno except it has an ESP8266 WiFi built-in while the Arduino Uno doesn't, but as you may know it only has 1 analog pin while I need at least 3 or 4 analog pins, so in my case I should connect the sensors with the Arduino Uno and measure the temperature, humidity, etc. and then send those values to the Wemos D1 R1 which will show the results itself on a web page as I said earlier.
It seems that there is a way to do that using an I2C connection, but I have read many articles talking about connecting an Arduino to another Arduino using an I2C connection, but I don't know how to do that in my case (Arduino Uno and Wemos D1 R1); if there is another way to send values please tell me.

You basically have the standard communication interfaces available: I2C, SPI or Serial (UART). You can freely choose between those, depending on your requirements. For I2C: You didn't describe, what exactly your problem is with doing this. Is it, that you didn't find a tutorial specifically describing the connection for Uno and Wemos d1 r1? Thats not really a problem, since codewise you can use any I2C code, that is aimed at the ESP8266 (which is the chip on the Wemos D1 r1). For the electrical connections: Just connect the corresponding pins (marked with SDA and SCL).

Yes, my problem is that unfortunately I did not find any tutorial out there showing how to do that! If there is a blog or a website showing how to do that please send it to me! otherwise for the electrical connections I only have to connect the arduino's ( the slave sender which is connected to the pc in the port usb directly in this case ) SDA and SCL pins to the wemos d1 SDA and SCL ( the master reciever )? what about the GND & 3.3V ( since it works on 3.3v not 5v) pin of the WeMos d1?

DHT doesn"t use analog pins

You can use an analog multiplexer, greatly simplifies the code and only one micro.

I agree with @Offer that using UART is the simplest solution to connect the devices.
I just want to suggest two alternatives:

Use an external analog to digital converter IC. Using the Arduino only for analog conversion is a bit over powered. E.g. the ADS1115 has a resolution of 16 bits and there's already a library, so usage should be easy.

The ESP8266's bigger brother - the ESP32 - has several ADC pins.

The biggest advantage (beside the higher resolution) is, that you only need to write code for one device, which makes your project less complex.

The external ADCs like ADS1115 are also much more precise than what Arduino Uno has, while cheap (less than 10 USD)

As I see it, the most straight-forward way to connect 2 Arduinos is using their built-in UART (aka Serial port, TX/RX pins) communication.
There are many tutorials on this on Google, and a similar explanation can be found in this question:
Serial communication arduino mega and D1 Wemos Mini
However, there is a slight difference.
Arduino Mega has built in more than 1 hardware serial ports (I can't recall now if it's full 3 ports, or just 2), what leave one port for debug purposes, and the other - for your communication.
In your case (Arduino Uno) - you have only one serial port, that if will be used for the inter-Arduinos communication - will not be available for debug/console messages.
The solution for this is adding a Software Serial port, also highly available in tutorials over the net, here is one example:
softwareserial between arduino uno and esp8266
Enjoy your project!

Thank you <3 I will choose the I2C connection, So in my case I must work with 2 computers ( one connected with the slave sender which is Arduino Uno and the other one is master receiver which is WeMos d1 ) and the two board must be connected through i2c connection, my question is that can I work with only one computer which will be connected with UNO through the USB port and then send the values measured from the sensors to the WeMos? and if that possible sending me some code example will be much appreciated!

Have a look at my blog 'Paynters Palace' and search for posts with the 'I2C' tag - you'll find quite a bit of useful code, I think.
This project shows how to connect two Arduinos using SPI
This project shows how to connect two Arduinos using I2C and how to pass arbitrary data types between the two units


text:
What is the best way I can detect if a ping pong ball has hit the ping pong table?
The goal is to track points, which, in the case of ping pong, is how many times the ball has touched the table.
My concerns are with how light the ball and therefore the impact on the table will be.  Is this too light for something like a vibration sensor to register?
Would you imagine the sensor working better on the paddles or the table?
I'm open to other suggestions on more reliable ways to track points other than vibration.

For tracking points in ping pong I think you have to check for the ball hitting the table. Hitting the paddles does not say much (If the ball hits my paddle but then not yours, it could be my fault or yours, so the point depends more on the table). I don't think, that vibration sensing is feasable here. vibration would mean, that the whole table moves when the ball hits it. A table is normally way too heavy for that. Maybe you can cover the table with a very sensitive touch foil, though I'm absolutely not sure about that and it might be very error prone.

The best that I can think of, would be to use a camera system and let a computer track the ball in the image. Though with this you are out of the Arduino realm. That's for computers, like the Raspberry Pi.

@chrisl - Understood, I appreciate the ideas. I was trying to think out of the box and avoid the camera system route, afraid cost might start to really add up, but that might be the best solution.

one idea more: you could use a laser pointer a little strip of mirror at the sides of the table. When you carefully align it, you might be able to create a light barrier at the surface of the table (laser light bouncing back and forth between the mirrors going from the laser pointer at the one side to a fitting photodiode at the other side). The laser would have to be reflected quite (or you need to use multiple lasers diodes). That might be a bit (but not much) cheaper, than the camera thing, but might be difficult to align and the mirrors standing up at the edge might be bad for the game.

@chrisl - Funny enough I had a similar idea. Again, I'm a newbie at this so I wasn't sure of what limitations I would run into. But I thought about having some sort of motion detection or lasers running across the table along the net pointing towards the ceiling. Another funky idea was trying to detect points using sound as ping pong makes a pretty distinct noise.

The sound idea is interesting. Though I think Arduino is not really fit for that. But with a little raspberry pi (like the Zero W for 10$) and a decent microphone that might be a good way

Attach a piezo to the underside of (both) tables (similar to a contact microphone). Sound travels very well through the plywood, so just one should do. Have a look at this Arduino knock detection project

@Gerben - Finally got the sensors and started to test. I downloaded this library you recommended. But I'm getting an error when compiling. I am not great with C++ syntax. I am currently trying to run his example .ino. Any hints?
/sketch_apr24f.ino:25:44: warning: invalid conversion from 'void ()(float, long int)' to 'void ()(float, int)' [-fpermissive]
KnockDetector knockDetector(20, 5, callback);

That's a warning, not an error. You should be able to just ignore it.

By any chance, did you have the opportunity to finish your project 2/3 years ago ? I'm trying to detect the sound of a ping pong ball when it hits the table compared to when it hits anything else. How did it work on your side ?
Hope you'll see this even if it's been a long time,
Philippe

Having played ping-pong (badly) I think a microphone would be able to count ball/table impacts quite well. The 'click' sound is much higher than that of hitting the paddle, so you might be able to differentiate on that basis. You might consider a two microphone/transducer arrangement- one coupled to the table and one not touching the table. If you get a simultaneous signal on both, the ball has hit the table. If you get only one signal (from the not-touching microphone) then the ball has hit a paddle. This also gives you the option of getting some timing information.

Seconding the coupled microphone idea. It may well be possible to filter out paddle-clicks in software. The only gotcha I see is a player whose "patter" includes knocking their paddle on the table.

@JRobert I think the frequency of the 'patter knocking' would be lower/different than the 'click' of the ball impact. Much larger signal on the table coupled transducer as well.


text:
Stepper motor won't change directions!
I am driving a bipolar stepper motor with an a4988 driver using the AccelStepper library. My goal is to press a button and the motor moves CW, then another button for CCW.
I have looked at another post with a very similar issue, but the solution does not seem to apply well to the AccelStepper library, which I would really like to use given its versatility.
Currently, whichever button I press, the motor moves CCW. Any help would be greatly appreciated!
#include <AccelStepper.h>
AccelStepper stepperX(1, 3, 2);

void setup() {
  pinMode(8, INPUT)
  pinMode(9, INPUT);

  stepperX.setMaxSpeed(100.0);
  stepperX.setAcceleration(100.0);
}

int moveRight = 1000;              //arbitrarily high number
int moveLeft = -1000;              //arbitrarily low number

void loop() {
  while (digitalRead(8) == HIGH) { //when d8 button is pressed move left
    stepperX.moveTo(moveLeft);     //set move
    if (digitalRead(8) == LOW) {   //if not pressed, kill loop
      stepperX.stop();
      break;
    }
    stepperX.run();
  }

  while (digitalRead(9) == HIGH) { //when d9 button is pressed move right
    stepperX.moveTo(moveRight);    //set move
    if (digitalRead(9) == LOW) {   //if not pressed, kill loop
      stepperX.stop();
      break;
    }
    stepperX.run();
  }
}

start debugging by reducing you code to moving CW for one second ... stop for one second ... move CCW for one second ... stop for one second

You work with accelleration and absolute positions. Are you aware of that?
This Library is not made for running permanently in the same direction. It let you define a position where the movement should end, an acceleration or speed and the controller moves the motor to that position.
The run method must be called permanently, It triggers the steps. So, I put it directly into the loop() method.
The following prog should hopefully move the motor towards position 1000 if you press the 8-button, towards position -1000 if you press the 9-button and stops if both buttons are off. I have not the hardware available at the moment, you it's just blind programming. Use it as an idea.
#include <AccelStepper.h>
AccelStepper stepperX(1, 3, 2);

void setup()
{
  pinMode(8, INPUT)
  pinMode(9, INPUT);

  stepperX.setMaxSpeed(100.0);
  stepperX.setAcceleration(3.0);
}

int positivePosition = 1000;
int negativePosition = -1000;

void loop()
{
  if ( digitalRead(8) == HIGH )
  {
    stepperX.moveTo(positivePosition);
  }
  else if (digitalRead(9) == HIGH)
  {
    stepperX.moveTo(negativePosition);
  }
  else
  {
    stepperX.stop();
  }
  stepperX.run();
}


text:
Random servo movement with Arduino Uno
Recently, I have been working on a project involving 8 Tower Pro SG90 servos and an Arduino Uno. The issue I am running into is that the servos will randomly move when connected, without even receiving a signal from the Arduino.
Specifically, sometimes the servos will work perfectly and the input moves the servos fine, but then all of a sudden the servos will start twitching and moving erratically back and forth. Then I disconnect the power and plug it back in and I will sometimes work again or sometimes not.
I don't think power is the problem because I am powering the servos externally with a 5.5 V power supply which can provide 2.5 A. I also made sure to have a common ground between the Arduino and the power supply. Additionally, I don't think this is an issue of a broken servo because I have this problem with all eight. In my code, I have input pins to control the servos which are just buttons. These buttons also have pull-down resistors, so I don't think the input is the problem either. I am using the Arduino servo library.
The only other thing I can think of is external frequency interference because some of the circuitry and wiring are close together, but none of the wires are very long and I even tried putting a ferrite bead on the servo cables but to no avail.
If anyone has any ideas about a solution to my problem which I have not tried yet that would be amazing!
#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
Servo servo5;
Servo servo6;
Servo servo7;
Servo servo8;

void setup(){
  pinMode(5, INPUT);
  pinMode(4, INPUT);
  pinMode(3, INPUT);
  pinMode(2, INPUT);
  pinMode(1, INPUT);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
  servo1.attach(13);
  servo2.attach(12);
  servo3.attach(11);
  servo4.attach(10);
  servo5.attach(9);
  servo6.attach(8);
  servo7.attach(7);
  servo8.attach(6);
}

void loop(){
  if (digitalRead(5) == LOW) {
    servo1.write(120);
    delay(20);
  } else {
    servo1.write(50);
    delay(20);
  }

  if (digitalRead(4) == LOW) {
    servo2.write(110);
    delay(20);
  } else {
    servo2.write(200);
    delay(20);
  }

  if (digitalRead(3) == LOW) {
    servo3.write(120);
    delay(20);
  } else {
    servo3.write(50);
    delay(20);
  }

  if (digitalRead(2) == LOW) {
    servo4.write(110);
    delay(20);
  } else {
    servo4.write(200);
    delay(20);
  }

  if (digitalRead(1) == LOW) {
    servo5.write(120);
    delay(20);
  } else {
    servo5.write(50);
    delay(20);
  }

  if (digitalRead(A3) == LOW) {
    servo6.write(110);
    delay(20);
  } else {
    servo6.write(200);
    delay(20);
  }

  if (digitalRead(A2) == LOW) {
    servo7.write(120);
    delay(20);
  } else {
    servo7.write(50);
    delay(20);
  }

  if (digitalRead(A1) == LOW) {
    servo8.write(110);
    delay(20);
  } else {
    servo8.write(200);
    delay(20);
  }
}

Are the servos getting heated up?

No not at all. They aren't under really any load either.

Please show your code. You can edit the question, include it there and format it correctly.

As JRobert says you'll want to (accurately) debounce and maintain current state. I would also ensure that the delay is long enough for the servo to reach its end position. I would also drop the number of servos in half and see if the problem persists, but in theory eight servos should be fine on the Uno. You could also try a non-blocking delay, but I don't think that should matter. Cross-talk isn't hugely likely. I think wrapping up each button/servo combo would be a good way to get started.

You call servoX.write() repeatedly, even when no button has changed. Each call turns off interrupts briefly while the servo value is being updated. This happens, maybe 40 times/sec and may be messing up the servo timing in some non-constant way. Try only calling the servoX.write() functions once, only when its button-state has settled into a new state.
Update:

could you provide an example please

  bool prevButton5 = LOW;            // one of these for each button
    :                                // outside of the loop() func.
    :

  if(digitalRead(5) != prevButton5){  // button changed?
    prevButton5 = !prevButton5;       // save new button state
    if(preButton5 == LOW){            // (your same code from here down)
      servo1.write(120);
      delay(20);
    }
    else{
      servo1.write(50);
      delay(20);
    }
  }

Make a boolean for each button.
Wrap each of your button segments as I did for button5. Notice that your code is now executed only if the associated button has changed, so you will have many fewer servoX.write() calls.

That isn't the totally best way to do it. I made it as straightforward as I could, even though the additional code gets replicated for every button. I'd probably write a single function that manages one button and one motor, and call that function for each button / motor pair.
I also ignored the concept of switch-bounce to keep the number of changes low, but you should look it up and consider it. Switch-bounce is apparent bouncing of the switch contacts for a few milli-seconds during the change from open to closed or vice-versa, which leads to several make-break-make.....-make cycles (or the reverse) when you push or release the button. I'd probably make (or search for) a button debounce function and call it for the particular button I'm testing if I see that button has changed.
First try the "rude and crude" fix I suggested and get that working. Then if you're interested, try making one or more of the refinements.
Update:
the servos still jitter and twitch esspecailly when
I move the whole arduino and wires around.

That suggests either or both of

cross-talk;
the plug wires' connections being less than solid, especially when the wires move.

Try:

laying out the servo cables to keep them away from each other as much as possible;
wiring only a few of the servos, and in different combinations;
also try commenting out the code - or not - for those servos you disconnected in the previous step.

If it turns out to be the plug-in wires and if this project is intended to actually be used for something, I'd suggest using a screw-terminal shield on your Uno to attach the servo wires more securely.

This sounds promising but Im a little confused could you provide an example please. Thank you

Well I tried the code and it works but after a certian amount of time the servo starts jittering again. I would say that the servo jitters by less magnitude but it still jitteres and twitches. I also noticed that if I touch the 5v pin of the Arduino that the "TX" light on the Arduino turns on and the servo moves a large distance clockwise. I think the code helped but it didnt fix it yet. Any other thoughts, Thank you

I just disconnect the input pins from the buttons and the servos still jitter and twitch esspecailly when I move the whole arduino and wires around. This tells me that the problem is not in my circuitry but probably something to do with the arduino itself. Do you think it is broken or something else?

@Xander If it jitters and twitches when you "move the arduino and wires around" it sounds like an issue with the wiring.


text:
Can't make attachInterrupt() work
I have an accel+gyro sensor connected to an Arduino Zero. It's configured to output an interrupt signal on pin 2 when tapped. I can do a digitalRead() on the pin, and it does go high, so the interrupt from the sensor is triggering as expected.
However, when I try to attachInterrupt() to that pin, so I can update a Boolean variable to use later in the code, it doesn't work; the boolean variable never updates.
Am I doing something wrong in the code, or is it a hardware issue? Thank you for your help.
byte int2 = 2;
int int2_val;
volatile boolean tapcheck = false;

void interrupt_setup() {
  // set up the sensor to fire interrupts
  // ...

  pinMode(int2, INPUT);

  // attach an interrupt on pin 2
  attachInterrupt(digitalPinToInterrupt(int2), tapdummyf, RISING);
}

// double tap ISR function
void tapdummyf () {
  tapcheck = !tapcheck;
}

void interrupt_test() {
  int2_val = digitalRead(int2);
  if (int2_val == 1) {
    SerialUSB.println ("interrupt triggered ");
    int2_val = 0;
  }
}

void loop(void) {
// in loop
  interrupt_test();
    if (tapcheck){
          SerialUSB.println("dt1");
    }
}

Pin 2 has been known to be iffy in the past (see https://forum.arduino.cc/t/zero-attachinterrupt/331384). Try using a different pin

@Majenko that was indeed the issue, wow go figure. Thank you :)

Pin 2 on Arduino M0 is the only pin on headers which doesn't support external interrupt because it is mapped to SAMD21G pin PA08 which is the only pin of SAMD which can't be multiplexed as external interrupt (because it is the only pin which supports NMI).
On Arduino Zero SAMD pin PA08 is mapped to headers pin 4, which is a better choice for a board in Uno format since on Uno only pins 2 and 3 support external interrupt. Maybe there was originally an idea that NMI (non-maskable interrupt) is an even better external interrupt.
Function attachInterrupt requires a pin which support external interrupt.
It looks like you have an Arduino M0 board, not Arduino Zero.

You should use an external pulldown resistor on your input pin, 10K would probably be ideal, tapcheck will only be true on alternate interrupts as you're toggling it.

Thank you. Issue was pin 2 iffy with interrupts.


text:
I am making heated socks with adjustments by Nano and want to extend batterty life?
I want to set a temperature and have Nano turn on for 2 minutes then off for 2 minutes and repeat using the same temperature originally set and have the ability to change temperature settings and do the same.
The following sketch works along with displaying battery voltage using MIT Inventor 2 app via Bluetooth HC-05 to my Android phone (without the on/off sequence I am looking to do).
I hope to keep my feet warm but also extend the battery life.  Can you tell me what methods I should research to figure out how to do this? I have looked at millis(), blink without delay, and my own limited programming skills without success.  Thanks.
#define right 5
#define left 6

int leftval = 0;
int val=0;
int vg=0;

void setup() {
  Serial.begin(9600);
  pinMode(left, OUTPUT);
  pinMode(right, OUTPUT);
  pinMode(A0, INPUT);
}

void loop() {
  int vg = analogRead(A0);
  Serial.println(vg / 82.049, 1);
  delay(200);
  if (Serial.available() >= 2) {
    unsigned int a = Serial.read();
    unsigned int b = Serial.read();
    unsigned int val = (b * 256) + a;

    if (val >= 0 && val <= 255) {
      analogWrite(right,val);
      delay(200);
    }

    if (val >= 1000 && val <= 1255) {
      leftval = val - 1000;
      analogWrite(left, leftval);
      delay(200);
    }
  }
}

https://www.arduino.cc/en/Reference/ArduinoLowPower - however the Arduino's power consumption will pale into insignificance compared to the power consumption of your heating element.

@Majenko, why this comment? I don't see in question a request for lowering the consumption of the Nano. OP wants to turn on the heating element for 2 minutes then turn it off for 2 minutes

@Juraj Because the OP asked "have Nano turn on for 2 minutes then off for 2 minutes" - not turn the element on and off, but turn the Nano on and off. Maybe it's poor English?

With an electrical heating element powerful enough to warm your feet, the power to the heating element is hundreds or thousands of times greater than the power to your Arduino. Anything you do to reduce the power consumed by your Arduino will have no meaningful effect on your total power consumption. It's like trying to stop a drip in your faucet to save water while the main water pipe has water gushing out of a gaping hole.
Heating elements convert watts of power to calories of heat. The more watts you put in, the more heat you get.
Current • duty cycle • on-time = total power consumed AND total heat generated.
If you reduce the duty cycle to the heating element, you will reduce the power consumed, but you will also reduce the amount of heat generated.
Given that you already have the ability to vary the duty cycle to your heating element (via your analogWrite to right and left) the only meaningful way to reduce power consumption is to lower the heat setting. It looks like you already have that ability. Turn down the heat setting and have slightly colder feet, or use a higher capacity battery.
All that said, if you turn the heat setting down to 0, the heating element completely stops using power. At that point the Arudino will slowly drain your battery while your electric socks sit in your sock drawer. It would be worth putting your Arduino in ultra-low-power sleep mode (or even turning it off entirely) to avoid draining it while you're not using it.
Edit:
If you want to run the heating element on for 2 minutes, off for 2 minutes, that would give exactly the same power savings as running it at half the current power level, but constantly.
If you really want to implement the 2 minutes on, 2 minutes off approach, you will need to use millis() to keep track of the time when you last turned the elements on/off. I suggest refactoring your current code to remove delay and use millis as well.
Take a look at the "BlinkWithoutDelay" sketch (which I believe is included with the IDE, and is certainly available online) for an idea of how to handle timing things without using delay().

I don't see in question a request for lowering the consumption of the Nano. OP wants to turn on the heating element for 2 minutes then turn it off for 2 minutes

I edited my answer to address the issue of 2 minutes on, 2 minutes off vs. turning the power down, and provided a starting point for implementing it if that's what they really want to do. (As I pointed out, cycling the power on and off every 2 minutes will have exactly the same power savings as lowering the PWM duty cycle by half.)

Thank you.  The source battery for the heating element was my concern.  I had looked at millis() as an option but needed someone to confirm as a potential option.  I will study millis() and BlinkWithoutDelay.


text:
Timing push button code
I am trying to time how long button is held for. The code seems to work but with two problems:

the millis values are being read wrongly. If you hold the button for 1 second, it returns holdTime of about 3000 ms. A quick click returns holdTime of about 1000 ms.

Each successive button press adds to the previous millis value so holdTime just gets higher and higher and doesn't measure how long the button has just been pressed for

Any ideas or advice for newbie welcome!
#include <LiquidCrystal.h>

const int button1Pin = 1;  // pushbutton 1 pin
const int ledPin = 13;     // LED pin

int button1State, button2State;  // variables to hold the pushbutton states
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int startPressed = 0;
int endPressed = 0;
int holdTime = 0;

void setup() {
  // Set up the pushbutton pins to be an input:
  pinMode(button1Pin, INPUT);

  // Set up the LED pin to be an output:
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
\
}

void loop() {

  while (digitalRead(button1Pin) == LOW) {}

  button1State = digitalRead(button1Pin);
  startPressed = 0;
  endPressed =0;
  holdTime = 0;

  // if button1 or button 2 are pressed (but not both)
  if (button1State == LOW) {
    digitalWrite(ledPin, LOW);   // turn the LED on
    startPressed = millis();
  } else {
    digitalWrite(ledPin, HIGH);  // turn the LED off
    endPressed = millis();
    holdTime = endPressed - startPressed;
  }
  lcd.print("You pressed for");
  lcd.setCursor(0, 1);
  lcd.print(holdTime);
  lcd.print("ms");
  while (digitalRead(button1Pin) == LOW) {}
  lcd.clear();
  startPressed =0;
  endPressed =0;
  holdTime = 0;
}

use unsigned long to store milliseconds

You may use this library: https://arduinogetstarted.com/tutorials/arduino-button-library, you can count the time that the button is pressed down. Greetings

thank you for your advice - i will check on these things

Your source has several flaws, and one error that generates the output you see. This is the analysis of the error.
In loop() you start by waiting for the button pin to get HIGH, following by another read of the pin's state that will most probably return the same, HIGH. Note: Only if your button bounces with just the right timing, this last read will return LOW.
while (digitalRead(button1Pin) == LOW) {}
button1State = digitalRead(button1Pin);

Next you check the pin's state, and let's assume that it is HIGH. Only the else part is executed, and it calculates the holdtime as the difference of endPressed and startPressed. The former has the current value of millis(), but the latter is 0 as you initialized it.
That's why you're getting always growing values.
How to solve?
Think about the while loops, do you need them? Remember that loop() is already called repeatedly.
You may need a state variable that stores the last pin's state, so you can detect changes.

thank you for your advice - i will check on these things


text:
Powering Arduino by USB
The USB cable that came with the Arduino board is not easily recognized by the computer for selecting the appropriate COM port,
For powering the Arduino it works fine (the board will light up when plugged), so why it is not easily recognized by the computer in the device manager?

What do you mean with "is not easy"? Does is work or doesn't it work?

it requires you holding it to be detected in the device manager

Mhh, that should not happen. When something only works, when you touch it, it is often because of a grounding issue. Can you please try a different cable? Maybe the one, that you got with the Arduino, is broken.

It sounds like you're describing a board with a micro-usb connector.  Is that what you have?


text:
Checking if Arduino board works or is damaged
I have an Arduino Uno and Mega, but when I connect them to a computer with the USB they came with, there is no green light near the reset button that illuminates.
On the Uno board the pin 13 continuously flashes with red light while on the Mega board the R17 and R18 both illuminate red light but no flashing.
How do I know if the boards work or are damaged?

Does your Operating System recognize the Serial Port when you connect them? Have you tried uploading a sketch? Is there a reason to suspect they do not work? Some boards (like your Uno maybe) have a “blink” sketch installed by the manufacturer, others do not.

in device manager in my computer nothing changes when i connect the Arduino. Yes I tried  uploading files and the "port option" is gray.  no reason to suspect it's working.

If the LED 13 is blinking, that's generally a good sign. I'd check the connection and try a different cable. On Windows, you might need to install the Arduino IDE first, because that includes the serial port driver for some of the boards.

the blinking is like in every one and half seconds. the power and the led 13 lights are both red. on the device manager of my computer, communication port (com11) appear with warning sign. but in the Arduino IDE the port is still gray .

See also: https://arduino.stackexchange.com/questions/153/how-to-check-my-arduino-board-is-working-or-dead

Did you try to connect to the computer and upload a blank sketch or a blink sketch...
If the program complies and uploads successfully it is alive.
But you will have to check IO, ADC and other features separately.