text:
Arduino Serial.readString() trouble
Hello everyone I write my code and have some troubles.
When I write on in my serial monitor my buzzer condition wasn't changed.
Can you help me realize the reason. I wrote code with int type and it works with Serial.parseInt() function properly.
String ask="Please enter buzzer condition";
int buzzerPin=2;
String state;
void setup() {
  pinMode(buzzerPin,OUTPUT);
  Serial.begin(115200);

}

void loop() {
 Serial.println(ask);
 state=Serial.readString();
 Serial.println(state);
 while(Serial.available()==0){

 }
 if(state=="on"){
  digitalWrite(buzzerPin,HIGH);
 }
 if(state=="off"){
  digitalWrite(buzzerPin,LOW);
}
}

What line ending have you selected in the Serial Monitor? And why do you wait for more data to arrive after you read a string from Serial?

@chrisl thank you you really help me I find my mistake

You need to use Serial.readStringUntil('\n') instead of Serial.readString if you use the Arduino IDE's serial monitor (where a \n is added as termination character when you press enter).
Also remove that while(Serial.available()==0). It will wait as long as there are any bytes in the serial buffer and as you don't Serial.read() within the loop, the buffer will not be emptied. So, if anything is received while Serial.println(state) is called or if you send two termination characters, the program will be stuck in that loop.


text:
What is wrong with my code? (HC-SR04 using 433 mhz module);
I asked a question about this last time but I still couldn't make it work but it somehow gave me an overview about my project. Now I've created an another project that is similar to the last one, the only different thing is that I used a VirtualWire library. So I connected an HC-SR04 to an arduino board(BOARD1) with a transmitter; and a receiver to another board(BOARD2). I Followed a code in the internet similar to my project but he has an lcd display but I just want to make my sensor readings displayed in my Serial monitor what should I do?
HERE IS THE CODE FOR THE TRANSMITTER
#include <VirtualWire.h>
const int trig= 9;
const int echo= A1;

float sensorval;
float distance;
char msg[6];

void setup() {
  vw_set_tx_pin(12);
  vw_setup(2000);
  pinMode(trig,OUTPUT);
  pinMode(echo,INPUT);
  Serial.begin(9600);

}

void loop() {
  digitalWrite(trig,LOW);
   delayMicroseconds(10);
   digitalWrite(trig,HIGH);
   delayMicroseconds(10);
   digitalWrite(trig,LOW);
   delayMicroseconds(10);
   sensorval=pulseIn(echo,HIGH);

   distance = (sensorval*.0343)/2;

   Serial.print("Distance: ");
   Serial.println(distance);
   dtostrf(distance, 6,2,msg);
   vw_send((uint8_t *)msg, strlen(msg));
   vw_wait_tx();
   delay(500);

}

AND HERE IS THE CODE FOR THE RECEIVER
#include<VirtualWire.h>
#include <Wire.h>

int i;
void setup() {
  vw_set_rx_pin(12);
  vw_setup(2000);
  vw_rx_start();

}

void loop() {
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;

  if (vw_get_message(buf, &buflen)){
    Serial.print("distance is: ");
   Serial.print((char *)buf);
      Serial.print(buf[i]);
    }

  }

What is your actual problem? You could usually simply serial.print()/read() "into/from" those radio modules...

source: Stack Exchange

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

sort: votes


text:
How do I make my piezo buzzer only hum once without repetition?
I have a problem with getting my buzzer to only do the tones I programmed in once. I know I have to add some sort of code but I'm relatively new to this so I don't really know. I want it to start playing the tones I have in the code once I press the button. After that it should immediately stop, without looping everything until I press the button again. Basically I have these LEDs that light up in a row with every time I press my button and once the last LED lights up, the buzzer should play its melody. After that, I can press my button again and the whole thing starts from the beginning. If anyone could help, I'd be more than grateful!
This is my code:
#define button 3

#define LED 1
#define twoLED 2
#define threeLED 4
#define fourLED 5
#define fiveLED 6
#define sixLED 7
#define sevenLED 8
#define eightLED 9
#define nineLED 10
#define tenLED 11

int state = 0;
int old = 0;
int buttonPoll = 0;

void setup() {
  pinMode (3,INPUT);
  pinMode (11,OUTPUT);
  pinMode(LED, OUTPUT);
  pinMode(twoLED, OUTPUT);
  pinMode(threeLED, OUTPUT);
  pinMode(fourLED, OUTPUT);
  pinMode(fiveLED, OUTPUT);
  pinMode(sixLED, OUTPUT);
  pinMode(sevenLED, OUTPUT);
  pinMode(eightLED, OUTPUT);
  pinMode(nineLED, OUTPUT);
  pinMode(tenLED, OUTPUT);

  digitalWrite(LED, LOW);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

}

void loop() {

  buttonPoll = digitalRead (3);
  if (buttonPoll ==1) {
    delay (50);
    buttonPoll = digitalRead (3);
    if (buttonPoll == 0) {
      state = old + 1;
    }
  }
  else {
    delay(100);

  }

  switch (state) {
    case 1:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 2:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 3:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 4:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 5:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 6:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 7:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 8:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 9:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 10:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, HIGH);
   old = state;

       tone (11,261);
      delay(250);

      tone(11, 330);
      delay(250);

      tone(11,391.99);
      delay(250);

      tone(11,440);
      delay(250);

      tone(11, 391.995);
      delay(250);

      tone(11, 330);
      delay(250);

        }

    break;

   default:
  digitalWrite(LED, LOW);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

    old = 0;

    break;

  }
}

Enshrine the first section of the loop() code inside a while loop.
while (condition)
{
    // this code executes continually until 'condition' is true
}

In your case, the variable state changes when an active button press is recorded: use that as your condition.
while (state == old)
{
  buttonPoll = digitalRead (3);
  if (buttonPoll ==1)
  {
    delay (50);
    buttonPoll = digitalRead (3);
    if (buttonPoll == 0)
    {
      state = old + 1;
    }
  }
  else
  {
    delay(100);
  }
}

So long as state stays the same, i.e. it equals old, the code within the while loop will execute indefinitely.
NOTE: Any code outside the while loop will effectively only run once. You may find, if you expand the code, most of it lives within the while loop. If that is the case there may be better approach to consider.

Thanks so much for your help! I really appreciate it!

I'm so glad you took the effort to answer me. Unfortunately, I've tried it out and the outcome was the same as before. Thanks anyways though!

Oh! You forgot to add noTone(11); at the end of the different tones! You will also need to reset state to zero when you reset old to zero, otherwise you will get stuck in an infinite loop.

Oh my gosh thank you so much!!! You have no idea how much you've helped me! I am so grateful for your help.

Once the LEDs & Piezo sequence finishes, your code doesn't wait for the button to be pressed again. If the button is not pressed, the code doesn't wait, it merely delays for 100ms, then repeats the sequence.

Welcome to ASE :)

You have mapped the Tone function and the LED to the same Pins. So, you may have to find another pin for the buzzer (pin 0 )
I have taken code from @charlieHanson as well.
The braces for the switch statement were put in the wrong place. I have fixed it.

Have a try: The code is here
#define button 3

#define LED 1
#define twoLED 2
#define threeLED 4
#define fourLED 5
#define fiveLED 6
#define sixLED 7
#define sevenLED 8
#define eightLED 9
#define nineLED 10
#define tenLED 11

int state = 0;
int old = 0;
int buttonPoll = 0;

void setup() {
  pinMode (3, INPUT_PULLUP);
  pinMode (11, OUTPUT);
  pinMode(LED, OUTPUT);
  pinMode(twoLED, OUTPUT);
  pinMode(threeLED, OUTPUT);
  pinMode(fourLED, OUTPUT);
  pinMode(fiveLED, OUTPUT);
  pinMode(sixLED, OUTPUT);
  pinMode(sevenLED, OUTPUT);
  pinMode(eightLED, OUTPUT);
  pinMode(nineLED, OUTPUT);
  pinMode(tenLED, OUTPUT);

  digitalWrite(LED, LOW);
  digitalWrite(twoLED, LOW);
  digitalWrite(threeLED, LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

}

void loop() {

  while (state == old)
  {
    buttonPoll = digitalRead (3);
    if (buttonPoll == 1)
    {
      delay (50);
      buttonPoll = digitalRead (3);
      if (buttonPoll == 0)
      {
        state = old + 1;
      }
    }
    else
    {
      delay(100);
    }
  }

  switch (state) {
    case 1:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, LOW);
      digitalWrite(threeLED, LOW);
      digitalWrite(fourLED, LOW);
      digitalWrite(fiveLED, LOW);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 2:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, LOW);
      digitalWrite(fourLED, LOW);
      digitalWrite(fiveLED, LOW);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 3:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, LOW);
      digitalWrite(fiveLED, LOW);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 4:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, LOW);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 5:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 6:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, HIGH);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 7:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, HIGH);
      digitalWrite(sevenLED, HIGH);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 8:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, HIGH);
      digitalWrite(sevenLED, HIGH);
      digitalWrite(eightLED, HIGH);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 9:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, HIGH);
      digitalWrite(sevenLED, HIGH);
      digitalWrite(eightLED, HIGH);
      digitalWrite(nineLED, HIGH);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 10:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, HIGH);
      digitalWrite(sevenLED, HIGH);
      digitalWrite(eightLED, HIGH);
      digitalWrite(nineLED, HIGH);
      digitalWrite(tenLED, HIGH);
      old = 0;
      state = 0;

      tone (11, 261);
      delay(250);

      tone(11, 330);
      delay(250);

      tone(11, 391.99);
      delay(250);

      tone(11, 440);
      delay(250);

      tone(11, 391.995);
      delay(250);

      tone(11, 330);
      delay(250);
      noTone(11);

      break;

    default:
      digitalWrite(LED, LOW);
      digitalWrite(twoLED, LOW);
      digitalWrite(threeLED, LOW);
      digitalWrite(fourLED, LOW);
      digitalWrite(fiveLED, LOW);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);

      old = 0;

      break;

  }
}

