body:
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?   [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/xilB9.jpg

title: How to implement Arduino NANO as a RS-232 to USB adapter (Or do I need a Arduino Mega?) For 3D printer comms

Answers: 4

body:
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:

1. Load a do-nothing sketch in the Nano
2. 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.

body:
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.

body:
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.

body:
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


body:
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?

title: EtherCard library without TCP

Answers: 1

body:
My EthernetENC library based on the original UIPEthernet library by Norbert Truchsess has [settings][1] 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.

  [1]: https://github.com/jandrassy/EthernetENC/wiki/Settings


body:
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][1] , 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][2] 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?

  [1]: https://github.com/espressif/esp-idf/issues/6179
  [2]: https://arduino.stackexchange.com/questions/55702/esp32-disable-brownout-detector

title: ESP32-S2 Brownout Detector Randomly Triggered in Deep Sleep

Answers: 0


body:
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.

~~~ c++
#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);
  }

}
~~~

title: Can someone help me figure out why only one wheel is spinning?

Answers: 1

body:
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.


body:
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;
}
```

title: Millis timer question

Answers: 1

body:
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:
1. The button is pressed
2. and is pressed for more than said time (`BUTTON_LOW_TIME_MAX`)
3. and if the audio hasn't been played.
</br>
>

    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;
    }


body: 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

title: arduino loRa module search tutorial

Answers: 0


body:
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?

title: ESP8266 ISO 8601 string to tm struct

Answers: 1

body:
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();
    }


body:
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();
}
```

title: How to use millis instead of delay?

Answers: 1

body:
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()`.


body:
I need some advice. I am trying to code a setup of 4 stepper motors that are connected to a keypad and 2 DC-motors that run a conveyor belt. My goal is to be able to push a key, the correspondning stepper motor starts and the DC-motors starts as well and run for a couple of seconds after the stepper. However, I want to be able to push multiple keys while the DC-motors are running. Right now I need to wait for the DC-motors to be done before I can push another key. How can I make this happen?

I think there will be issues if I code it with a timer since the keys are waiting for an input. I don't have any sensors.

This is my code:

    #include <Keypad.h>
    #include <Stepper.h>

    const int stepsPerRevolution = 1024;

    Stepper myStepper1(stepsPerRevolution, 22, 26, 24, 28);
    Stepper myStepper2(stepsPerRevolution, 32, 36, 34, 38);
    Stepper myStepper3(stepsPerRevolution, 23, 27, 25, 29);
    Stepper myStepper4(stepsPerRevolution, 33, 37, 35, 39);

    const int IN1 = 47;
    const int IN2 = 45;
    const int IN3 = 51;
    const int IN4 = 49;

    const int ENA = 43;
    const int ENB = 53;

    const byte ROWS = 4; //four rows
    const byte COLS = 4; //three columns
    char keys[ROWS][COLS] = {
      {'D','C','B','A'},
      {'H','G','F','E'},
      {'L','K','J','I'},
      {'P','O','N','M'}
    };

    byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {6, 7, 8, 9}; //connect to the column pinouts of the keypad

    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    void setup(){
      Serial.begin(9600);
       myStepper1.setSpeed(10);
       myStepper2.setSpeed(10);
       myStepper3.setSpeed(10);
       myStepper4.setSpeed(10);

      pinMode (IN1, OUTPUT);
      pinMode (IN2, OUTPUT);
      pinMode (IN3, OUTPUT);
      pinMode (IN4, OUTPUT);
      pinMode (ENA, OUTPUT);
      pinMode (ENB, OUTPUT);

    }

    void loop(){
     // char key = keypad.getKey();
     char key = keypad.waitForKey();

       if (key){
        Serial.println(key);
    //control speed
      analogWrite(ENA, 200);
      analogWrite(ENB, 200);
    //control direction
    int onTime   = 5000;
      digitalWrite(IN1, HIGH);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, HIGH);
      digitalWrite(IN4, LOW);

    // ----------------------------------Stepper1-----------------------------

            // just print the pressed key
       if (key == 'A' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper1.step(256);
      delay(100);
    }

      // just print the pressed key
       if (key == 'E' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper1.step(512);
      delay(100);
    }

      if (key == 'I' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper1.step(768);
      delay(100);
      }

      if (key == 'M' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper1.step(1024);
      delay(100);
      }

    //-----------------------Stepper2------------------------

    if (key == 'B' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper2.step(256);
      delay(100);
    }

      // just print the pressed key
       if (key == 'F' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper2.step(512);
      delay(100);
    }

      if (key == 'J' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper2.step(768);
      delay(100);
      }

      if (key == 'N' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper2.step(1024);
      delay(100);
      }

     //------------------------Stepper3--------------------

    if (key == 'C' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper3.step(256);
      delay(100);
    }

      // just print the pressed key
       if (key == 'G' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper3.step(512);
      delay(100);
    }

      if (key == 'K' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper3.step(768);
      delay(100);
      }

      if (key == 'O' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper3.step(1024);
      delay(100);
      }

     //------------------------Stepper4--------------------

    if (key == 'D' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper4.step(256);
      delay(100);
    }

      // just print the pressed key
       if (key == 'H' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper4.step(512);
      delay(100);
    }

      if (key == 'L' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper4.step(768);
      delay(100);
      }

      if (key == 'P' ){
        Serial.println(key);
         // step one revolution in one direction:
      Serial.println("clockwise");
      myStepper4.step(1024);
      delay(100);
      }

    //---------DC_Motor---------

       delay(onTime);
      digitalWrite(IN1, LOW);
      digitalWrite(IN2, LOW);
        digitalWrite(IN3, LOW);
      digitalWrite(IN4, LOW);

     }
    }

title: Not have to wait for if statement to run

Answers: 1

body:
The `delay(onTime);` statement in the `//---------DC_Motor---------` section of your code is preventing anything else taking place until the end of the DC motor run. Instead of delaying, you need to test how long the motor has been running, and do nothing if that time has not been reached yet. As others have pointed out, the BlinkWithoutDelay example program demonstrates how to do this. But in short, the motor section needs to do:

    // Start motor here
    timeMotorStarted = millis();
       :
       :
       :
    if( millis() - timeMotorStarted > onTime ){  // has motor run long enough?
      // stop the motor
    }


body:
I Have a Liquid Level Project that Currently uses an Oled display.  I have just discovered the existence of the nRF24L01 wireless communication module; and it is exactly what I need to make my project more user friendly.

Eventually I want to have a dashboard that brings all my info together in one place, but for now I just want to figure out how to get my Liquid Level Project transmitting, and receive the data on another Arduino and view it on the Serial monitor.  As is all it does is print out "?" in the Serial monitor.