Here is the preview :)

Here is the Arduino simulator link: https://wokwi.com/arduino/projects/297098737606459913

Wow, thanks so much!!!

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


text:
Why does the MKR WiFi 1010 LED_BUILTIN sometimes pulsate?
Sometimes the built-in LED pulsates after an upload. It could be after a failed upload but I'm not entirely sure. What does this indicate? I haven't been able to find any information about it.
It doesn't blink like in the Bliky example. It pulsates.
The led is not controlled by a Sketch. Usually this happens after a failed upload, and the previous Sketch doesn't work anymore.

maybe it is the sketch that you loaded

@jsotola Usually it's after a failed update, and my best guess is that it is, but I haven't seen it documented anywhere. It's not in the sketch.

bootloader does it while active


text:
MKR 1010 disconnects COM-port on each upload
Each time I attempt to upload to the MKR WiFi 1010 board the COM-port gets disconnected, usually at one of the following points:

Either it disconnects just after compiling/verifying. In this case the LED_BUILTIN pulsates slowly, and the USB-cable needs to be reconnected in order to try again. The next attempt usually results in 2..

Or, it disconnects after a successful upload. The next attempt to upload will always result in 1. occurring. When this happens the COM-port is still visible in Windows Device Manager but it can't be found by a Serial Monitor.

Any ideas what could be causing this or what could be done to have it stay connected? With an UNO this doesn't happen.

does it happen only with your sketch or with Blink too? Uno has external Serial chip. on MKR the MCU handles the USB so as it resets the port disconnects

This was due to using a virtual machine (VMware) which apparently doesn't handle the MKR board COM-port so well. Moving the development environment to the host solved the problem. It still disconnects the COM-port after upload but then consistently reconnects to the same COM-port and that's good enough.


text:
How can I control 2 servos separately using a joystick on an ATTiny85?
Prelude
I haven't done a lot of work in programming chips. The ATTiny85 is the first chip I've programmed, and I have the hang of the basics I think, but I don't have an in-depth understanding of it's capabilities and how to perform complex circuits with it.
The Issue
I cannot get the following to work: utilize any combination of PWM Pins with 2 Servos, and ADC (Analog to Digital Converter) Pins connected to a Joystick to control the servos using an ATTiny85.
My code works fine with an Arduino Uno R3. Porting it over to the ATTiny85 only lets me control 1 servo with 1 axis of the joystick (x or y).
As far as I can see from ATTiny85 Pinout, there are 3 PWM pins (PB0, PB1 and PB4) that I can use for the Servo data line, and 4 ADC Pins (PB2, PB3, PB4 and PB5) that I can use to send output from the joystick.
Swapping servos works fine - so I know they're not causing issues.
Swapping joystick axis works fine - so that's not it.
Running the code on the Arduino and viewing in the Serial Monitor shows that the joystick is writing correctly for both the X and Y axis - and is correctly mapping the coordinates to the serial output.
I can list out the different pins I've tried to use for the servos and the joystick - but at this point I think this is a capability issue of the ATTiny85 - and the latest pins I've tried are in the code.
I can give pictures/diagrams of my wiring for the servos and joysticks to the ATTiny85 if someone needs them, or of the wiring I use to program the ATTiny85 if it's useful.
I'm currently still debugging this issue and trying to find what's going wrong - but so far no luck. I haven't tried debugging the ATTiny85 with the serial monitor, but I've just been reprogramming it and trying different combinations of pins and code commented out. I will update the question as I discover more information.
Something strange
In my setup() code - the S1_.write(S1_Center) works, and the servo moves to the center of it's set limitations - but after that it is not responsive to the joystick. At least that tells me every time I run it that the servo is attached and able to receive a write() and so is functional - and leads me to believe that I have an issue with the Analog/Serial side of things, but I'm not sure.
Questions
Is it possible to control 2 servos with a joystick (X-axis for one servo, Y-axis for another - essentially 2 potentiometers in lieu of joystick) using an ATTiny85?
Am I using incorrect pins for the ATTiny85 to do this? ADC and PWM?
Is the issue with the code I'm using or is this a hardware constraint for the ATTiny85?
If anyone has any advice at the least it would be helpful. I know this question is to a somewhat specific scenario - but in doing my (apparently not very good) research I can only find very basic - non analog/serial ways people drive servos which I already know how to do.
Here is the code I've written that works standalone with Arduino but not with the ATTiny85.
#include <Servo_ATTinyCore.h>

Servo S1_;  // create servo object to control a servo
Servo S2_;  // create servo object to control a servo

//Joystick 1 inputs (Joystick -> Arduino)
int J1_VRx = PIN_PB3; //Attiny85 PB3 (Physical pin 2) - as per SpenceKonde ATtinyCore Github 'You cannot use the Pxn notation (ie, PB2, PA1, etc) to refer to pins ... use PIN_Pxn (ex, PIN_PB2)'
int J1_VRy = PIN_PB2; // Attiny85 PB4 (Physical pin 7)
int J1_SW = PIN_PB4; // Attiny85 PB2 (Physical pin 3)

//Joystick 1 variables
int J1_xPosition = 0;
int J1_yPosition = 0;
int J1_SW_state = 0;
boolean J1_SW_pressed = false;
//int J1_SW_state_read = 0;
//boolean buttonPressed
int J1_mapX = 0;
int J1_mapY = 0;

//Servo output (Arduino -> Servo)
int S1_Output = PIN_PB1;
int S2_Output = PIN_PB0;

//Servo Variables
int S1_Limits[2] = {0,180};  // set limitations (min/max: 0->180)
int S2_Limits[2] = {0,180};  // set limitations (min/max: 0->180)
boolean refresh = false;  // toggle refresh on/off
int S1_Degree = 0;
int S2_Degree = 0;
int S1_Speed = 0;
int S2_Speed = 0;
int S1_Speed_Limit = 2; //controls how quickly the servo can move
int S2_Speed_Limit = 2; //controls how quickly the servo can move
int speedModes[3] = {1,2,3}; //Define the speeds which can be toggled between
int speedMode = 2; //Set initial speed mode (speedModes[1] if this value is 1)

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

  //Assign Joystick 1 pins
  pinMode(J1_VRx, INPUT);
  pinMode(J1_VRy, INPUT);
  pinMode(J1_SW, INPUT_PULLUP);

  //Assign Servo pin
  S1_.attach(S1_Output);
  S2_.attach(S2_Output);

  //Get center of Servo limitations
  int S1_Center = ((S1_Limits[0]/2) + (S1_Limits[1]/2));
  int S2_Center = ((S2_Limits[0]/2) + (S2_Limits[1]/2));

  //Send servos to center
  S1_.write(S1_Center);
  S2_.write(S2_Center);

  //Set servo current degrees as at center
  S1_Degree = S1_Center;
  S2_Degree = S2_Center;

  //Set servo initial speed limit
  S1_Speed_Limit = speedModes[speedMode - 1];
  S2_Speed_Limit = speedModes[speedMode - 1];

}

void loop() {

  //Reset servo direction speeds
  S1_Speed = 0;
  S2_Speed = 0;

  //Read Joystick 1 inputs
  J1_xPosition = analogRead(J1_VRx);
  J1_yPosition = analogRead(J1_VRy);
  J1_SW_state = digitalRead(J1_SW);
  J1_mapX = map(J1_xPosition, 0, 1023, -1024, 1024); //X-position of joystick
  J1_mapY = map(J1_yPosition, 0, 1023, -1024, 1024); //Y-position of joystick

  //Fix offsets for joysticks (custom fixes because these joysticks aren't perfect :/)
  J1_mapX += 6;
  J1_mapY += 20;

  delay(10);

  boolean J1_SW_toggled = false;
  //If the button is down
  if(J1_SW_state == 0) {
    J1_SW_pressed = true;
    //Joystick button pressed
  }
  //If the button was down and is now up
  if(J1_SW_pressed == true && J1_SW_state == 1) {
    J1_SW_pressed = false;
    J1_SW_toggled = true;
    //Joystick button released
  }

  //Cycle the speed mode for servos 1, 2 and 3
  if(J1_SW_toggled) {
    J1_SW_toggled = false;
    if (speedMode != speedModes[(sizeof(speedModes) / sizeof(int)) - 1]) { //This is how to get length of speedModes array of byte type int
      speedMode += 1;
    }
    else {
      speedMode = 1;
    }
    S1_Speed_Limit = speedModes[speedMode - 1];
    S2_Speed_Limit = speedModes[speedMode - 1];
  }

  int stutterSetting = 100; //+- buffer to keep servos from moving due to imperfect readouts from joysticks

  if(J1_mapY > stutterSetting || J1_mapY < -stutterSetting) {
    S1_Speed = map(J1_mapY, -512, 512, S1_Speed_Limit, -S1_Speed_Limit);
  }
  if(J1_mapX > stutterSetting || J1_mapX < -stutterSetting) {
    S2_Speed = map(J1_mapX, -512, 512, S2_Speed_Limit, -S2_Speed_Limit);
  }

  if(S1_Speed != 0) {
    if((S1_Degree + S1_Speed) < S1_Limits[1] && (S1_Degree + S1_Speed) > S1_Limits[0]) {
      S1_Degree += S1_Speed;
      S1_.write(S1_Degree);
      delay(10);
    }
  }

  if(S2_Speed != 0) {
    if((S2_Degree + S2_Speed) < S2_Limits[1] && (S2_Degree + S2_Speed) > S2_Limits[0]) {
      S2_Degree += S2_Speed;
      S2_.write(S2_Degree);
      delay(10);
    }
  }

//  Serial.print("J1_X: ");
//  Serial.print(J1_mapX);
//  Serial.print(" | J1_Y: ");
//  Serial.print(J1_mapY);
//  Serial.print(" | S1_Speed: ");
//  Serial.print(S1_Speed);
//  Serial.print(" | S1_Degree: ");
//  Serial.print(S1_Degree);
//  Serial.print(" | S2_Speed: ");
//  Serial.print(S2_Speed);
//  Serial.print(" | S2_Degree: ");
//  Serial.println(S2_Degree);
}

You could try to pinpoint the problem by outputting the data on the ATtiny over Serial (there are TX only Software Serial libraries, which are rather small and only need one pin, which you then can connect to the PC via an Arduino). Look at the ADC measurements and the results of your calculation. It will be way easier to fix, when we know, where exactly the problem occurs


text:
Why does my stepper motor run when I open the Serial port?
For some reason my motor moves a certain amount every time I open the serial port without giving it any other instructions. It will move further by the same amount if I close and reopen the serial port. Please could someone tell me how to avoid this? I haven't had this problem before.
I am using two stepper motors with a A4988 driver each.
Here is my code so far
#include <AccelStepper.h>
#include <MultiStepper.h>

// Define pin connections
const int dirPin1 = 2;
const int stepPin1 = 3;
const int dirPin2 = 4;
const int stepPin2 = 5;

String incomingByte; // for incoming serial data

// Define motor interface type
#define motorInterfaceType 1

// Creates an instance
AccelStepper stepper1(motorInterfaceType, stepPin1, dirPin1);
AccelStepper stepper2(motorInterfaceType, stepPin2, dirPin2);

MultiStepper steppers;

void setup() {
  Serial.begin(9600);
  String excess1 = Serial.readString();
  // Configure each stepper
  stepper1.setCurrentPosition(0);
  stepper2.setCurrentPosition(0);
  stepper1.setMaxSpeed(100);
  stepper2.setMaxSpeed(100);
  stepper1.setAcceleration(10);
  stepper2.setAcceleration(10);
  // Then give them to MultiStepper to manage
  steppers.addStepper(stepper1);
  steppers.addStepper(stepper2);
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.readString();

    // say what you got:
    Serial.print("I received: ");
    //Serial.println(incomingByte, DEC);
    Serial.println(incomingByte);

    int x = incomingByte.toInt();

    long positions[2];

    positions[0] = x;
    positions[1] = 0;
    steppers.moveTo(positions);
    steppers.runSpeedToPosition();
  }
}

add serial.print() statements into your code so that you can determine how the program is progressing ... the Uno is probably resetting

That makes sense that the Uno would reset when the serial port is opened, but the motor shouldn't move if the current position is set to zero each time and there are no new instructions to move. I have included the line below to flush the serial buffer, so there shouldn't be any new instructions.
'''
String excess1 = Serial.readString();
'''