I have this Sketch on the Liquid Level Project Arduino:

    #include <Wire.h>
    #include "SSD1306Ascii.h"
    #include "SSD1306AsciiAvrI2c.h"
    SSD1306AsciiAvrI2c oled;
    #define I2C_ADDRESS 0x3C
    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    double SensorAnalogValue;
    uint8_t calculation=1;
    String Show_value;

    //create an RF24 object
    RF24 radio(9, 8);  // CE, CSN

    //address through which two modules communicate.
    const byte address[6] = "00001";

    void setup()
    {

      Serial.begin(9600);
      oled.begin(&Adafruit128x64, I2C_ADDRESS);
      oled.setFont(CalLite24);
      oled.clear();

      radio.begin();

      //set the address
      radio.openWritingPipe(address);

      //Set module as transmitter
      radio.stopListening();

    }

    void loop()
    {

      SensorAnalogValue = analogRead(A0) * 5.0 / 1023.0;
      if (SensorAnalogValue < 1.726) {
        calculation=0;
        Show_value="Low";
      }
      if (SensorAnalogValue > 4.04) {
        calculation=0;
        Show_value="High";
      }
      if(calculation!=0){
      //  Serial.println(SensorAnalogValue);
        Show_value=(String)Liquid_Volume(SensorAnalogValue);
      }
      Serial.println(SensorAnalogValue);

    oled.setCursor(20, 0);
      oled.print(Show_value);
      oled.print(" L");
      oled.println(" ");
      oled.print(Show_value);
      oled.print("L");
      oled.println(" ");
    delay(500);
       oled.clear();

      radio.write(&Show_value, sizeof(Show_value));
      delay(1000);

      calculation=1;
    }
    int Liquid_Volume(double Volt) {
      double A =   2.81842;
      double B = -11.00151 ;
      double C =  14.4765 ;
      double D =  28.73579 ;

      return A * Volt * Volt * Volt + B * Volt * Volt + C * Volt + D;
    }

And the Receiver has this:

    //Include Libraries
    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    //create an RF24 object
    RF24 radio(9, 8);  // CE, CSN

    //address through which two modules communicate.
    const byte address[6] = "00001";

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

      radio.begin();

      //set the address
      radio.openReadingPipe(0, address);

      //Set module as receiver
      radio.startListening();
    }

    void loop()
    {
      //Read the data if available in buffer
      if (radio.available())
      {
        char Show_value[32] = {0};
        radio.read(&Show_value, sizeof(Show_value));
        Serial.println(Show_value);
      }
    }

I think the problem is in:

    radio.write(&Show_value, sizeof(Show_value));

I believe "radio.write" is used kinda like Serial.print, or oled.print,  But I don't really understand the "sizeof" part, maybe that is the problem?

title: Add nRF24L01 to a project

Answers: 1

body:
```c++
radio.write(&Show_value, sizeof(Show_value));
```

> I believe "radio.write" is used kinda like Serial.print, or
> oled.print, But I don't really understand the "sizeof" part, maybe
> that is the problem?

Sort of.  There's kind of two interrelated problems.  The major one is that the actual data of a `String` is not contained with the actual `String` type itself.  It's [allocated on the heap][1].  What the `String` class contains is [a pointer to it and some numbers][2] for tracking the allocated size and amount used.

So the first problem is you're not reading the memory that actually contains the text inside the string.

`sizeof(Show_value)` evaluates to the size in bytes of the `String` class itself, which is the size of a pointer and a couple of integers, about 6 bytes, and not the size of the content of the string.

So you're sending a pointer (a memory address) that the receiver wouldn't know what to do with, and some information about how much was allocated and used and nothing of the String content.

Try:

```c++
radio.write(Show_value.c_str(), Show_value.length());
```

`.c_str()` gets a pointer to the actual string content itself.  And `.length()` is the actual size of the used part of the `String`'s allocated area on the heap.

That said, it's better to avoid `String` where you reasonably can.

---

Regarding:

> Does this also mean I need to `replace radio.read(&Show_value, sizeof(Show_value));`

It would. Doing that is a bit more complicated since `.c_str()` yields `const char *`; `String` isn't designed to make write-access to its underlying data as easy.

Without hacking your way around `String`'s expectations, that would require using a temporary buffer. Something like:

```c++
char buffer[33] = "";  // Note: this will actually fill the entire buffer with '\0', which some find a surprise.
// The idea in the above is to accommodate the maximum RH24L01 packet size 32 bytes plus room for a null terminator.

radio.read(buffer, sizeof buffer - 1);  // We're only making the 32 byte chunk available to the .read() call, and leaving the last byte to it's '\0' value to force null termination in any case.

String s = buffer;
```

This assuming that you're either filling the packet with bytes, or including the null terminator in the packet, or both.  If you're using a dynamic payload size, rather than initializing the array with `= "";`, it could be left uninitialized and the received packet size could be used to place the null terminator at the location needed.

You could wrap this in a function if you plan on doing it a lot.  But again, it's probably better if you can just use the array and not work with `String`.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/WString.cpp#L157
  [2]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/WString.h#L196


body:
I'm trying to read a file from micro SD on an ESP32-cam board and upload to an FTP server, but when I try to read data from the opened file to an unsigned char, it gives me the following error:

```
Guru Meditation Error: Core  1 panic'ed (StoreProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x4008c674  PS      : 0x00060030  A0      : 0x800ed1c7  A1      : 0x3ffb1e20
A2      : 0x00000000  A3      : 0x3ffd7c78  A4      : 0x00000080  A5      : 0x00000000
A6      : 0x474e5089  A7      : 0x0a1a0a0d  A8      : 0x00000000  A9      : 0x3ffb1df0
A10     : 0x00000080  A11     : 0x3ffb66e4  A12     : 0x3ffd7c78  A13     : 0x00000080
A14     : 0x00002494  A15     : 0xff000000  SAR     : 0x00000018  EXCCAUSE: 0x0000001d
EXCVADDR: 0x00000000  LBEG    : 0x4008c670  LEND    : 0x4008c68c  LCOUNT  : 0x00000007

ELF file SHA256: 0000000000000000

Backtrace: 0x4008c674:0x3ffb1e20 0x400ed1c4:0x3ffb1e30 0x400ed245:0x3ffb1e60 0x400d06e7:0x3ffb1e80 0x400d084f:0x3ffb1f20 0x400d2b5a:0x3ffb1fb0 0x4008efde:0x3ffb1fd0

Rebooting...
```

The code is the following:

```
// Wifi and FTP Client Lib
#include <WiFi.h>
#include <WiFiClient.h>
#include "ESP32_FTPClient.h"

// MicroSD
#include "driver/sdmmc_host.h"
#include "driver/sdmmc_defs.h"
#include "sdmmc_cmd.h"
#include "esp_vfs_fat.h"

// FTP Server credentials
char ftp_server[] = "192.168.1.50";
char ftp_user[]   = "username";
char ftp_pass[]   = "password";

// wifi access
const char* ssid = "ssid";
const char* password = "psk";

// file to be read and uploaded
FILE *fileUpload = NULL;

// ftp client object
ESP32_FTPClient ftp (ftp_server, ftp_user, ftp_pass);

// micro sd initialization
static esp_err_t init_sdcard()
{
  esp_err_t ret = ESP_FAIL;
  sdmmc_host_t host = SDMMC_HOST_DEFAULT();
  sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
  esp_vfs_fat_sdmmc_mount_config_t mount_config = {
    .format_if_mount_failed = false,
    .max_files = 10,
  };
  sdmmc_card_t *card;
  ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card);
}

void FTP_upload( void );
void FTP_upload()
{

  // initialize file name
  char fileName[100];
  sprintf(fileName, "/sdcard/img.png");
  fileUpload = fopen(fileName, "r+");

  // notify reading of the file
  Serial.print("Reading file: ");
  Serial.println(fileName);
  if (fileUpload == NULL)
  {
    Serial.println("Cannot open file");
    return;
  }

  // retrieve file size
  fseek(fileUpload, 0, SEEK_END);
  long int size = ftell(fileUpload);
  fclose(fileUpload);

  // print file size to serial
  Serial.print("File size: ");
  Serial.println(size);

  // Reading data to array of unsigned chars
  fileUpload = fopen(fileName, "r+");
  unsigned char * in PROGMEM = (unsigned char *) malloc(size);

  // display allocated memory
  Serial.print("Allocated memory: ");
  Serial.println(sizeof(in));

  // read file to allocated memory
  int bytes_read = fread(in, sizeof(unsigned char), size, fileUpload); // <------- THIS ROW RISES THE ERROR

// close file
  fclose(fileUpload);

  // Open FTP connection
  Serial.println("Starting FTP upload...");
  ftp.OpenConnection();

  //Create a file and write the image data to it;
  ftp.InitFile("Type I");

  // change remote directory
  ftp.ChangeWorkDir("/Shared/");

  // specify remote file name
  String strNome = "img.png";

  // convert String to char
  const char *f_name = strNome.c_str();

  // create a new file with the given name inside the remote directory
  ftp.NewFile( f_name );

  // write data read above from local file to remote file
  ftp.WriteData(in, sizeof(in));

  // close remote file
  ftp.CloseFile();

  // notify completed upload
  Serial.println("File uploaded successfully");

  // wait
  delay(100);

}

void setup() {

  // begin serial communication
  Serial.begin(115200);

  // initialize micro sd
  esp_err_t errSD = init_sdcard();
  if (errSD != ESP_OK) {
    Serial.printf("Cannot initialize SD. Error code: 0x%x", errSD);
    return;
  }

  // begin wifi connection
  WiFi.begin(ssid, password);

  // wait for the connection to be estabilished
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // notify successful connection
  Serial.println("");
  Serial.println("WiFi connected");

  // show the assigned IP
  Serial.print("IP: ");
  Serial.println(WiFi.localIP());

  // call the FTP upload procedure
  FTP_upload();

}

void loop() {
  // empty
}
```

How can I solve this? Thank you

title: StoreProhibited error while trying to read file to PROGMEM

Answers: 1

body:
Solved, I changed the method a little.

In a loop, I read a portion of the file and write it to the opened FTP remote file, then I close both at the end of the cycle

```
// open FTP connection
ftp.OpenConnection();

// open local file
fileUpload = fopen("/sdcard/img.png", "r+");

// initialize file type
ftp.InitFile("Type I");

// change remote directory
ftp.ChangeWorkDir("/Shared/");

// define remote file name
String strName = "img.png";

// convert to char
const char *f_name = strName.c_str();

// create remote file with given name
ftp.NewFile( f_name );

// read all file in a loop
unsigned char buff[64];
while(!feof(fileUpload)){

    // read a portion of the file
    fread(buff, sizeof(char), sizeof(buff), fileUpload);

    // write that portion to the remote file
    ftp.WriteData(buff, sizeof(buff));
}

// close both the local and the remote file
fclose(fileUpload);
ftp.CloseFile();
```


body:
I'm trying to decide my rf remote signals using ESP32 or node MCU. I have tried with Arduino and was successful but for some reason it is not working on either ESP32 or node MCU even using the same GPIO2 pin can anyone please tell me why both the boards are not able to decode the signal. I'm using the rc-switch library to decode and a 433Mhz transmitter reciever combo from amazon

```#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    output(mySwitch.getReceivedValue(), mySwitch.getReceivedBitlength(), mySwitch.getReceivedDelay(), mySwitch.getReceivedRawdata(),mySwitch.getReceivedProtocol());
    mySwitch.resetAvailable();
  }
}```

title: Decode rf remote signals with ESP32 or node MCU?

Answers: 1

body:
For ESP32, you should provide real GPIO number.
For instance:
mySwitch.enableReceive(13);

And without deep explanation, believe that it properly works
with GPIO 13 and 27.
Details you can find by google...


body:
I am brand new to Arduino but have good experience with Raspberry Pi's and Microchips.