When you open or reopen the Serial port, the Arduino resets (depending on how you open it; some programs don't send the signal on DTR or RTS, which result in the reset).
My guess is, that the stepper driver reacts to the Arduino configuring its pins for the stepper. Difficult to say, what exactly happens there. To mitigate that, you can add an external pulldown resistor (assuming you have an active high stepper driver. For active low use a pullup resistor). That should keep the step line of the driver low even when its not actively driven by the Arduino.


text:
Blynk, but continue program if Blynk connection fails
I'm having an issue with Blynk.begin(auth, ssid, pass);
The problem is, when it fails to connect to the wifi, the rest of the program does not continue.
I'm using a Wemos D1 and it is also controlling some relays based on a temperature sensor.
But when there was a power outage and power comes back on, the programs should continue whether the wifi is working or not, so that relays can still be controlled by the temperature sensor reading.
What happens now is if there is a wifi issue when Wemos D1 is starting up again, the program simply stops in the void setup() at Blynk.begin(auth, ssid, pass); and the rest of the program cannot be executed.
Anyone knows how to avoid this?
Kind regards,
Peter

This has been a weakness with Blynk right along. The connect functions block and nothing else can execute until they return. In addition, some of the transmit-data functions block if your internet connection goes down or is carrying too much traffic for Blynk's traffic to complete in a timely way (how long is 'timely'?). I don't know a way around it other than possibly to make your own watchdog timer (one that can have a much longer timeout than 8 sec), and code your system to run without Blynk if it was restarted because of Blynk.

@JRobert, thank you for your comment!
At first I thought perhaps just moving the Blynk code completely out of the void setup() into the main loop, at the very end, but even then I'll get stuck if wifi fails for some reason.
I'm sure I'm missing something - not being very well experienced with anything more than the basic Blynk. Hard to imagine this is not a major issue when it comes to programs that need to execute important tasks regardless whether wifi is working or not...

this may help https://gist.github.com/mercdev/f0fea967a82fb87e92a425c5f12580af#file-blynk_wemos_d1_r2-ino-L276

https://docs.blynk.cc/#blynk-firmware-configuration-blynkconfig and the ESP8266_Standalone_Manual_IP example for Blynk library

You can try my Blynk_WM or Blynk_Async_WM library with their Blynk.begin() functions are not blocking.

Check Why using this Blynk_WiFiManager with MultiWiFi-MultiBlynk features
Why using this Blynk_WiFiManager with MultiWiFi-MultiBlynk features
You can see that the system automatically detects and connects to the best or avaiable WiFi APs and/or Blynk Servers, whenever interruption happens. This feature is very useful for systems requiring high degree of reliability.
Moreover, this Blynk.begin() is not a blocking call, so you can use it for critical functions requiring in loop().
Anyway, this is better for projects using Blynk just for GUI (graphical user interface).
In operation, if WiFi or Blynk connection is lost, Blynk.run() will try reconnecting automatically. Therefore, Blynk.run() must be called in the loop() function. Don't use:
void loop()
{
  if (Blynk.connected())
     Blynk.run();

  ...
}

just
void loop()
{
  Blynk.run();
  ...
}

It's also beneficial to search in Blynk Forum for more information and examples

Khoi, stack exchange policy requires to disclose that these are your libraries

Thanks Juraj, already update.

Yes, Blynk_WiFiManager is great.
I have modified DHT11ESP8266.ino to suit my needs and works.


text:
Arduino Uno Clone Error Compilig AVRDUDE
Can anyone please help me with this error?
Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"

Sketch uses 2964 bytes (9%) of program storage space. Maximum is 32256 bytes.

Global variables use 89 bytes (4%) of dynamic memory, leaving 1959 bytes for local variables. Maximum is 2048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xcd

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xcd

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

With enabled a in comment:
Arduino: 1.8.13 (Windows 10), Board: "Arduino Duemilanove or Diecimila, ATmega168"

C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries D:\Documents\Arduino\libraries -fqbn=arduino:avr:diecimila:cpu=atmega168 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\Mark\AppData\Local\Temp\arduino_build_293669 -warnings=none -build-cache C:\Users\Mark\AppData\Local\Temp\arduino_cache_250344 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose D:\Downloads Chrome\sketch_apr20a\sketch_apr20a.ino

C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries D:\Documents\Arduino\libraries -fqbn=arduino:avr:diecimila:cpu=atmega168 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\Mark\AppData\Local\Temp\arduino_build_293669 -warnings=none -build-cache C:\Users\Mark\AppData\Local\Temp\arduino_cache_250344 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose D:\Downloads Chrome\sketch_apr20a\sketch_apr20a.ino

Using board 'diecimila' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr

Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr

Detecting libraries used...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega168 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_DUEMILANOVE -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\standard" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE

Alternatives for Servo.h: [Servo@1.1.6 Servo@1.1.3]

ResolveLibrary(Servo.h)

  -> candidates: [Servo@1.1.6 Servo@1.1.3]

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega168 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_DUEMILANOVE -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\standard" "-ID:\\Documents\\Arduino\\libraries\\Servo\\src" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\avr\Servo.cpp

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\megaavr\Servo.cpp

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\nrf52\Servo.cpp

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\sam\Servo.cpp

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\samd\Servo.cpp

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\stm32f4\Servo.cpp

Generating function prototypes...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega168 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_DUEMILANOVE -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\standard" "-ID:\\Documents\\Arduino\\libraries\\Servo\\src" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp" -o "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\preproc\\ctags_target_for_gcc_minus_e.cpp" -DARDUINO_LIB_DISCOVERY_PHASE

"C:\\Program Files (x86)\\Arduino\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\preproc\\ctags_target_for_gcc_minus_e.cpp"

Compiling sketch...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega168 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_DUEMILANOVE -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\standard" "-ID:\\Documents\\Arduino\\libraries\\Servo\\src" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp" -o "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp.o"

Compiling libraries...

Compiling library "Servo"

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\avr\Servo.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\megaavr\Servo.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\nrf52\Servo.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\sam\Servo.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\samd\Servo.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\stm32f4\Servo.cpp.o

Compiling core...

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring_pulse.S.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\hooks.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\WInterrupts.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring_analog.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring_shift.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring_digital.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring_pulse.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\CDC.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\HardwareSerial1.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\PluggableUSB.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\HardwareSerial3.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\HardwareSerial.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\IPAddress.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\HardwareSerial2.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\HardwareSerial0.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\WMath.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\Print.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\WString.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\abi.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\Stream.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\Tone.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\new.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\USBCore.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\main.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\core.a

Archiving built core (caching) in: C:\Users\Mark\AppData\Local\Temp\arduino_cache_250344\core\core_arduino_avr_diecimila_cpu_atmega168_0c812875ac70eb4a9b385d8fb077f54c.a

Linking everything together...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega168 -o "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.elf" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\avr\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\megaavr\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\nrf52\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\sam\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\samd\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\stm32f4\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/core\\core.a" "-LC:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669" -lm

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.elf" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.eep"

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.elf" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.hex"

Multiple libraries were found for "Servo.h"

 Used: D:\Documents\Arduino\libraries\Servo

 Not used: C:\Program Files (x86)\Arduino\libraries\Servo

Using library Servo at version 1.1.3 in folder: D:\Documents\Arduino\libraries\Servo

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-size" -A "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.elf"

Sketch uses 2964 bytes (20%) of program storage space. Maximum is 14336 bytes.

Global variables use 89 bytes (8%) of dynamic memory, leaving 935 bytes for local variables. Maximum is 1024 bytes.

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega168 -carduino -PCOM4 -b19200 -D -Uflash:w:C:\Users\Mark\AppData\Local\Temp\arduino_build_293669/sketch_apr20a.ino.hex:i

avrdude: Version 6.3-20190619

         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4

         Using Programmer              : arduino

         Overriding Baud Rate          : 19200

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x62

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

'''

It might be helpful if you add the error message with verbose output during compilation as instructed at the end of the error message. Is it an original Arduino or a Clone? And possible duplicate of this post.

Sorry, didn't see the Clone in the title and can't edit my comment now.

Hi, i updated my post. Would you mind checking it again? Thanks

Did you follow the weblink in the error message? Have you checked the Stackexchange post and the answers I linked to?

Board: "Arduino Duemilanove or Diecimila, ATmega168" is not Uno. what did you select in Tools menu?

Does this answer your question? "avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program

@Juraj Already linked it, see my first comment.

i already checked the link before submitting a post here but the post's solutions do not work

Did you change the board to UNO, as @Juraj said? In the second error message the selected board is a Arduino Duemilanove or Diecimila, ATmega168, not a UNO as you said in the title and in the first error message.

More words. Explain what board you actually have, the process your going through, and make sure the listings in your question match the output of the steps described.  If it the answer is as simple as "I selected the wrong board" you can just delete your question rather than letting it float around in the system forever being of no use to anyone else.

Hi, i have an arduino uno. the reason why the board was diecimila was that i found a thread before posting here that changing the board to the latter will somehow fix the issue. I already installed a driver for the board and my computer can read it, i just am not able to upload codes within it. I tried playing with the boards and programmers but nothing works, and yes i changed it back to the default yet still, it has the same problem. Thank you


text:
Arduino web server-how to get values form URL
I’ve already searched through the internet but cannot find satisfactory answer.
Is there an easy way to get value of variable passed through an URL?
What I mean is I want to start a web server on my Arduino then call the URL like 10.0.0.1/?var1=x&var2=y from my browser and read var1 and var2 to my program.
I could also use JSON format but how to send it to my Arduino and then read it?
I use Arduino Ethernet Shield W5100.
Any ideas?

you could use a WebServer library which among other things parses the parameters


text:
Data output , ds18b20 , lcd1602 , yl-69, dht11
Good afternoon, I wonder if you could help me. I have the code but the data from the sensors is not correct. Perhaps there are some errors, could you fix them?
I apologise for my inaccurate statement. I have the task of displaying data from three sensors on the screen. I've written a sketch, but it doesn't work correctly. That is, the data from two sensors (ds18b20, yl-69) is not displayed correctly. I think the problem is with the sketch.
The data from sensor ds18b20 is constantly displayed differently, and partly depends on the data from sensor yl-69, although it should not. All sensors should work separately from each other, but give their data to the arduino
#include <DallasTemperature.h>

#include <OneWire.h>
#include <DS18B20.h>

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#include <DHT.h>

const uint8_t ds1Pin{7};            // DS18b20 будем подключать к пину D7
const uint32_t msRepTime {10000};   // DS18b20 будем опрашивать каждые 10 секунд (по факту каждые 11)
uint32_t msTemp {msRepTime};        // Объявляем счетчик для опроса DS18b20 и инициализируем его значением для моментального начала процедуры
const uint8_t simvol[8] = {B11100,B10100,B11100,B00000,B00000,B00000,B00000,B00000};
uint8_t ds1Qty {1};                 // Количество датчиков DS18b20 на пине (не более 3-х). Если больше одного, значения будут усредняться
int8_t  ds1Temp {0};                // Собственно, значение температуры по Цельсию от DS18b20
uint8_t ds1DS[3][8];                // Адреса положу пока здесь. Если кому не лень, их нужно убрать из глобальной ОВ, как и количество датчиков

const uint8_t DHTPin{8};            // DHT будем подключать к пину D8
float dhtTemp {0};                  // DHT значение температуры
float dhtHum {0};                   // DHT значение влажности
const uint32_t msDhtTime {5017};    // DHT будем опрашивать каждые 5+ секунд. "Кривое" значение, чтобы не пересекаться по времени с опросом DS
uint32_t msDht {msDhtTime};         // Объявляем счетчик для опроса DHT и инициализируем его значением для моментального начала процедуры

const uint8_t ylPin{14};            // YL будем подключать к пину A0(14). ВНИМАНИЕ: подключение аналогового выхода датчика!
uint16_t ylVal{0};                  // Переменная для показаний датчика влажности YL
const uint32_t msYlTime {100};      // YL будем опрашивать каждые 0.1 секунд, чтобы МК хоть чем-то был занят в цикле))
uint32_t msYl {0};                  // Объявляем счетчик для опроса YL-69

const uint32_t msPageExpo {5000};   // Устанавливаем по 5 секунд на отображение каждой страницы
uint32_t msPage {0};                // Объявили счетчик для экрана

LiquidCrystal_I2C lcd(0x27, 16, 2);
DHT dht(DHTPin, DHT11);
OneWire oneWire(DS18B20);

void setup() {
  Serial.begin(9600);     // Скорость должна соответствовать настройкам монитора порта
  lcd.init();
  lcd.backlight();
  dht.begin();
  searchSensors();          // Запускаем первоначальный поиск датчиков DS18b20 на пине
}

void loop() {

  if (millis() - msTemp > msRepTime)  updateTemp();       // Опрашиваем температуру DS18b20 с частотой msRepTime
  if (millis() - msDht > msDhtTime)   runDht();           // Опрашиваем DHT
  if (millis() - msYl > msYlTime)     runYl();            // Опрашиваем YL-69
  if (millis() - msPage > msPageExpo) updatePage();       // Листаем страницы

}

//**************  Секция экранчег  ****************************
void updatePage(){                       // Листаем страницы на экранчике
  static uint8_t page {0};
//  Первая страница
  if (page == 0){
    lcd.setCursor(0,0);
    lcd.print("temp water:    ");
    lcd.setCursor(0,1);
    lcd.print((int8_t)ds1Temp);
    lcd.setCursor(3,1);
    lcd.print("C   ");
    msPage = millis();
    page++;
    return;
  }
//  Вторая страница
  if (page == 1){
    lcd.setCursor(0,0);
    lcd.print("temp air:         ");
    lcd.setCursor(0,1);
    lcd.print((int8_t)dhtTemp);
    lcd.setCursor(2,1);
    lcd.print("C   ");
    msPage = millis();
    page++;
    return;
  }
//  Третья страница
  if (page == 2){
    lcd.setCursor(0,0);
    lcd.print("hum air:         ");
    lcd.setCursor(0,1);
    lcd.print((uint8_t)dhtHum);
    lcd.setCursor(2,1);
    lcd.print("%   ");
    msPage = millis();
    page++;
    return;
  }
// Последняя страница
  if (page == 3){
    lcd.setCursor(0,0);
    lcd.print("hum earth:         ");
    lcd.setCursor(0,1);
    lcd.print((uint16_t)ylVal);
    lcd.setCursor(3,1);
    lcd.print("%   ");
    msPage = millis();
    page = 0;
    return;
  }
}

//**************  Секция YL-69  ****************************
void runYl(void){
  ylVal = analogRead(ylPin);; //Измеряем влажность. Маппинг пишем сами, если надо
  msYl = millis();
}

//**************  Секция DHT  ****************************
void runDht(void){
  dhtHum = dht.readHumidity();          //Измеряем влажность
  dhtTemp = dht.readTemperature();      //Измеряем температуру
  msDht = millis();
}

//**************  Секция DS18b20  ****************************
void updateTemp(){                       // Основная процедура обновления температурных данных со всех датчиков
  static uint8_t stage {0};
//  Первый этап. Отправка запросов на конвертацию
  if (stage == 0){
    if (ds1Qty) requestSensor(ds1Pin);
    stage++;
    msTemp = millis() - msRepTime + 800;    // 0.75 секунды требуется датчику для осуществления конвертации на максимальном разрешении
    return;
  }
// Второй этап. Чтение показаний
  if (stage == 1){
    if (ds1Qty) readSensor(&ds1Temp, ds1Pin, ds1DS, ds1Qty);
    msTemp = millis();
    stage = 0;
    return;
  }
}

void readSensor(int8_t* t, uint8_t pin, void* buf, uint8_t qt){       // Чтение температуры с датчика ds18b20
  OneWire ds(pin);
  uint8_t addr[8];
  uint8_t data[9];
  float temp[3];
  uint8_t qty {0};
  for (uint8_t c {0}; c < qt; c++){
    for(uint8_t i {0}; i<8 ;i++) addr[i] = *((uint8_t*)buf+c*8+i);
    ds.reset(); ds.select(addr); ds.write(0xBE);
    for (uint8_t d {0}; d<9; d++) data[d] = ds.read();
    int16_t raw = (data[1] << 8) | data[0];
    raw = raw & ~1;
    temp[qty++] = raw / 16.0;
  }
  float tmp {0};
  for (uint8_t i {0}; i<qty; i++) tmp+= temp[i];
  *t = round(tmp/qty);
  Serial.print("Температура пин "); Serial.print(pin); Serial.print(" : "); Serial.println(*t);
}

void requestSensor(uint8_t pin){          // Отправка запроса на конвертацию ds18b20
  OneWire ds(pin);
  ds.reset();
  ds.skip();
  ds.write(0x44,0);
}

void searchSensors(){                          // Поиск датчиков на всех линиях
  ds1Qty =   src(ds1DS, ds1Pin);
}

uint8_t src(void * adr, uint8_t pin){      // Вспомогательная функция для поиска на одной шине. Возвращает количество найденных датчиков
  if (pin == 0) return 0;
  OneWire ds(pin);
  uint8_t newAddr[8]{0};
  uint8_t count {0};
  ds.reset_search();
  delay(5);
  while (ds.search(newAddr) && count <3){
    if (ds.crc8(newAddr, 7) == newAddr[7]){
       for (uint8_t i{0}; i<8; i++) *((uint8_t*)adr + count * 8 + i) = newAddr[i];
       count++;
    }
  }
  return count;
}

Is the compiler giving you any errors? Then you absolutely need to include them in your question. Or is the code having unexpectedly? Then you need to describe, what you expected and how the code actually behaves. I don't really want to read a long code and searching for errors, that might or might not be there. Please test yourself and then you can provide the needed information for us to help you

Please divide your program into small chunks and test them individually. If you have figured out, which part is not working as indended, I am happy to help on that small part. Also please read: https://arduino.stackexchange.com/help/how-to-ask

how do you know that data from sensors is not correct? ... what are you expecting to see? ... what are you seeing? .... which sensors are affected? .... how are the sensors connected? .... please add all information to your question ... do not put in comments


text:
why can Arduino variables of int type contain a value such as A2
How come the following statement is true:
int inputPin = A2;

I thought int variables can only hold integer numbers. Is the A just a representation of a number?
Thanks for any help

Normally, I'd vote to close this, as it's pretty simple and really language related and there's an endless pile of those questions.  But, I've seen this question come up countless times in conversation with new Arduino users in almost exactly this form, often citing A0 instead.  So, I'm voting to leave it open.

It would probably be better written "following statement is valid" or something to that effect, as opposed to "true".

You are correct. A2 is just a number (like everything in a microcontroller). We can look at the corresponding part in pins_arduino.h (a file defined in the variants folder of your used core and of your used board, for me: ~/arduino-1.8.9/hardware/arduino/avr/variants/standard/pins_arduino.h):
#define PIN_A0   (14)
#define PIN_A1   (15)
#define PIN_A2   (16)
#define PIN_A3   (17)
#define PIN_A4   (18)
#define PIN_A5   (19)
#define PIN_A6   (20)
#define PIN_A7   (21)

static const uint8_t A0 = PIN_A0;
static const uint8_t A1 = PIN_A1;
static const uint8_t A2 = PIN_A2;
static const uint8_t A3 = PIN_A3;
static const uint8_t A4 = PIN_A4;
static const uint8_t A5 = PIN_A5;
static const uint8_t A6 = PIN_A6;
static const uint8_t A7 = PIN_A7;

So here the core first defines the macro PIN_A2 as 16 (which is the pin number of that pin) and then it declares a static constant A2 with PIN_A2. So A2 is just the pin number of that pin, 16 in this case.
This is done to make the code more readable. The analog pins are marked with A0 to A7, so it is good to also be able to refer to that with these names. If you wanted, you could also use the pin number directly. But that wouldn't be as easy to read.

It makes no difference to the answer whatsoever, but I'm surprised you're using version 1.8.9.

I'm not using it very often, thus haven't really bothered in updating. But you are right, I should really do an update XD

The value of the symbol 'A2' is an integer - it is an Arduino pin number. For an Uno, it is equal to 16. Are you maybe confusing the pin number, A2, with the value read from A/D channel 2? That would be the value returned by analogRead(A2) or analogRead(PIN_A2) as it has been #define'd. And even then, that value is also an integer between 0 and 1023, which represents the voltage on the pin, 0 representing 0v or Ground, and 1024 representing the reference voltage (therefore, 1023 represents any voltage that is greater or equal to ((1023/1024) * Vref).


text:
Can i use PL2303 USB to TTL Serial Converter Module send keystrokes using Arduino nano?
If I can, which library to use (an example code will be great).
Here is the module:

Like Majenko said in their answer.  If you don't want to get a board with native USB support for whatever reason, and want to use your Nano, the easiest thing is to have the Nano pretend to be a PS/2 keyboard, at which point you're likely using a PS/2 to USB adapter, rather than a logic level serial to USB adapter.  Odds are good that you can acquire a USB to PS/2 adapter locally from someone that has old computer junk, assuming you don't just happen to have one yourself.

it may be possible ... research FreePIE ... https://andersmalmgren.github.io/FreePIE/

@timemage, how?

@Juraj, you want me to write an article in the comments about how to make a Nano behave like a PS/2 keyboard?

@timemage, more about how to convert it to USB signal. but now I realized what you mean.

@Juraj, in my comment "PS/2 to USB adapter" refers to this sort of thing, in case that wasn't clear.

No. That is serial. Just like every other USB to TTL Serial converter. The clue is in the name.
You need an Arduino with a dedicated native USB interface, like those based on the ATMega32U4 chip.
Or dedicated software on the PC that will read serial data and emulate keypresses (which is outside the scope of this website).

Is there any module that lets me do this

I posted something to that effect in a comment on your question itself.  Had it been worded differently, I might have put it as an answer, or part of one.  Now that you have an answer addressing what you actually asked, you should avoid changing the nature of the question though.

@WHITE_DEVIL yes there is. It's called an Arduino based around the atmega32u4.


text:
Basic doubt regarding encoders with Arduino
I created a program that measures the pulses set out by the encoder (part of the dc motor with encoder inbuilt), and uses the ppr value (pulses per rotation) to calculate the rotations per minute (rpm)
However, the serial monitor continuously shows 0 for the variable "pulsecount", that maintains the total pulses sent.

code:
float ppr=512.0;
int encpin=3;
volatile long pulsecount=0;
float revs;
float rps;
float rpm;
unsigned long time;

void setup()
{
  pinMode(encpin,INPUT);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(encpin),function,RISING); //when pulse is detected
                                           //interrupt triggered,
                                           //function callled
}
void function(){
  pulsecount+=1;
}

void loop()
{
 revs= pulsecount/ppr ;
 time=millis()/1000;
 rps=revs/time ;
 rpm=revs*60;
 Serial.println(pulsecount);
}

Why are you defining function() inbetween setup() and loop()? If it compiles it might be OK, but I have never seen that... Try to print every value to Serial Monitor and maybe you can see the variable which causes this behavior.

What happens if you use INPUT_PULLUP rather than INPUT?

You code counts pulses just fine when tested here.
Fan/motor tachometer outputs and encoders frequently are set to switch your signal contact to ground, either with a transistor or mechanically.  When the ground contact is not being made, the signal connection is floating and not reliably HIGH.  So, you need a pullup resistor on the pin, just like you do for a typical push button switch configured to switch to ground.
My comment on the question:

What happens if you use INPUT_PULLUP rather than INPUT?

was referring to doing this in your code:
pinMode(encpin, INPUT_PULLUP);

At higher frequencies, higher RPM, you may need to use an external resistor to get a lower resistance value than the 20k-50k of the internal pullup resistor that INPUT_PULLUP enables.
It is best to turn off interrupts when you retrieve your volatile pulse counter variable so that there's no tearing of the value where the ISR interrupts your code mid-read and updates the latter half of the value.
e.g.:
// Note I've switched your pulsecount variable
//  to unsigned long for this example.
unsigned long get_pulsecount() {
  noInterrupts();
  const auto r = pulsecount;
  interrupts();
  return r;
}

Note you can probably avoid float usage altogether, and should if you can.

It is hard to find the error in these TinkerCad examples, because I do not know where to find the datasheet of the components used there and I am never sure, what am I debugging, the program or Tinkercad?
Anyhow, the encoder simulated there needs to be connected with a pull-up resistor. Arduino has a built-in pullup and you can activate via the pinmode() function:
void setup()
{
  pinMode(encpin,INPUT_PULLUP); //  before here was pinMode(encpin,INPUT);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(encpin),function,RISING); //when pulse is detected
                                           //interrupt triggered,
                                           //function callled
}

But notice: your types are all over the place and I expect that you get some bugs due to this. Avoid to divide float and int variables without converting, especially this can cause trouble, because you might divide by 0:
 time=millis()/1000;
 rps=revs/time ;

Also it is a long shot to have basic doubts regarding encoders and arduino, just because some code does not work. Many people are using encoders all the time and countless libraries of encoders have been published for arduino.


text:
How to implement Arduino NANO as a RS-232 to USB adapter (Or do I need a Arduino Mega?) For 3D printer comms
I have a PC upstairs running my 3D printing slicer program (Simplify 3D). In the basement, I have several USB-enable 3D printers. My PC upstairs has a USB-to-RS-232 serial adapter. The serial side of that USB-to-Serial adapter connects to the Serial port of a Moxa Nport 6150 RS232-to-Ethernet protocol adapter. I get those Moxa devices for free when they break at work and then fix them for a couple of dollars.
The other side of the Moxa connects to my home computer network router. In the basement I can plug another Moxa into an ethernet cable on my home network and the serial RS232 output I need to connect to the Micro-USB jack of the 3D printer. How can I use an Arduino Nano (or Uno or Mega if required) to convert the RS232 data to the USB input of my 3D printer?
So I have PC->(RS-232)->[MOXA(RS-232)->Moxa(Ethernet)]->Router->[Moxa(Ethernet)->Moxa(RS-232)]->[Arduino(RS-232)->Arduino(USB)]->3D Printer(USB)... How can I get the Arduino to do that function? Items within [ and ] brackets are single devices performing a protocol conversion.
I know people use Raspberry Pi's and a program called OctoPrint to remotely control their 3D printers but I get the Moxas for free and Uno's or Nanos are dirt cheap. RPi's are more expensive and for several 3D printers it can start adding up. Any ideas?

The Nano can't take RS-232: it takes logic-level serial. You will need some kind of level shifter, like the MAX232 chips.

Hmm.. something like that MAX232 chip is the part I replace in the MOXA's to fix them. If I took the serial output of the Moxa through a MAX232 chip, then the TTL serial to the RX and TX of the Arduino... that's where I get lost.

Or can I just connect the RX and TX TTL data from the MAX232 and connect it directly to the Micro-USB jack? I found a MicroUSB pinout diagram but it shows the data as "D+" and "D-". Not sure how that correlates to TX and RX. Also, somewhere I am going to have to set the baud rate of whatever does the conversion to the 115200 speed of my 3D printer. Thats also why I think I need a Microcontroller? But I can set the serial baud rate on the Printer-side Moxa to 115200, then send that RS232 to the MAX232 but now I need a UART chip to convert the RX and Tx to D+ and D- ? Is that right?

RX and TX directly to D+ and D- is a no go. Different protocol, different voltage levels and different functions of the pins.

This depends entirely on what protocol your 3D printer expects over its USB port.  When you plug in your 3D printer, what does it appear as?  A native USB device with its own device driver?  As a USB/RS-232 UART that presents a virtual COM port?  If the 3D printer is not controlled by RS-232 then this is hopeless, and it's hopeless anyway because it has its UART already hidden behind a USB converter, so you would need to send the USB frames and not the raw RS-232 data.  Needs more info.

If the printer is an RS-232 protocol with a built-in USB converter, then one solution would be to open up the 3D printer, hack the RS-232 signal off of the UART, and connect the moxa directly to the printer's internal RS-232 lines.  The arduino RS-232/USB converter only works one way - the USB is the host side, not the device side.

Its not as easy as you think. An Arduino will not be enough for connecting the USB of the 3D printer. The USB protocol is strictly divided into slaves and masters. A USB(us) has exactly one master, which totally controls, what the slave can do. The slave itself cannot do much of its own.
Your 3D printer is a USB slave device. That enables a USB master (like a computer) to control it. The Arduino is also a USB slave device. If you connect both, you have a USB connection without a master. Nothing will happen. So you need to implement a USB master on the Arduino, which can handle the UART communication; all in software. That is generally possible, but I wouldn't recommend it. Also you definitely need extra hardware, because D+ and D- on USB are also electrically totally different from the TTL lines RX and TX (and also from the RS232 lines). They work differentially. So you need extra hardware to do that.
The easiest way with an Arduino would be to buy a USB host shield. With that you may be able to build, what you want.
But I would dispute, if this really makes sense. The cheapest USB host shield for Arduino, that I could find at amazon is around 10€, plus the price for an Arduino and the hassle of getting it all to work. A RaspberryPi Zero W only costs 10€. If you don't want to use wifi, you can add a USB to Ethernet adapter. And depending on the used software and its installation you might even be able to handle multiple printers with only one Pi (I use the Repertier Server, which has the ability to control multiple printers, I think). (Though depending on the number of printers and the resulting load you might wanna step up the game to a full Pi4)

There might be an additional way, depending on your printers. The printers microcontroller board might break the TX and RX pins out for you. Then you could connect the Arduino to them, no need for USB in that case. But that might not be an option. If the used microcontroller has a direct USB interface, there are no RX and TX pins to break out.

The Nano, like the Uno, has an onboard serial ↔ USB converter. If you
can get a logic level serial from the Moxa, then you can use the Nano to
convert that to USB:

Load a do-nothing sketch in the Nano
Connect the Moxa TX to the Nano's Tx through a 1 kΩ resistor, and the
Moxa RX to the Nano's RX.

Yes, the second step looks backwards. The reason is that the labels RX
and TX refer to the ATmega328P that runs your sketches on the Nano.
Internally, the pin labeled RX is connected (through a resistor) to the
TX pin of the serial ↔ USB converter, and this is thus the pin you want
to connect the Moxa's RX. And similarly for the pin label TX (it's the
RX of the onboard converter).
Step 1 is important because you do not want the 328P to open its
serial port. The resistor is needed for the short time when the 328P is
running the bootloader, and has its serial port open.

+1 Jumping RESET to GND is typically what I do, although putting the do-nothing sketch on there is a good idea also.  With it held in reset, the bootloader doesn't get an opportunity to play with the serial lines either.

That's great! So I already have some of these RS232 to TTL converter boards I bought from Amazon: https://smile.amazon.com/gp/product/B07PFB4MHR/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1 I can then take the TX from that converter board to the TX of the Nano (running something like the Blink sketch) and the RX from the converter board to the RX of the Nano and then connect the Mini-USB of the NANO to the Micro USB of my 3D printer.

@ABNormal connect the Mini-USB of the NANO to the Micro USB of my 3D printer. No, that can never work.  USB is a host-driven protocol.  You can't just connect two devices together at the business end without a host.

There's not enough information to provide a general solution at this time. As chrisl rightly says, the 3D printers are expecting a connection from a host. That host connection depends on whether the USB-serial interface inside the printer is supported. These are typically FTDI or WCH (QinHeng) chips, and would need the appropriate system driver for each type. This would be hard to implement on a USB host shield for Arduino.
Most 3d printers are, in essence, an Arduino inside. The typical 8-bit controller on the vast majority of 3d printers uses a very similar ATMega microcontroller. Some newer machines use 32-bit ARM microcontrollers, which are typically 3.3 V logic compared to the Arduino's (typical) 5 V. To add a standard RS-232 port you'd need to find the RX, TX, GND and Vcc points on each printer controller board and connect the right pins of your RS-232 to TTL converter boards to those points. This would bypass the USB ports on the printers entirely.
You might experience issues with flow control and buffering with multiple ports sending from one PC and Serial-Network-Serial latency. Marlin-style Gcode printers (= most filament printers that aren't Makerbot or Flashforge, approximately) don't use flow control: the printer sends back ok when it's ready for the next command. If your serial ports send data too slowly, the printer will pause and print quality may suffer. 3d printers don't need a really fast serial connections (under 20 kbit/s per printer, if using Gcode) but they need the data when they're ready to print.
OctoPrint can be quite an expensive option. The minimum supported platform is a Raspberry Pi 3b+ (+ power supply, SD card, USB cable, case, ...) dedicated to each printer. While you can run a very cut-down OctoPrint on a Raspberry Pi Zero, the author does not recommend it, and you have to click through an Unsupported Configuration: Use at your own risk dialogue.

If we take the following configuration PC(only pseudo serial like by old laptops without USB) -> Arduino -> USB printer,
than all what is important is Arduino 'xxx.ino' pseudo ;) code:
//do all necessary setups
  initialize
(((( loop
//pc-->arduino
    oh, some bytes on serial     //Nano detect some activity on serial port
    I'm dividing that in commands,status and cargo. //Nano parse this stream and determine what to do with what.
    huh, now repack that in USB protocol and send out // most probably this are data an commands to sent to printer over USB with appropriate protocol
//Arduino-->printer
    hey printer, here is some feed for you //Nano announce upcoming data event
//printer --> Arduino
    thanks, want more input    // printer certainly react with acknowledge, (success or error) and request or not next data
//Arduino --> PC
    let's send some more, he like it //Nano request next data package from sender PC
))) //end loop         and repeat until all done

But somehow more detailed.
I hope you understand that this id ;) "humor/joke/nonsense" pseudo code that show only organization of data flow how to make some functions/procedures. The concrete usable code is up to you.
Once more, it shows only that is possible to do it with Arduino.
It is certainly needed more than 5 minutes to write the comment.
I'm not sure if CR/LF come through correctly but anyone that can write code  in C would be able to properly format this text and may be start filling the sections with real code

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Welcome to Stack Exchange! It will probably be more helpful, and get you more reputation, if you answer more recent questions. I imagine this question, from April 2021, is no longer particularly relevant to the OP.


text:
EtherCard library without TCP
I have connected some sensors to an Arduino Uno (but the final code should run on a Pro-Mini) with an ENC28J60 shield. The sensor code works fine - until I add EtherCard. I tried UIPEthernet first, but it's even worse. The problem is the memory footprint. The ethernet libraries are consuming so much memory that random malfunctions do occur.
So I was thinking about removing TCP from the EtherCard library, because I don't need it anyway. I only need IP, ARP, UDP, and based on that DHCP, DNS and NTP.
Has someone already done this?
Is there a stripped-down library?
The file tcp.cpp is pretty big (the biggest in this lib). Is it safe to remove all methods with "tcp" in their name?
Or is there a better solution for this situation?

try my EthernetENC with custom settings https://github.com/jandrassy/EthernetENC/wiki/Settings

@Juraj: Thanks. That looks promising.

Setting uno.build.extra_flags= -DUIP_CONF_MAX_CONNECTIONS=0 in "boards.txt" in the arduino IDE folder reduced program memory usage by 2442 bytes and dynamic memory usage by 290 bytes. BTW changing the #define in "uipethernet-conf.h" has had no effect. However, thank you for the great work :-)

My EthernetENC library based on the original UIPEthernet library by Norbert Truchsess has settings to balance performance and memory usage. These settings are in utility/uipethernet-conf.h file or can be specified as -D parameters for compilation.
UIP_CONF_MAX_CONNECTIONS is a maximum number of connected EthernetClient connections. The default value s 4. You can set it to 0 if you don't use EthernetClient TCp connections. It will save a lot of dynamic memory.
Arduino IDE doesn't have the possibility to set defines for a sketch (For example Sloeber has it). As some workaround to set the defines for different boards for Arduino IDE, you can create a file boards.local.txt next to boards.txt file in hardware package. Set build.extra_flags for individual boards.
comment by OP:

Setting uno.build.extra_flags= -DUIP_CONF_MAX_CONNECTIONS=0 in "boards.txt" in the arduino IDE folder reduced program memory usage by 2442 bytes and dynamic memory usage by 290 bytes.


text:
ESP32-S2 Brownout Detector Randomly Triggered in Deep Sleep
I have thoroughly searched for answers on this over the past couple weeks, and have not been able to find a solution for Arduino.
I'm using an ESP32-S2-Saola-1M Dev board that needs to store a sensor reading in RTC memory, go to sleep for 5 min, and then wake up again and store another reading. Every few hours, it shares its data and starts over.
The issue I'm having is that about 2/3 of the devices I have will randomly wakeup with a POWERON event instead of from the timer, and all of the RTC memory is lost. From searching online, this seems to be a hardware issue that causes the brownout detector to trigger incorrectly.
The accepted solution in the esp-idf is turning off the brownout detector , but this doesn't seem to be implemented in the ESP32 Arduino core, and using code I've found for turning off the brownout detector in Arduino causes constant brownouts rather than turning the detector off.
There seem to be solutions if I switch my development environment, but I'd rather not do that at this point in development. Has anyone had luck fixing this issue in Arduino?


text:
Can someone help me figure out why only one wheel is spinning?
I am attempting to use a code which I have posted below for two wheels. However, when connected to power, only one wheel spins. I am using a 9V battery which is what was suggested so I am not sure why only one wheel spins. When both wheels are connected, the wheel that was originally working stopped spinning.
#include <SPI.h>      //SPI library for communication with the nRF24L01+
#include "RF24.h"  //The main library of the nRF24L01+
#include "Wire.h"

RF24 radio (8, 9); // CE,CSN

//Create a pipe addresses for  communication
const uint64_t pipe = 0xE8E8F0F0E1LL;

struct package
{
  int X = 1;
  int Y = 1;
};

typedef struct package Package;
Package pos;

int buttonState;
int spinnerState = false ;
int motora_1 = 3;
int motora_2 = 4;
int motorb_1 = 5;
int motorb_2 = 6;
int spinner = 2;

void setup()
{
  Serial.begin(9600);
  radio.begin();                    //Start the nRF24 communicate
  radio.openReadingPipe(1, pipe);   //Sets the address of the transmitter to which the program will receive data.
  radio.startListening();
  pinMode(motora_1, OUTPUT);
  pinMode(motora_2, OUTPUT);
  pinMode(motorb_1, OUTPUT);
  pinMode(motorb_2, OUTPUT);
  pinMode(spinner, OUTPUT);
  digitalWrite(spinner, LOW);
  delay(100);
}

void loop()
{

  if (radio.available()) {
    radio.read(&pos, sizeof(pos));
    radio.read(&buttonState, sizeof(buttonState));
    Serial.print("X:");
    Serial.print(pos.X);
    Serial.print("      Y");
    Serial.print(pos.Y);
    Serial.print("      buttonState");
    Serial.println(buttonState);
  }

  int xAxis = pos.X;
  int yAxis = pos.Y;
  int forward = map(yAxis, 570, 1024, 0, 255);
  int backward = map(yAxis, 480, 0, 0, 255);
  int right = map(xAxis, 570, 1024, 0, 255);
  int left = map(xAxis, 480, 0, 0, 255);

  if (yAxis > 570) {          // Move Forward
    // Set Motor A forward
    analogWrite(motora_1, forward);
    analogWrite(motora_2, 0);
    // Set Motor B forward
    analogWrite(motorb_1, forward);
    analogWrite(motorb_2, 0);
  } else if (yAxis < 480) {                     //Move Backward
    // Set Motor A backward
    analogWrite(motora_1, 0);
    analogWrite(motora_2, backward);
    // Set Motor B backward
    analogWrite(motorb_1, 0);
    analogWrite(motorb_2, backward);
  } else if (xAxis > 570) {                     // Move Right
    // Set Motor A forward
    analogWrite(motora_1, right);
    analogWrite(motora_2, 0);
    // Set Motor B stop
    analogWrite(motorb_1, 0);
    analogWrite(motorb_2, 0);
  } else if (xAxis < 480) {                     // Move Left
    // Set Motor A stop
    analogWrite(motora_1, 0);
    analogWrite(motora_2, 0);
    // Set Motor B foward
    analogWrite(motorb_1, left);
    analogWrite(motorb_2, 0);
  } else  {     //stop
    // Set Motor A stop
    analogWrite(motora_1, 0);
    analogWrite(motora_2, 0);
    // Set Motor B stop
    analogWrite(motorb_1, 0);
    analogWrite(motorb_2, 0);
  }

  if (buttonState == 0 ) {
    spinnerState = ! spinnerState;
    delay(50);
  }

  if (spinnerState == true) {
    digitalWrite(spinner, HIGH);    //turn On spinner
    delay(100);
  } else {
    digitalWrite(spinner, LOW);      //turn Off spinner
    delay(100);
  }

}

With "9V battery" do you mean the standard 9V block batteries, that are often used in smoke detectors? If yes, please try to use a different power source. These batteries are made for very low power applications, not for driving motors

A connection diagram would be nice!

You have int motora_2 = 4;  and analogWrite(motora_2, backward); and an arduino-uno tag.  Pin 4 on the Arduino UNO is not a PWM capable pin.  analogWrite basically becomes digitalWrite on a 0x80 threshold when you use it with non-PWM pins.  So you have at least one problem in your sketch that can't be identified as the problem without a better description of the problem.

Firstly, the 9V batery is going to struggle with driving two motors. Change this 9V battery out with another power source.
As @timemage points out in his comment, you are using a PWM command on a non-PWM pin. For the Arduino Uno, the PWM pins are: 3, 5, 6, 9, 10, 11. Move the wiring and change the code so that it is using pin 9, 10 or 11 instead of pin 4.
It sounds like you are trying to test your hardware setup and your firmware at the same time. It is much easier to test your hardware first and make sure that works as expected before testing your firmware. I suggest writing a simpler program (the simpler the better) that just drives the motors full forward - one at a time and then together. Verify that it works and then change your test program so the motors spin in (full) reverse. Then change your test program so it changes the speed of the motors. Then with known working hardware test your firmware.

Yeah, it may be helpful for them to break the code down into more functions to make it more testable also.


text:
Millis timer question
Trying to figure out how to do this in millis. So right now the code works just fine, plays mp3_play(2) while a push button is closed then plays mp3_play(1) when its open. Lets say I want mp3_play(2) to play while the push button closed but after 4 seconds if the button is still closed another audio file will be triggered to play. Cant figure that one out.
thanks
Jason
void fire(){

  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {

    if (reading != buttonState) {
      buttonState = reading;

      if (buttonState == HIGH) {
        mp3_play (1); //power down sound
      }

      if (buttonState == LOW) {
        mp3_play (2);  // fire sound
      }

    }
  }
  lastButtonState = reading;
}

Do you want to keep playing the other audio if it is past 4 seconds? or just once?

Hi, if the 3rd audio file could play once, that would be great. Thanks

You have to keep track of time once a button is pressed (LOW). So buttonLowTime is initialized every time you press the button. In the if logic, you first check if the buttonstate is LOW and if the said time has been passed.
But you also mentioned you want to play the audio once. So you need to keep track if you already played the audio. So, a flag, timeoutAudioPlayed has been created to keep track of that. So, now, the 3rd audio will only play if:

The button is pressed
and is pressed for more than said time (BUTTON_LOW_TIME_MAX)
and if the audio hasn't been played.

void fire()
{
  static int buttonLowTime = 0; <-------------------
  static bool timeoutAudioPlayed = true; <---------

  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState)
  {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay)
  {
    if (reading != buttonState)
    {
      buttonState = reading;

      if (buttonState == HIGH)
      {
        mp3_play (1); //power down sound
      }

      if (buttonState == LOW)
      {
        mp3_play (2);  // fire sound
        buttonLowTime = millis(); <-----------
        timeoutAudioPlayed = false; <---------
      }
    }
  }

  // The logic for timeout audio <------------
  if((buttonState == LOW) && (millis() - buttonLowTime) > BUTTON_LOW_TIME_MAX && timeoutAudioPlayed == false)
  {
    mp3_play (3);
    timeoutAudioPlayed = true;
  }

  lastButtonState = reading;
}

Great, I really appreciate it. Thanks

Thanks for the help Fahad. One little issue after trying the code, its works great for a few times, then it only plays the (3) file with a button press and not the (2) anymore.

I can just speculate the reason. I changed the timeout logic, from lastButtonState to buttonState. Because lastButtonState is true even without going through the debounce check. I updated the code above. Let me know if that works.

Unfortunately it still has the same problem, works a few times as intended, then breaks. Thanks Fahad

I changed static int buttonLowTime to static long buttonLowTime and it seems to be working fine now.

Oh, my bad. It should have been long, and NOT int. Good catch!

thanks again...


text:
arduino loRa module search tutorial
I recently purchased a LoRa module (https://it.aliexpress.com/item/1005002116232826.html?spm=a2g0s.9042311.0.0.38c74c4dPnh2Gg) but I have not found any working tutorial for this model can you help me

this may help ... https://github.com/Lora-net/LoRaMac-node


text:
ESP8266 ISO 8601 string to tm struct
I have a web service that returns timestamps in ISO 8601 format, e.g., "2021-06-25T12:00:00"
I'm trying to turn the timestamp string into a tm type struct from the ESP8266 library <time.h>, to perform time calculations using the difftime() function.
I've been referring to the Redhat time functions https://sourceware.org/newlib/libc.html#time, as it seem to be compatible with the ESP library, though all i can find are functions converting tm structs to timestamp strings. Are there any functions to convert a string timestamp into a tm struct and then back into epoch? Or what would be the best way to approach this kind of conversion on the ESP8266 platform?

Does this answer your question? How to parse 20180810T143000Z to time_t

Thank you! This method works too, though i find the answer below to be more useful.

sorry yes, there is a different format. strptime can't parse a timestamp without delimiters.

Try strptime from the time.h.
void setup()
{

  struct tm tm = {0};
  char buf[100];

  // Convert to tm struct
  strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);

  // Can convert to any other format
  strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);
  Serial.printf("%s", buf);
}

void loop()
{
    yield();
}

Thank you. The method above works. I just formatted my string as "%Y-%m-%dT%H:%M:%S",instead.


text:
How to use millis instead of delay?
Sorry if something similar has been answered before...
I am working on a garden timer project that runs on a ESP8266 based NodeMCU and is integrated with Blynk.
I have a waterNow function that activates when I press a button on the Blynk app, it sets pin D5 to HIGH and waits 3 seconds with a delay function, the problem is that with delay the code just halts all other functions until the delay is complete.
After doing some research I found out that the millis function could be used to have a time delay and have the program still run, but I can't get it to work.
How do use the millis function to add a delay?
Any help is appreciated.
Code:-
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include "DHT.h"
#include "LiquidCrystal_PCF8574.h"

#define BLYNK_PRINT Serial
#define DHT_PIN_DATA  12
// LCD definations
#define LCD_ADDRESS 0x27
#define LCD_ROWS 2
#define LCD_COLUMNS 16
#define SCROLL_DELAY 150
#define BACKLIGHT 25
#define DHTTYPE DHT22

char auth[] = "ymri204FL9_xZhf6WIRHtQ1qEWOt9zBy";

char ssid[] = "Aihertgtel-Hotspotgfdf-82DB";
char pass[] = "";
int autoSch;
int waterNow;
int morTime;
int afterTime;
int eveTime;
int schTime;
int x;

DHT dht(DHT_PIN_DATA, DHTTYPE);
LiquidCrystal_PCF8574 lcdI2C;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "in.pool.ntp.org", 19800, 600000);
// This function will be called every time Slider Widget
// in Blynk app writes values to the Virtual Pin 1

BLYNK_CONNECTED() {
  Blynk.syncAll();
}

BLYNK_WRITE(V0)
{
  autoSch = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V1)
{
  morTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V2)
{
  afterTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V3)
{
  eveTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V10)
{
  waterNow = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V4)
{
  schTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

void time_run() {
  Blynk.virtualWrite(V11, int(timeClient.getHours()));
  Blynk.virtualWrite(V12, int(timeClient.getMinutes()));
  Blynk.virtualWrite(V13, float(dht.readTempC()));
  Blynk.virtualWrite(V14, float(dht.readHumidity()));
  Serial.println(dht.readTempC());
}

void auto_run1() {
  if (morTime == 1 && String(timeClient.getFormattedTime()) > "06:00:00" && String(timeClient.getFormattedTime()) < "06:20:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    Blynk.syncAll();
  }
  else if (afterTime == 1 && String(timeClient.getFormattedTime()) > "12:00:00" && String(timeClient.getFormattedTime()) < "12:20:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    Blynk.syncAll();
  }
  else if (eveTime == 1 && String(timeClient.getFormattedTime()) > "15:47:00" && String(timeClient.getFormattedTime()) < "13:48:00") {
   // digitalWrite(14, HIGH);
    for (x; x >  10; x++){
  digitalWrite(14, HIGH);
  delay(1000);
  }
    Blynk.virtualWrite(V5, 255);
    Blynk.syncAll();

  }
  else {
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
    Blynk.syncAll();
  }
}

void sch_run2() {
  if (schTime == 1) {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    Blynk.syncAll();
  } else {
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
  }

}

void waterNowrun() {
  if (waterNow == 1) {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    lcdI2C.selectLine(2);
    lcdI2C.print("Watering Now     ");
    delay(3000); // I want to remove this for millis
    Blynk.virtualWrite(V10, 0);
    Blynk.syncAll();
  } else {
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
  }
}
void lcd() {
  delay(300);
  lcdI2C.clear();

  timeClient.update();
  lcdI2C.print(timeClient.getFormattedTime());

  if (autoSch == 0) {
    lcdI2C.setCursor(9, 0);
    lcdI2C.print("Auto");
  } else {
    lcdI2C.print(" Sch");
  }

  if (digitalRead(14) == 1) {
    lcdI2C.selectLine(2);
    lcdI2C.print("Watering Now");
  }
  else
  {

    if (int(timeClient.getHours()) < 6 && morTime == 1 && autoSch == 0) {
      Blynk.syncAll();

      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 6");
    } else if (int(timeClient.getHours()) < 12 && afterTime == 1 && autoSch == 0) {
      Blynk.syncAll();

      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 12");
    } else if (int(timeClient.getHours()) < 18 && eveTime == 1 && autoSch == 0) {
      Blynk.syncAll();
      lcdI2C.selectLine(2);

      lcdI2C.print("Auto Wtr at: 18");
    } else if (int(timeClient.getHours()) >= 18 && morTime == 1 && autoSch == 0) {
      Blynk.syncAll();
      lcdI2C.selectLine(2);

      lcdI2C.print("Auto Wtr at: 6");
    } else {
      Serial.println(timeClient.getHours());
    }

  }

}

void loop()
{
  Blynk.run();
  time_run();
  lcd();
  timeClient.update();

  if (waterNow == 1) {
    waterNowrun();
  }
  if (autoSch == 0) {
    auto_run1();

  } else {
    sch_run2();

  }

}
void setup()
{
  dht.begin();
  lcdI2C.begin(LCD_COLUMNS, LCD_ROWS, LCD_ADDRESS, BACKLIGHT);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  pinMode(14, OUTPUT);
  digitalWrite(14, LOW);
  pinMode(16, INPUT_PULLDOWN_16);

  Serial.begin(9600);
  //WiFi.begin(ssid, password);
  Blynk.begin(auth, ssid, pass);
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }
  timeClient.begin();
}

This question comes up regularly. Look at the “Blink without delay” example included with the Arduino IDE to see how you can use millis() for non-blocking time delays and event scheduling.

I have already looked at that, can't make out anything... but will try again

Short hint: You have to keep track of your state. So in the WaterNow function you have to store the millis() value to a variable when you start watering and then compare that value regularly with the current time to find out when the required amount has elapsed.

Does this answer your question? How to use millis() in my code instead of delay()?

Does this answer your question? Is it possible to replace this delay with millis()? (And issue with other millis loop)

Try this search: https://arduino.stackexchange.com/search?q=%5Bmillis%5D+delay

I am assuming after you start watering you want to set V10 to 0 after 3 seconds.
First, you will have to set waterNow to 0 after you start watring. Otherwise waterNowrun() will keep executing.
Second, you need to keep track of the 'watering' state so that you know that you have to start tracking the time.
Third, save the time when the watering started so that you can compare with the current time to see if your '3 seconds' has been passed.
Here is a simple example:
// Global variables
const long int MAX_TIME_THRESHOLD_MS = 3000;
bool WateringStarted = false;
long int WateringStartTime = 0;

... ... ...

void waterNowrun()
{
  if (waterNow == 1)
  {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    lcdI2C.selectLine(2);
    lcdI2C.print("Watering Now     ");

    waterNow = 0;
    WateringStarted = true;
    WateringStartTime = millis();

  }
  else   // <------ Why do you even have else! You only call waterNowrun() when waterNow == 1
  {
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
  }
}

... ... ...

void loop()
{
  ... ... ...

  if(WateringStarted && (millis() - WateringStartTime) > MAX_TIME_THRESHOLD_MS)
  {
    WateringStarted = false;
    Blynk.virtualWrite(V10, 0);
    Blynk.syncAll();
  }

  ... ... ...

}

I haven't run this code and don't have your setup to check it either. But it should give you some idea. Also, check the comments to your question for some more information about millis().

The setup is after the loop

Haha! I meant your actual hardware setup and Blynk app etc.

Oh ok..... I got it solved