My problem is that I am having trouble driving many stepper motors at once. I am using the AccelStepper library(https://www.airspayce.com/mikem/arduino/AccelStepper/index.html). The code is pretty simple and I got it to work perfectly for a long time with three motors, however it had trouble running more than three motors, I have 5 motors hooked up right now and all of them vibrate or skip steps.

Can anyone help me get the 5 motors working.

Here is the code I'm running:
```
#include <MultiStepper.h>
#include <AccelStepper.h>
#include <Stepper.h>

AccelStepper stepper1(AccelStepper::FULL4WIRE, 8, 10, 9, 11);
AccelStepper stepper2(AccelStepper::FULL4WIRE, 4, 5, 6, 7);
AccelStepper stepper3(AccelStepper::FULL4WIRE, 12, 13, 2, 3);
AccelStepper stepper4(AccelStepper::FULL4WIRE, A0, A1, A2, A3);
AccelStepper stepper5(AccelStepper::FULL4WIRE, 0, 1, A4, A5);

void setup()
{
    //Serial.begin(9600);
    pinMode(0, OUTPUT);
    pinMode(1, OUTPUT);
    pinMode(A0, OUTPUT);
    pinMode(A1, OUTPUT);
    pinMode(A2, OUTPUT);
    pinMode(A3, OUTPUT);
    pinMode(A4, OUTPUT);
    pinMode(A5, OUTPUT);
    Serial.print(" a0:");
    Serial.print(digitalRead(A0));
    stepper1.setMaxSpeed(600.0);
    stepper1.setAcceleration(50.0);
    stepper1.moveTo(3240);

    stepper2.setMaxSpeed(50);
    stepper2.setAcceleration(1);
    stepper2.moveTo(800);

    stepper3.setMaxSpeed(300.0);
    stepper3.setAcceleration(200.0);
    stepper3.moveTo(1500);

    stepper4.setMaxSpeed(300.0);
    stepper4.setAcceleration(200.0);
    stepper4.moveTo(1500000);

    stepper5.setMaxSpeed(300.0);
    stepper5.setAcceleration(200.0);
    stepper5.moveTo(1500000);
}
void loop()
{
    // Change direction at the limits

    if (stepper1.distanceToGo() == 0)
        stepper1.moveTo(-stepper1.currentPosition());
    if (stepper2.distanceToGo() == 0)
        stepper2.moveTo(-stepper2.currentPosition());
    if (stepper3.distanceToGo() == 0)
        stepper3.moveTo(-stepper3.currentPosition());
    if (stepper4.distanceToGo() == 0)
        stepper4.moveTo(-stepper4.currentPosition());
    if (stepper5.distanceToGo() == 0)
        stepper5.moveTo(-stepper5.currentPosition());
    stepper1.run();
    stepper2.run();
    stepper3.run();
    stepper4.run();
    stepper5.run();
}
```
I don't think it is the code that is the problem because as I stated before it worked with three motors just fine and the code for 4 and 5 is just copy paste.

I think it could be a power problem, I have a wall outlet that can convert to a range of dc voltages between 3 and 12, at 5V the motors are clearly lacking the power to run. At 6V they do turn on but dont work well at all(as I stated above) and at 7.5V the Arduino seems to continually restart: the motors start for just a second.

Here are the 28BYJ-48 motors with drivers I bought from amazon: https://www.amazon.com/gp/product/B01CP18J4A/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1

Can anyone explain to me why it restarts at 7.5 volts? I've read that the minimum power should be around 7 volts so this doesn't make sense to me.

Appreciate any help I can get, please remember I'm new to this. Thank you.

title: Help needed with driving multiple stepper motors on arduino UNO

Answers: 0


body:
I had written some code that involved doing something after 10 milliseconds had elapsed, however it was performing unexpectedly. Upon debugging, I think I have identified the error, and I wrote some code with *just* that block:

    unsigned long int newtime=0;
    unsigned long int prevtime=0;
    int time;
    void setup()
    {
      Serial.begin(9600);
    }

    void loop()
    {
    newtime=millis();
    time=newtime-prevtime;
    if(time==10){
      Serial.println(prevtime);
      prevtime+=10;
    }

    }
The serial monitor "freezes on 150. it shows the values 0,10,20...as expected but it freezes on 150...and then nothing happens.

What exactly is causing this?

title: Unexpected output for simple code involving calculating a time interval of 10ms

Answers: 2

body:
your logic is just tricky to confuse. It is repeatable because along as you not change the if logic, the code is going to run till it displays 150. then it will stop. You can also check the same behaviour [here][1]

Once the time difference is not exactly equal to 10, the if part will not be executed. Hence, the `prevtime` will not catch up with the `newtime` anymore. newTime will soon grow to be bigger and the difference will always be greater than 10.

I suggest visiting https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay to get some hints on tracking time in a safer way.

  [1]: https://wokwi.com/arduino/projects/297224412670722569

body:
The problem is, that you are filling up the Serial buffer rather fast, because you try to send ASCII numbers every 10ms at only 9600ms. When the buffer is full, `Serial.println()` will wait, until there is enough space free in the buffer for the current data. That makes your loop lasting significantly longer.

In that case the time, where the `time` is exactly 10 is missed. Thus the code does nothing at that point, until time rolls over and gets 10 again (48 days I think).

While you can mitigate the problem by using a higher baudrate, the main problem is still

    if(time==10){

You have only provided an example code. Your real code might sometimes take longer than 10ms out of some other reason (actually this already gets critical, when the loop takes longer than 1ms, since it then might already miss the one moment, where `time` is 10). To futureproof your code and make sure, that you don't hunt down the same bug again and again, you should do, what you were told in the comments, and use

    if(time>=10){

Depending on your code the event will still happen after 10ms the absolute most of the time. But this variant also doesn't break, if the loop takes longer than 10ms sometimes.


body:
I have a windows computer connected to my Arduino Uno. I work in a area with a bunch of cubicles and we leave our desk fairly regularly to go and troubleshoot other computers (I'm a service desk technician).
When we leave we are instructed to raise and lower a small flag so management can see whether or not we are sitting at our desk. I've attached my arduino to a servo motor with the following code.

```

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2

int angle =0;    // initial angle  for servo
int angleStep =20;
const int minAngle = 0;
const int maxAngle = 90;

int buttonPushed =0;

void setup() {
  // Servo button demo by Robojax.com
  Serial.begin(9600);          //  setup serial
  myservo.attach(servoPin);  // attaches the servo on pin 3 to the servo object
  pinMode(pushButtonPin,INPUT_PULLUP);
   Serial.println("Nathan's Status flag");
}

void loop() {
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }
   if( buttonPushed ){
  // change the angle for next time through the loop:
  angle = angle + angleStep;

    // reverse the direction of the moving at the ends of the angle:
    if (angle <= minAngle || angle >= maxAngle) {
      angleStep = -angleStep;
       buttonPushed = 0;
    }
    myservo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
  delay(100); // waits for the servo to get there
   }
}

```

We also have a policy that we need to keep our computers locked for obvious reasons. I learned my lesson with that early on. I would like to edit my code so that when I lock my computer the flag goes down, then when my computer is unlocked it goes back up. That way as long as I remember to keep my computer locked when I'm away I don't have to worry about the flag. Here is my breadboard/arduino layout.
[![Arduino Layout][1]][1]
I also have processing on my computer and am planning on using that. (https://processing.org/)

Any help is greatly appreciated.

  [1]: https://i.stack.imgur.com/Khat5.png

title: How do I make my Arduino do a specific action when the computer is locked/unlocked?

Answers: 1

body:
Read a value through serial (what exactly is entirely up to you) to do the same job the button does now.

Use `Serial.read()` to get that data, and `Serial.available()` to know if there is any data to read.

How you generate that value on the PC to send through serial we cannot help you with, as that is outside the scope of this site.


body:
[![enter image description here][1]][1]

EDIT: I'm so sorry but the clicking wasn't coming from the Arduino **but from the piezo buzzer!** I was wrong and I'm so sorry for misguiding you!

I recently bought an Arduino Nano so that I could downsize my arrangement with my Arduino Uno so I soldered everything together and when I plugged in the Nano I extra made sure that nothing was shorting each other out. But the buzzer attached to it kept making this clicking noise. Does anyone know why? Do I actually have a short-circuit?

Here is the code:

```

#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() {

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,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 3:
  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 4:
      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 5:
  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 6:

  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 7:
  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 8:
  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 9:
    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 10:
    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 11:
    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 12:
        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 13:
    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 14:
    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 15:
    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 16:
    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 17:
    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 18:
    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 19:
    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);

      tone (11,493.88);
      delay(150);

      tone(11, 523.25);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11,329.63);
      delay(150);

      tone(11, 261.63);
      delay(150);

      tone(11, 246.94);
      delay(150);

      tone (11,196.00);
      delay(150);

      tone(11, 246.94);
      delay(150);

      tone(11, 261.63);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11, 523.25);
      delay(150);

      tone (11,493.88);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11, 329.63);
      delay(150);

noTone(11);

old = state;
state = 0;
old = 0;

    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 a video of the clicking:
https://drive.google.com/file/d/1TprL56p2YyJ3j8cq43U2LYzaWofZpJM7/view?usp=sharing

  [1]: https://i.stack.imgur.com/d95tA.jpg

title: Why is my Arduino Nano's buzzer clicking?

Answers: 1

body:
The simpler piezos click when a voltage is applied, and again when it is removed. To make it buzz, it needs a pulse-train: many clicks makes a buzz. There are piezos that have that feature built-in, but I'm guessing yours hasn't. That's actually a Good Thing in disguise: it allows you to make tones by making pulse-trains at different frequencies. The easiest way to do that is to connect it to one of the PWM pins (5, 6, 9, 10, or 11) and use the `tone()` library-function (look it up if you need to). Of course, you can do it "manually", too, on any output pin, just by switching it HIGH and LOW at rates that you choose, but that will pretty much tie up your processor, at least for higher frequencies.

Update:

> Just why wasn't it clicking when I connected it to the Arduino Uno?

I can't tell without seeing the two sketches but in your video, it sounds like it is being turned on or off, or pulsed, once per second.

Please add your code (both of them, if they're different) to your question. Wiring diagram(s) of the piezo connection to the Arduino boards would help, too.


body:
I ordered ATMEGA328P AU from China recent but I got "ATMEGA328P U-TH". which seem super problematic.
I try to use USBasp to burn bootloader but it fail and show error message as shown.

    avrdude: error: program enable: target doesn't answer. 1
    avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.
which I believed many people face same situation as mine. Then I accidentally found the solution by using Arduino as ISP which successfully birn bootloader. After that I can use USBasp to upload sketch or burn bootloader.  I don't understand what happen here.
Note: I solder ATMEGA328P U-TH in SMD package to Arduino UNO clone.

title: Why ATMEGA328P U-TH doesn't answer to USBasp but work fine with Arduino as ISP?

Answers: 1

body:
If you want to upload a sketch via any other interface than ISP, the atmega needs a bootloader.

The bootloader basically is a piece of software which is stored in a dedicated flash section, the "bootloader section". Code stored in this bootloader section has the special ability to write to parts of flash memory where the actual program is stored (this is called the "application section").
In general, a program can not overwrite its own flash section, so the bootloader and the application need to be stored in different sections/partitions.

In principle, a bootloader can do whatever a normal sketch could do: toggle pins, access eeprom, read UART/I2C/etc... and as it can also write to the "application section", you can make it read data from any interface and transfer it to the application section.
This is what happens if you upload code via USBasp (Arduinos have a USB-to-UART converter on board).
But of course, this requires that a bootloader is installed.

`avrdude: error: program enable: target doesn't answer. 1` - this might sound misleading, what it actually means is, that the **bootloader** doesn't answer. That makes sense, as the device doesn't have a bootloader.

When there is no bootloader, the only way to upload code is to use ISP, which doesn't need any software to function. It's a hardware functionality that Atmel implements in silicon.
A code upload via ISP works in (almost) any case.


body:
My project requires that `Serial.read()` be able to accept extended ASCII characters (`0x80` <=> `0xFF`). For example, I would expect reading the character `¥` to yield the decimal value `157`. Instead, the `read()` command has two successful reads, with the values: `194` and `165`. Of course, I could create a lookup table and convert, but this is not a viable option. I am conforming to the `Grbl` standard protocol, which uses these single-byte extended ASCII characters as **interrupts**. Such a two-byte structure precludes a simple peek/read approach necessitated by the protocol.

**Edit** I tried to simplify the question for this context, but failed to account for the fact that the Arduino IDE will send the input as Unicode. Regardless, it still does not work when sending bytes directly. Namely, if I send the byte `0x93` via C# as `Serial.Write("\u0093")`, the Arduino's `Serial.read()` does not see any bytes available. Sending normal ASCII, e.g., `Serial.Write("\u0018")`, works fine.

title: Is it possible to read extended ASCII from the serial port?

Answers: 1

body:
Yes, of course, you can read any byte sequence. As you have experienced,
if you send the byte values 194 and 165, your Arduino reliably reads 194
and 165.

Now, you have to be aware that there are tons of incompatible character
encodings that could all be called “extended ASCII”. I do not know which
one you have in mind. Maybe there is such an encoding where “¥” has the
code point 157. Nowadays, however, almost any modern computer system
uses Unicode, and serializes the characters using UTF-8. The character
“¥” is serialized in UTF-8 as the pair of bytes 194 and 165.

If you want to use the Grbl protocol, send interrupts as _bytes_, do not
think about them as “characters”.


body:
I'm supposed to write a raspberry pi and arduino code to read the RPM of a motor with an encoder attached to it. However, I'm having weird numbers and I'm unsure about the specs on the motor and the encoder. So I thought it would be smart to use a second arduino to simulate the motor with encoder.

The simulator would need to produce a 2 signals representing the two signals from the encoder. I want to be able to set the frequency and phase shift of these signals in software to imitate changes in speed and direction of the motor rotation. Forward would have one signal 90 degrees ahead, and then reverse having that same signal to be 90 degrees behind. So phase difference of plus or minus 90 degrees.

I'd like to eventually have the simulator be able to simulate motor actions like oscillating between forward and reverse 5 seconds each, or forward for 5 seconds and then stop completely.

I found this [code by bigjosh][1] which is more or less what I want to do. However, that code doesn't allow for a shift of -90 deg by default. I know there's a comment there to change it, but I'm not knowledgeable enough to understand what's going on exactly. I'd like someone to help me with that.

  [1]: https://electronics.stackexchange.com/a/174759/33966

title: Simulate motor encoder quadrature signals using an Arduino UNO

Answers: 1

body:
Wow, that turned out to be way harder than I expected. It is very hard to do cleanly on the AVR timer. But I was able to come up with this working function, which I think is what you are looking for...

```
// freq_hz is frequency in hertz from 122 to 4,000,000
// shift_deg is phase shift between output A and output B in degrees (values outside -180 to +180 are normalized)

// Note that at frequencies above 44KHz you will loose precision on phase shift. At 4Mhz, everything is rounded to just 0 or +/-90 degrees.
// Note that all timing happens in 1/16Mhz increments, so frequencies that do not land on integer multipules of that will be aproximiate.
// Use startWaveforms() directly for more precise control.

void startQuadrature( unsigned long freq_hz , int shift_deg  );
```

It can glitch at start-up, shutdown, and changes in speed and direction... but so can a motor encoder so I guess that is ok. It would be possible to create a glitch-free version but more work.

Github repo here...
https://github.com/bigjosh/Quadrature

So, to simulate a motor going forward with 50KHz pulse rate, you would use something like...

`startQuadrature( 50000 , +90);`

...and the same pulse rate going backwards would be...

`startQuadrature( 50000 , -90);`

Do note that if you connect an Arduino UNO output pin to a Raspberry Pi input pin that it will likely damage the Pi. This is because the UNO outputs 5 volts for a "1" signal, but the Pi can only tolerate a maximum 3.3V on any pin. You can google "5V 3.3V level shifting" for solutions to this problem.


body:
I am using a DC motor with encoder, and I am trying to calculate how many pulses are  recorded in every one second interval. (note that the power source is of 12V for the motor)

**Circuit and code:**

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/NpmQC.jpg

    int encpin=3;
    volatile long npc=0; //new pulse count
    volatile long opc=0;  //original pulse count
    volatile long pulsecount;
    unsigned long int newtime;
    unsigned long int prevtime=0;
    unsigned long int time;
    void setup()
    {
      pinMode(encpin, INPUT_PULLUP);
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(encpin),function,RISING);
    }
    void function(){
      npc++;
    }
    void loop()
    {
     newtime=millis();
     time=newtime-prevtime;
     pulsecount=npc-opc;
      if(time==1000){
        Serial.println(pulsecount);
        prevtime+=1000;
        opc=npc;
      }
    }

It seems to be rather intuitive that increasing the rpm should increase the number of pulses recorded in one second. However, the results are rather erratic:

     RPM  PULSECOUNT
      26    2365
      32    2367
      38    2400
      44    2375
      52    2400
     116    2412
     142    2384
     195    2416
     280    2406
     350    3008
     416    1580
     520    1975
     624    2370
     730    2334
    2737    2188

**Increasing RPM sometimes increases the pulsecount, but sometimes decreases it....what could be the reason for this behaviour?**

title: unexpected behaviour of encoder with increasing rpm

Answers: 2

body:
I think the problem is in the tinkercad simulation:
The encoder is attached to the motor and the motor is always rotating at the same speed. Selecting a different RPM on the component changes the gear ratio and the RPM of the shaft, but not of the motor. That means that the number output after 1s should be always the same.
Why it is not exactly the same, only the programmers of the simulation can tell.
It might have to do with simulation speed, because I get totally different numbers there.

To tell exactly what is going on, a documentation of the components in the simulation and of the simulation would be necessary.

body:
One important principle to learn when working with interrupts is that of *atomic operations*.  It is vital, when working with any data that cannot be manipulated by one single assembly instruction, that you protect against that data being changed midway through any reading of that data.

In your situation you are working with 32-bit values. On an 8-bit microcontroller those take many many instructions to manipulate, and at any time during that manipulation the interrupt can be triggered and change the value, corrupting your readings.

There is a concept in programming called *critical sections*. These are "blocked off" bits of code where no interrupts are allowed to happen while you do whatever is needed to your shared variables. For obvious reasons you want to keep those sections as brief as possible.

Also you don't need to calculate the pulse count by comparing it to the previous count - just start from 0 each second. And on the topic of a second, it's best to check if *at least* a second has passed. There's always a chance you may see 1001ms instead of 1000ms. A slim chance, but best to be safe.

Here's an example, using your code as a base:

```c++
void loop() {

    if (millis() - prevtime >= 1000) { // you should check for more time passing than you expect
        prevtime += 1000; // Don't assume you always had 1 second, force it instead

        // This block is the "critical section". Keep it as short as possible
        // so just grab the data and reset the count.
        noInterrupts(); // Stop any interrupts happening
        uint32_t currentCount = npc; // Grab this second's count
        npc = 0; // And reset the count to zero
        interrupts(); // Release the block on interrupts

        // And output the results.
        Serial.println(currentCount);
    }

}
```


body:
I am new to Arduino and C++ and I was practicing with a traffic light project.

This is my code:
```cpp
int red = 10;
int yellow = 9;
int green = 8;

void setup() {
  pinMode(red,OUTPUT);
  pinMode(yellow,OUTPUT);
  pinMode(green,OUTPUT);
}

void loop() {
  changelights();
  delay (15000);
}

void changelights{
  // 1st action: green off to yellow
  digitalWrite(green, LOW);
  digitalWrite(yellow, HIGH);
  delay (3000)
  // 2nd action: tellow to red
  digitalWrite(yellow, LOW);
  digitalWrite(red, HIGH);
  //3rd action: caution light
  digitalWrite(yellow, HIGH);
  delay (3000)
  //4th action: caution to go
  digitalWrite(red,LOW);
  digitalWrite(yellow, LOW);
  digitalWrite(green, HIGH);
}
```
I tried compiling it and returned an error message that said that I did not declare my "changelights" function. What should I do to fix this?

Thank you very much

title: void declaration error

Answers: 1

body:
You forgot to put the parenthenses `()` after the name of the function `changelights`. They are there to declare variables you can use later in the code like that:
```cpp
void function(int a){
  a+=1;
  return a;
}
```
To fix your error just change
```cpp
void changelights{
```
to
```cpp
void changelights(){
```
Keep in mind if you want to program C++ (which would be Off-Topic here, but you mentioned it in your question) you have to declare the function in the beginning or mention it.


body:
I am trying to choose a wire encoder for my project. So far, I found this wire encoder (see [link][1]). Assuming the measurement range of my cylinder is 1 m. Then, with a 10 bit ADC converter of my Arduino Mega2560, I would have a resolution of 0.09cm (= 100cm/1024). But, lets say some cylinder only have a measurement range of 0.5m. Then the resolution would be 0.048 (=50cm/1024).

I can see that I am missing something here, because the resolution of the later case should be worse than the case with the full measurement range 1m. I would be appreciate for any tipps.

--------

Edit:

 - Cylinder's movement range 0~1m
[![enter image description here][2]][2]
 - Wire encoder's measurement range 0~1.25m
[![enter image description here][3]][3]
 - Wire encoder's analog output 0~10v
 - ADC resolution 10 bit

  [1]: https://www.sick.com/de/en/encoders/wire-draw-encoders/ecoline/bcg05-l1km01pp/p/p332388
  [2]: https://i.stack.imgur.com/kYyvf.png
  [3]: https://i.stack.imgur.com/ekvLy.png

title: Arduino ADC converter calculation

Answers: 1

body: Your calculation is not correct. The encoder has its 0 to 10V output voltage distributed over the whole distance, that the cable can reach, so 1.25m. And that gives you the resolution: `1.25m/1024 = 1.22mm`. The resolution doesn't change, if you use less than the maximum length. It's still the same resolution of about 1.22mm. The encoder doesn't care, if you are only using 1m of its range.


body:
i have a node mcu and i uploaded one example code to test it for rf signal decoding it worked. so after that i have written a code based on that and when i uploaded the code my node MCU suddenly isn't working as it should be. It is giving out some random things onto the serial monitor like this:

```
⸮L⸮⸮⸮ՋR(⸮⸮^⸮̓#⸮⸮;'⸮⸮(Zs"⸮⸮Z|⸮⸮⸮'⸮⸮⸮'⸮⸮⸮!#⸮⸮⸮G⸮⸮⸮⸮⸮h⸮y⸮⸮⸮⸮'⸮⸮LD⸮⸮J⸮*J⸮⸮⸮⸮⸮⸮⸮LD⸮⸮⸮⸮F(⸮y⸮⸮؁'1⸮L⸮⸮⸮
```

THE CODE:
```
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <RCSwitch.h>
BlynkTimer clocktime;

#define relayfan 5
#define relaylight 6
#define relaylightb 7
#define relayrandom 2

#define VPIN_BUTTON_1    V12
#define VPIN_BUTTON_2    V13
#define VPIN_BUTTON_3    V14
#define VPIN_BUTTON_4    V15

RCSwitch mySwitch = RCSwitch();

int relayfanstate = HIGH;
int relaylightstate = HIGH;
int relaylightbstate = HIGH;
int relayrandomstate = HIGH;
int mainstate = HIGH;
long code;

char auth[] = "rJUG7fhgXk9Y7OlowTontA1C2irfpgs2";

const char *ssid =  "Nag";
const char *pass =  "87654321";

BLYNK_CONNECTED()
{
  Serial.println("blynk connected first function");
  Blynk.syncVirtual(VPIN_BUTTON_1);
  Blynk.syncVirtual(VPIN_BUTTON_2);
  Blynk.syncVirtual(VPIN_BUTTON_3);
  Blynk.syncVirtual(VPIN_BUTTON_4);
}

BLYNK_WRITE(VPIN_BUTTON_1)
{
  Serial.println("blynk write");
  relayfanstate = param.asInt();
  digitalWrite(relayfan, relayfanstate);
}

BLYNK_WRITE(VPIN_BUTTON_2)
{
  Serial.println("blynk write");
  relaylightstate = param.asInt();
  digitalWrite(relaylight, relaylightstate);
}

BLYNK_WRITE(VPIN_BUTTON_3)
{
  Serial.println("blynk write");
  relaylightbstate = param.asInt();
  digitalWrite(relaylightb, relaylightbstate);
}

BLYNK_WRITE(VPIN_BUTTON_4)
{
  Serial.println("blynk write");
  relayrandomstate = param.asInt();
  digitalWrite(relayrandom, relayrandomstate);
}

void setup()
{
  Serial.begin(9600);
  mySwitch.enableReceive(0);
  pinMode(relayfan, OUTPUT);
  pinMode(relaylight, OUTPUT);
  pinMode(relaylightb, OUTPUT);
  pinMode(relayrandom, OUTPUT);
  digitalWrite(relayfan, HIGH);
  digitalWrite(relaylight, HIGH);
  digitalWrite(relaylightb, HIGH);
  digitalWrite(relayrandom, HIGH);
  Serial.println("Start");
  WiFi.begin(ssid, pass);
  Serial.println("wifi config done");
  Blynk.config(auth);//, ssid, pass);
  Serial.println("Blynk config done");
}

void loop()
{

  if (WiFi.status() != WL_CONNECTED)
  {
    Serial.println("Not Connected");
    Serial.println("Without internet rf code recieving started");
    delay(500);
    if (mySwitch.available())
    {
      Serial.println("Switch available");
      code = mySwitch.getReceivedValue();
      if (mySwitch.getReceivedValue() == 8594433)
      {
        Serial.println("code matched without internet");
        mainstate = !mainstate;
        digitalWrite(relayfan, mainstate);
        digitalWrite(relaylight, mainstate);
        digitalWrite(relaylightb, mainstate);
        digitalWrite(relayrandom, mainstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594447)
      {
        digitalWrite(relayfan, LOW);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594445)
      {
        digitalWrite(relayfan, HIGH);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594436)
      {
        relaylightstate = !relaylightstate;
        digitalWrite(relaylight, relaylightstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594437)
      {
        relaylightbstate = !relaylightbstate;
        digitalWrite(relaylightb, relaylightbstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594439)
      {
        relayrandomstate = !relayrandomstate;
        digitalWrite(relayrandom, relayrandomstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
    }
  }
  else
  {
    Serial.println(" Connected");
    Blynk.run();
    with_internet();
  }
  clocktime.run();
}

void with_internet()
{
  Serial.println("With internet rf code recieving started");
  delay(500);
  if (mySwitch.available())
  {
    Serial.println("Switch available");
    code = mySwitch.getReceivedValue();
    if (mySwitch.getReceivedValue() == 8594433)
      {
        Serial.println("code matched without internet");
        mainstate = !mainstate;
        digitalWrite(relayfan, mainstate);
        digitalWrite(relaylight, mainstate);
        digitalWrite(relaylightb, mainstate);
        digitalWrite(relayrandom, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_1, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_2, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_3, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_4, mainstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594447)
      {
        digitalWrite(relayfan, LOW);
        Blynk.virtualWrite(VPIN_BUTTON_1, LOW);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594445)
      {
        digitalWrite(relayfan, HIGH);
        Blynk.virtualWrite(VPIN_BUTTON_1, HIGH);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594436)
      {
        relaylightstate = !relaylightstate;
        digitalWrite(relaylight, relaylightstate);
        Blynk.virtualWrite(VPIN_BUTTON_2, relaylightstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594437)
      {
        relaylightbstate = !relaylightbstate;
        digitalWrite(relaylightb, relaylightbstate);
        Blynk.virtualWrite(VPIN_BUTTON_3, relaylightbstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594439)
      {
        relayrandomstate = !relayrandomstate;
        digitalWrite(relayrandom, relayrandomstate);
        Blynk.virtualWrite(VPIN_BUTTON_4, relayrandomstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
  }
}
```
can anyone tell me what is wrong with my code or my nodemcu module?
Is it because i uploaded two codes one after the other and messed up the module?

title: Node MCU not functioning correctly

Answers: 1

body:
> Can anyone just try to upload this code to their node MCU with
> changing the WiFi credentials and the blynk Auth token to one of your
> own project by following the blynk guide and check if it is connecting
> to blynk and it's only a problem with my module or there is some
> problem in my code

This might be necessary to see more problems.  But it isn't necessary to see at least one important one.  Here's what I cut your code down to:

```c++
#define relayfan 5
#define relaylight 6
#define relaylightb 7
#define relayrandom 2

void setup() {
  Serial.begin(9600);
  pinMode(relayfan, OUTPUT);
  pinMode(relaylight, OUTPUT);
  pinMode(relaylightb, OUTPUT);
  pinMode(relayrandom, OUTPUT);
  digitalWrite(relayfan, HIGH);
  digitalWrite(relaylight, HIGH);
  digitalWrite(relaylightb, HIGH);
  digitalWrite(relayrandom, HIGH);
  Serial.println("Start");
}

void loop() {
  Serial.println("loop()");
}

```

So, you have:
```c++
#define relaylight 6
```

One thing to make clear about here is that this is **GPIO**6, and **not** `D6`, which would [be mapped to][1] GPIO12, which would make more sense.  GPIO6 is actually used internally to the ESP8266 module to access the SPI flash chip that stores your code.  Basically when you do this:

```c++
pinMode(relaylightb /* GPIO6 */, OUTPUT);
```

you're kind of ripping the rug out from underneath the the microcontroller inside the ESP8266 module.  It's a bit like reaching into a computer and pulling out harddrive while it's running.  It's trying to load code and data from the SPI flash, but you've reconfigured that pin.

The ESP8266 brings code from SPI flash into some smaller chunk of internal RAM that it executes the instructions from.  So, I suppose it might be possible to get in the situation where you're continuing to run cached instructions while trying and failing to load data from the spi flash, which maybe could explain part of why the problem manifests the way it does for you.

In case you're wondering, it is possible to get the microchip used in the ESP8266 to load code from sources other than SPI flash, in which case GPIO6 might actually be available for your own general purposes, but not with the way most of modules are set up and used.  If you look at the pinout for the common ESP8266 modules, the smaller board mounted to your NodeMCU board, you'll notice GPIO6 doesn't actually leave the module; it just goes from the microcontroller to the SPI flash chip, which is all hidden away under the RF shield on the NodeMCU.

There *may* be other problems here with pin selection.  E.g., GPIO7 is not mentioned in the pin mapping, nor does it seem to leave common modules, so `#define relaylightb 7` is a bad sign.  Have a look through [this guide][2] with regard what you can do with each pin and what sort of behaviours they have at boot.  E.g. GPIO2 (your `relayrandom`) is "pin is high on BOOT, boot failure if pulled LOW" according to the guide.  So perhaps it will pulse your relay which you might not like.  And it may be that whatever circuit you have for the relay tugs GPIO2 toward LOW, which would also be bad.  Do keep in mind that the D# labeling is different from the GPIO# labeling.

---

I just checked GPIO7 (`randomlightb`), and like GPIO6 (`randomlight`), it was sufficient to execute `pinMode` with `OUTPUT` on it cause a reset.

  [1]: https://github.com/esp8266/Arduino/blob/2.7.4/variants/nodemcu/pins_arduino.h#L40
  [2]: https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/


body:
I am using the ESP8266 NODEMCU.
I am aware that the CH341 on the NodeMCU is bridged to the serial pins GPIO3(Rx) and GPIO1(Tx).
Hence, any data send on Rx and Tx is also visible on the serial monitor.

I need to interface MAX485 TTL-to-RS485 to the ESP8266 on different serial pins (other than GPIO3 and GPIO1).

Is there a way to configure other pins as Rx and Tx?

Please suggest any other ways to achieve this.

EDIT-1:
I need to use two serial ports at the same time (one with the CH341 and another with TTL-to-RS485). Please help with this.

title: ESP8266: Interfacing MAX485 TTL-to-RS485 on serial port

Answers: 2

body:
You can't redefine pins on the ESP8266. You can, though, use SoftwareSerial to emulate a serial port. There's plenty of examples.

Also you need to use the MAX**3**485 on 3.3V devices. The MAX485 is for 5V devices.

body:
Regarding this:

> Please suggest any other ways to achieve this.

The `SoftwareSerial` mention in Majenko's answer is one of those other ways.

[There's also][1] a `.swap()` function on the Serial interface that will remap the UART from its normal position talking to the host to GPIO15 and GPIO13.  If you only need to talk to one device at a time, that may also be an option.

There's also a second transmit-only UART (also mentioned in previous link), so if you only need to transmit on one of the interfaces, that is an option.  And there's the possibility of using the transmit-only UART together with using `SoftwareSerial` (or something like it) to complete the receive half.

Another option might be interpose a SPI-interfaced UART chip, between the ESP8266 and the RS485 transceiver, so that it's just SPI from the ESP8266 side.  It is also possible to find chips that are combined SPI-UART/RS485-transceiver, although the only one I've noticed thus far is a 5V part.

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/reference.html#serial


body:
As part of a project, I created a simulation of a juncture with 4 traffic signals. The time for the green signal is set based on a function that calculates it based on an algorithm (and it takes the no. of cars, motorcycles, buses and trucks as input).

The number of vehicles in the actual project is calculated using deep learning methods, however for the purpose of the simulation, I am using random() to generate these.

**Layout of the entire process**

 1. The green light of the current signal stays on for **gst**(**g**reen **s**ignal **t**ime) seconds, and the red light stays on for the rest of the signals.
 2. When gst seconds have elapsed, the green light of the current signal changes to yellow. Rest all are still red.
 3. The yellow light is intended to stay on for 5 seconds. In these 5 seconds, the gst for the next signal is calculated.
 4. 5 seconds after step 3, the yellow signal turns to red, and the next signal turns from red to green, (for an amount that has been calculated).
 5. This process keeps continuing. When we reach the 4th signal, the next signal should be set to 1.

**Code explanation**

 6. gst has been initialised to 20, and sn (current signal no.) has been initialised to 1.

 7. The if block for calculating the next signal number (and next2next,next2next2next) , is in lieu with point 5.

 8.  `signal` is an array that contains all the LED pins. The colours `red,yellow,green` have been attributed numbers 0,1,2 , so that the pin number of the "colour" LED of the "ith" signal can be given be `signal[i-1][colour]`

eg: "red" LED of the "2nd" signal is given by pin `signal[1][0]`, i.e pin `5` .

**Wiring and code**

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/WANxl.jpg

    int gst=20; //green signal time
    int ns=4;  //no.of signals
    int sn=1; //current signal number

    //pin numbers for LEDS: {{RYG for signal1},{RYG forr signal2}..}
    int signal[4][3]={{2,3,4},{5,6,7},{8,9,10},{11,12,13}};

    //indexes for the signal array
    int red=0;
    int yellow=1;
    int green=2;

    //pin number of "colour" of signal "i" is given by signal[i][colour]
    //example: red led of signal 3: signal[2][0]

    int c; //cars
    int b; //buses
    int m; //motorcycle
    int t; //trucks

    void setup()
    {
      for(int i=2;i<=13;i++){
        pinMode(i,OUTPUT);
      }
      Serial.begin(9600);
      randomSeed(analogRead(0));
    }

    void loop()
    {
        int next_sn= sn+1; //next signal
        if(next_sn==5)
          next_sn=1;

        int next2_sn= next_sn+1; //next2next
        if(next2_sn==5)
          next2_sn=1;

        int next3_sn= next2_sn+1; //next2next2next
         if(next3_sn==5)
          next3_sn=1;

       //current signal green (for gst seconds), rest all red.

        digitalWrite(signal[sn-1][green],HIGH);
        digitalWrite(signal[sn-1][red],LOW); //this line will make sense
                                          //for the 2nd iteration

        digitalWrite(signal[next_sn-1][red],HIGH);
        digitalWrite(signal[next2_sn-1][red],HIGH);
        digitalWrite(signal[next3_sn-1][red],HIGH);

        //for debugging purposes

       Serial.println(digitalRead(signal[sn-1][green]));

        delay(gst*1000);

        //gst seconds elapsed, now current signal should become yellow

        digitalWrite(signal[sn-1][green],LOW);
        digitalWrite(signal[sn-1][yellow],HIGH);

        delay(5*1000);

        //snapshot taken for calculating no. of cars, buses etc
        //for now, random numbers used

         c=random(10,17);
         m=random(5,10);
         b=random(0,5);
         t=random(0,5);

         //calculate gst

         gst=calc_gst(c,m,b,t);

      //make current signal red

        digitalWrite(signal[sn-1][red],HIGH);
        digitalWrite(signal[sn-1][yellow],LOW);

      //the next signal is our current signal for the next iteration
      //the green signal should turns on for gst seconds in the next
      //iteration,and the red signal turns off
        sn=next_sn;

      }

    //function for calculating green signal time

    int calc_gst(int c,int m,int b,int t)  //car bus motorcycle truck
    {

    int vehicle[4]={c,m,b,t};
    int avgtime[4]={2,1,2.5,2.5};
    int x=0;
    for(int i=0;i<4;i++){
    x+=vehicle[i]*avgtime[i];
    int gst= x/(ns+1);
    return gst;

    }

    }

**Problems**

At the start of the simulation, the green light of the first signal is not lighting up. (However Rest three are red, rightly so). After 20 seconds, the first signal turns yellow correctly. Then after 5 seconds, the second signal turns green correctly, but the first signal doesn't turn red. Subsequently, there are many instances where only 3 LEDs in total are lighting up instead of 4.

For testing why the green light is not lighting up, I added a line:

        //for debugging purposes
       Serial.println(digitalRead((3*(sn-1)+green)));

**The serial monitor shows 1, so why is the LED not lighting up??**

If there are any suggestions/corrections in my process, I will be obliged if someone can point it out.My code is heavily commented, and it explains it the entire process.

**Tinkercad link** if anyone wants to try out the simulation: https://www.tinkercad.com/things/1Le8m5ouHPc

title: LED not lighting up despite digitalRead displaying 1

Answers: 0


body:
Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to +180 when joy is forward or back.

I just cant seem to figure out the mapping or setup for the code for this part.
I remember seeing it done before but my google skils are failing me and i cant seem to find it again.
Thanks

title: Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to 180 when joy is forward or back

Answers: 2

body:
You can use the `map` function, see [Arduino Map Function][1].

So in your case, assuming a `value` of 0..1023 coming from an analog pin, where 0 needs to be mapped to -180 and 1023 to +180, you get

    int mappedValue = map(value, 0, 1023, -180, 180);

(note I assume you mean -180 when backwards, +180 when forwards).

  [1]: https://www.arduino.cc/reference/en/language/functions/math/map/

**UPDATE**

It seems value 0 (backward) needs to be mapped to 180, 512 (neutral) to 0, and 1023 (forward) to 180 (again).

For this you need two maps depending on the value:

    int mappedValue = 0;
    if (value < 512) // Backwards
    {
        mappedValue = map(value, 0, 511, 180, 0);
    }
    else // Forward
    {
        mappedValue = map(value, 512, 1023, 0, 180);
    }

body:
Try this one although, the others answered you properly :

    #include <Servo.h>
    Servo myservo;
    int potpin = 1;
    int val;

    void setup () {
        myservo.attach(9);
    }

    void loop () {
        val = analogRead(potpin);
        val = map(val, 0, 1023, 0, 360);
        myservo.write(val);
        delay(20);
    }

Connect the signal wire of your Servomotor to PWM pin number 9 of Arduino
Connect the output of your joystick to A1 pin of your arduino

Actually i'm not sure about one of that lines and i forgot the correct form, if didn't work, change this line :

    val = map(val, 0, 1023, 0, 360);

To this :

    val = map(val, 0, 1023, -180, 180);

I think both of them works

Good luck