# Question
Title: Converting my delays to millis for smoother operation
I need help converting my code to change out the `delay()` command into the `millis()` command for smoother operation.

Currently the code only moves after the delay is up. I would like the codes to run simultaneously.

This is my codes

```
#define aref_voltage 3.3
#include <Servo.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
Servo Servo1;
int led = 13;
int sw = 3;
int bz = 14;
int ldr = A1;
int lv = 0;
int rly = 7;
int buttonState = 0;
int servoPin = 8;
// the setup routine runs once when you press reset:
void setup()
{
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(sw, INPUT);
  pinMode(ldr, INPUT);
  pinMode(bz, OUTPUT);
  pinMode(rly, OUTPUT);
  digitalWrite(rly, LOW);
   Servo1.attach(servoPin);
  analogReference(EXTERNAL);
  Serial.begin(115200);

   if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
   Serial.println(F("SSD1306 allocation failed"));
   for(;;);
  }
}
void loop()
  {
  lv = analogRead(ldr); // read the value off the LDR
  Serial.print("LDR Value is: ");
  Serial.println(lv);
  delay(100);

  buttonState = digitalRead(sw); // Check switch 1 or 0
  Serial.println(buttonState);   //Show the state of pushbutton on serial monitor
  delay(100);

    while ( (lv >= 150) && (buttonState == HIGH) )
{
    delay(1000);
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(0,0);
    display.println("Relay On! ");      // here the message is inside the ""
    delay(1000);
    display.display();

    digitalWrite(rly, HIGH);//relay on 1 min
    delay(6000);
    tone(bz, 1500);//buzzer on for 30 sec
    delay(3000);
    digitalWrite(led, HIGH);//led flash at 1 Hz
    delay(3000);
    digitalWrite(led, LOW);
    delay(3000);

    digitalWrite(led, HIGH); // led 2 kHz
    delay(3000);
    digitalWrite(led, LOW);
    delay(3000);
    tone(bz, 2000); //buzzer at 2 khz
    delay(3000);
    noTone(bz);

    delay(2000);
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(0,0);
    display.println("Tank 2 Filled! ");      // here the message is inside the ""
    delay(1000);
    display.display();

    digitalWrite(rly, LOW); // relay low
    digitalWrite(led, HIGH);
    delay(5000);            // led flash 4Hz
    digitalWrite(led, LOW);
    delay(5000);

   Servo1.write(45); // Make servo go to 45 degrees
   delay(1000);

   Servo1.write(135); // Make servo go to 135 degrees
   delay(1000);

   Servo1.write(0); // Make servo go to 0 degrees
   delay(1000);
    break;
}
   if (buttonState == LOW)
  {
    digitalWrite(rly, LOW); // relay off
    digitalWrite(led, LOW); // led off
    delay(500);
   Servo1.write(0);     // Make servo go to 0 degrees
   delay(1000);
    noTone(bz); // buzzer off

  }
  }

```

# Answer
> 1 votes
Your delays are making the program jerky, so you have to get rid of them. :)

I have a lengthy discussion about this on my own web site, but basically you need to restructure so that you use a "state machine" and instead of delaying, make a note of the current time (using millis() function) and then do the next step when the time is up.

Just as an example, when you bake a cake you don't stop what you are doing for an hour and stare at the oven while it cooks, do you? You make a note of the time, and come back when the time is up.

One of the Arduino tutorials Blink without delay has an example of doing that.

The example code is (initial comments removed):

```
// constants won't change. Used here to set a pin number:
const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

```

This won't be a one-line change. You have to re-think how you go about handling time delays.

# Answer
> 1 votes
A while back I wrote an answer to another question about non-blocking programming, using "maybe-do" functions - functions that maybe do something if the conditions for doing it are met, typically a time-interval having passed. @nickgammon's excellent article (linked in his answer to this question) shows a similar structure that evaluates the condition within loop() rather than within the maybe-do/action function, as I did in my answer. Both ways work equally well.

It will be a good exercise to play with the BlinkWithoutDelay example sketch, and even write a couple of your own sketches that follow that general format. But soon you'll get tired of writing all of those `if( (millis() - previousMills) >= someInterval){` expressions and the bookkeeping of the various `previousMillis`es that goes with them - not to mention debugging the results of the inevitable typos! )-:

Once you've got the hang of:

```
is (current time - time when we previously acted) >= action interval{
   do the action;
   save the current time as the previous time;
}
// again, for the next action
// yet again, for each remaining action

```

, consider using a timer library such as SimpleTimer. Its job is to maintain all that bookkeeping for you, and to call your action functions at the right time.

You need to know a few things to use it - some of the same few things you needed to know to write code the previous way, but the more tedious parts will be done for you:

* How to make a set of timers;
* How to make an action function (called a 'callback function');
* How to set an interval (one-time or repeating) that the action- or callback-function will get called.
* How to run the timers so they can do their jobs.

**How to make timers**:

* First, you need the library: Visit this github page and click the green "Download Code" button (it's really a down-arrow, not the word "download"). In the menu that appears, click "Download ZIP".
* Open the file that you receive, "Arduino-SimpleTimer-master.zip" (how you do this depends on your computer's operating system). In the .zip file you'll find this folder structure:
`Arduino-SimpleTimer-master --- SimpleTimer --- (some folders and files)`
Drag the 'SimpleTimer' folder into the 'libraries' folder within your Arduino sketch folder. This library can serve every sketch you write from now on.
* Add the following include file to the top of your sketch: `#include <SimpleTimer.h>`
* Create a global set of timers: `SimpleTimer myTimers;` // creates 10 timers and makes them available for use.

**How to make a callback function** \- the function that runs your LED, stepper motor, or whatever other action you need taken at a certain time:

* A callback function does whatever is necessary to complete the timed task, *and nothing more*. For example, it might toggle an LED off if it is on, or on if it is off.
* An action function takes *no arguments* and *returns no value*. It *must have the type*:
`void toggleLED(void);`
Of course, you get to name your functions whatever you like.

**How to set an interval.** There are a number of ways, but you're likely to use these two for nearly everything - repeating, or one-time:

* `myTimers.setTimeout(time, toggleLED);`
sets a one-time timer that will call my \`toggleLED()' function *once* only, after "time" milliseconds. It returns the timer number that will be used. Mostly you can ignore that value for now.
* `myTimers.setInterval(time, toggleLED);`
sets a repeating timer that will keep calling my `toggleLED()` function *every* "time" milliseconds, for as long as the sketch runs. It also returns the timer number, and again, you can ignore that value for now.

**How to run the timers.**

* The timer library needs to be called **frequently** for your functions to get called at fairly precise intervals. Your `loop()` function should call `myTimers.run()` each time it runs.
* `loop()` should not do anything that takes very long, nor call any function that can take very long. Long tasks will disturb the precision of the timing with which your callback functions get called.
* Your loop function should look like:

```
void loop(){
   myTimers.run();
   // maybe some other fast code here
}

```

The `.run()` function checks each of your timers, and for every one whose time has expired, it calls its callback function (the one you specified when you called `.setInterval()` or `.setTimeout()`). This is how the timer library does its work, and why you need to call it frequently.

Now let's look put it all together in a **sample program to blink 2 LED's** at different intervals using SimpleTimers:

```
// SimpleTimer demo program
//    Blink 2 LEDs at different rates for 15 seconds, then turn off both LEDs and stop.

#include <Arduino.h>
#include <SimpleTimer.h>

/*****< Definitions >*****/
#define LED1    13  // the on-board LED
#define LED2    12  // an external LED

/*****< External and Global Declarations >*****/
SimpleTimer myTimers;       // define a set of timers
bool doHalt = false;            // a flag to tell loop() to stop

/*****< Local Function Prototypes >*****/
void toggleLED1(void);      // function to toggle the state of LED1
void toggleLED2(void);      // function to toggle the state of LED2
void setHalt(void);         // function to set the halt flag

void setup()
{
    // Set the pin modes for our two LEDs:
   pinMode(LED1, OUTPUT);
   pinMode(LED2, OUTPUT);

   // Turn off the LEDs:
   digitalWrite(LED1, LOW);
   digitalWrite(LED2, LOW);

    // Set up the blink intervals
    myTimers.setInterval(800L, toggleLED1); // start timer to blink LED1 slowly
    myTimers.setInterval(300L, toggleLED2); // start timer to blink LED2 rapidly

    // Stop the program after 30 seconds.
    myTimers.setTimeout(15*1000L, setHalt); // start timer to halt the program
}

void loop() {
    myTimers.run();                 // keep calling the timers as often as possible

    if( doHalt ){                       // if the halt flag is set,
        // Turn off the LEDs:
       digitalWrite(LED1, LOW); //    shut off the leds,
    digitalWrite(LED2, LOW);

    // Hang here, doing nothing
        while(1)                            //    and hang here forever.
            ;
    }
}

// Toggle the state of LED1
void toggleLED1(void){
    bool isOn = digitalRead(LED1);

    digitalWrite(LED1, !isOn);
}

// Toggle the state of LED2
void toggleLED2(void){
    bool isOn = digitalRead(LED2);

    digitalWrite(LED2, !isOn);
}

// Set the halt flag to stop 'loop()'
void setHalt(void){
    doHalt = true;
}

/***  end  ***/

```

This program does everything BlinkWithoutDelay does, but without the bookkeeping and the mechanics of calling your action functions. Those are all taken care of by the SimpleTimer library, leaving you free to concentrate on what your program is meant to do.

---
Tags: arduino-uno, teensy
---


# Question
Title: Can I power the arduino UNO through the 5V pin while I use USB cable to collect data?
I understand that if the Arduino is powered by Jack or Vin when the USB cable is connected, the internal circuitry would inderdict the USB powering. But what if I power the arduino througn 5V pin while the USB cable is connected? How does the internal circuit do the choice? Did I just connect the 5V power supply directly with USB port of the laptop (since the 5V rail directly connects 5V pin and USB port)? Is this allowable? Is this dangerous? Thank you!

# Answer
If u use the VIN pin of arduino, You shouldn't have a problem , as arduino selects it required voltage automatically, it's voltage regulator senses the voltage from USB and External source, if the power of the external source is higher than usb, the the power is bypassed to the External power. But don't know if you are using the 5 volt pin to turn on the arduino.

Well everything I said is applicable for UNO boards don't know other ones.

Thanks...
> 1 votes

---
Tags: arduino-uno, power, usb
---


title: i need help my coding for my fyp

text:
# Question
Title: i need help my coding for my fyp
how my coding works = 1 rfid card detect on first rfid reader and 2 rfid card detect on second rfid reader after that servo go to 90

my second rfid not detect

this is my coding

```
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
Servo  myservo;
int pos = 0;
int angle = 0;
int angle11 = 0;

#define RST_PIN2           8          // Configurable, see typical pin layout above
#define SS_PIN           9          // Configurable, see typical pin layout above
#define SS_PIN2          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN2 );   // Create MFRC522 instance.
MFRC522 mfrc522_2(SS_PIN2, RST_PIN2);   // Create MFRC522 instance.

void setup()
{
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin();        // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  mfrc522_2.PCD_Init(); // Init MFRC522 card
  Serial.println("Approximate your card to the reader...");
  Serial.println();
   myservo.attach(5);

}
void loop()
 {

// Look for new cards

if ( ! mfrc522.PICC_IsNewCardPresent()) {

return;

}

 // Select one of the cards

if ( ! mfrc522.PICC_ReadCardSerial()) {

return;

}

// Dump debug info about the card; PICC_HaltA() is automatically called

mfrc522.PICC_DumpToSerial(&(mfrc522.uid));

  delay(1000);
  // Look for new cards

  if ( ! mfrc522_2.PICC_IsNewCardPresent()) {

    return;

  }
  // Select one of the cards

  if ( ! mfrc522_2.PICC_ReadCardSerial()) {

    return;

    mfrc522_2.PICC_DumpToSerial(&(mfrc522.uid));

  }

  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "09 99 55 B2") //change here the UID of the card/cards that you want to give access
 {
String content= "1";
  byte letter;
  for (byte ii = 0; ii < mfrc522_2.uid.size; ii++)
  {
     Serial.print(mfrc522_2.uid.uidByte[ii] < 0x10 ? " 0" : "1 ");
     Serial.print(mfrc522_2.uid.uidByte[ii], HEX);
     content.concat(String (mfrc522_2.uid.uidByte[ii] < 0x10 ? " 0" : "1 "));
     content.concat(String (mfrc522_2.uid.uidByte[ii], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "09 99 55 B3") //change here the UID of the card/cards that you want to give access

      myservo.write(angle); delay(3000);
   for(angle = 0; angle > 90; angle11)
    myservo.write(angle11);
    delay(3000);

    myservo.write(angle11); delay(3000);
   for(angle = 90; angle11 > 0; angle)
    myservo.write(angle);
    delay(3000);
    }

 else
 {
    Serial.println(" Access denied");
    delay(3000);

    }
  }

```

# Answer
> 1 votes
Right at the start of your loop you have this (and other similar constructs):

```
if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
}

```

That means that if no new card is present on reader 1 then the rest of the loop is ignored. Nothing else can happen.

You need to restructure your whole program so that it works in the complete opposite way - instead of saying "If there's no card do nothing" you should say "If there is a card then do something".

---
Tags: arduino-uno, rfid
---


# Question
Title: what to write instead of delay() in interrupt function?
I was trying to develop a traffic light signal controller . when the button is pressed, the pedestrian green light will turn on faster than before . I used delay() in Interrupt function, But it is not working as expected . I am totally new in Arduino coding. My whole code is below:

```
int carred = 11;
int caryellow = 10;
int cargreen = 9;

int padred = 13;
int padgreen = 12;

int padpushbutton = 3;
int buspushbutton = 2;

void setup(){
  pinMode(carred , OUTPUT);
  pinMode(cargreen , OUTPUT);
  pinMode(caryellow , OUTPUT);

  pinMode(padgreen , OUTPUT);
  pinMode(padred , OUTPUT);

  pinMode(padpushbutton, INPUT_PULLUP);
  pinMode(buspushbutton,INPUT);
  attachInterrupt(digitalPinToInterrupt(padpushbutton), padcontrol,CHANGE);
 attachInterrupt(digitalPinToInterrupt(buspushbutton), buscontrol,CHANGE);
}
void loop()
    {
     carchangeLights();
 }
void carchangeLights(){

   //turn  carred,padgreen off padred high and cargreen on for 10 seconds
  digitalWrite(carred, LOW);
  digitalWrite(caryellow,LOW);
  digitalWrite(padred, HIGH);
  digitalWrite(cargreen, HIGH);
  delay(10000);

   //cargreen off,  turn on caryellow for 4 seconds

  digitalWrite(cargreen, LOW);
  digitalWrite(caryellow, HIGH);
  delay(4000);

   // turn caryellow and padred off,turn on padgreen, turn on carred for 7 seconds
  digitalWrite(caryellow, LOW);
  digitalWrite(padred,LOW);
  digitalWrite(padgreen,HIGH);
  digitalWrite(carred, HIGH);
  delay(7000);
  //turn padgreen off and padred high , caryellow high for 3 second
  digitalWrite(padgreen, LOW);
  digitalWrite(padred, HIGH);
  digitalWrite(caryellow, HIGH);
  delay(3000);

}

void padcontrol(){

  int red = digitalRead(carred);
  int yellow = digitalRead(caryellow);
  int green = digitalRead(cargreen);

  if (red == HIGH && yellow == LOW ) {
    digitalWrite(carred, HIGH);
    delay(2000);
    digitalWrite(padred, LOW);
    digitalWrite(padgreen, HIGH);
    delay(15000);
     }

  else if(yellow == HIGH && red == LOW){
     digitalWrite(caryellow, HIGH);
    delay(2000);
    digitalWrite(caryellow,LOW);
    digitalWrite(carred,HIGH);
    digitalWrite(padred,LOW);
    digitalWrite(padgreen,HIGH);
      delay(15000);
    }
  else if(yellow == HIGH && red == HIGH) {
   digitalWrite(caryellow, HIGH);
    delay(1000);
    digitalWrite(caryellow,LOW);
    digitalWrite(padred,LOW);
    digitalWrite(padgreen,HIGH);
      delay(15000);
    }
   else{
    digitalWrite(cargreen,LOW);
    digitalWrite(caryellow,HIGH);
    delay(3000);

    digitalWrite(caryellow,LOW);
    digitalWrite(carred,HIGH);
    digitalWrite(padred,LOW);
    digitalWrite(padgreen,HIGH);
    delay(15000);
   }

}

void buscontrol(){

  int red = digitalRead(carred);
  int yellow = digitalRead(caryellow);
  int green = digitalRead(cargreen);

  if (red == HIGH && yellow == LOW ) {
    digitalWrite(carred, HIGH);
    delay(3000);
    digitalWrite(carred,LOW);
    digitalWrite(padgreen, LOW);
    digitalWrite(padred, HIGH);
    digitalWrite(caryellow, HIGH);
    delay(2000);
    digitalWrite(caryellow,LOW);
    digitalWrite(cargreen, HIGH);
    delay(10000);

     }

  else if(yellow == HIGH && red == LOW) {
    digitalWrite(padgreen,LOW);
    digitalWrite(padred,HIGH);
   digitalWrite(caryellow, HIGH);
    delay(2000);
    digitalWrite(caryellow,LOW);
    digitalWrite(cargreen,HIGH);
      delay(10000);
    }
  else if(yellow == HIGH && red == HIGH) {
   digitalWrite(caryellow, HIGH);
    delay(1000);
    digitalWrite(carred,LOW);
    digitalWrite(caryellow,LOW);

    digitalWrite(padgreen,LOW);
       digitalWrite(padred,LOW);
     digitalWrite(cargreen, HIGH);
      delay(10000);
    }
   else{
    digitalWrite(padred,HIGH);
    digitalWrite(cargreen,LOW);
    delay(10000);

   }
}

```

# Answer
> what to write instead of dely() in interrupt function?

Nothing. An interrupt service routine (ISR) should not do any things, that take long. That will block any other things from happening, for example Serial communication (which is done by interrupts in the background).

`delay()` does not work in an ISR, because it relies on the `millis()` counter to increment. But that is done in another ISR. While one ISR is running, no other can run at the same time. Thus `delay()` waits forever, that the `millis()` counter increments.

**What to do instead?**

Instead you should only use the ISR to set a simple flag variable, for example of type `boolean` (because it should be a single byte type). Then in your main code (meaning inside `loop()`) you check for this flag. When it is set by the ISR, you execute the corresponding code and reset the flag. Be sure to declare the flag variable as `volatile`, so that the compiler knows, that is can change at any time.

---

That said, you should really ditch all the `delay()` calls. Instead use a non-blocking coding style involving `millis()` like in the `BlinkWithoutDelay` example, that comes with the Arduino IDE. There are tons of tutorials and explanations about that on the web and this site. Just search for it. Using a non-blocking coding style is needed, if you want the code to be responsive while doing long timed things.

Also you should look into Finite State Machines (FSM). Thats a very powerful principle, that will come in useful. It fits exactly on a traffic light project. I have once wrote a longer explanation about FSMs in my answer to this question, though you can also google something like "Arduino fsm". You basically divide the behavior of the project into individual states. The current state is hold by a variable. By changing that variable you transition between states. For example `padcontrol()` could change the state variable to the state for the pedestrian light. I strongly suggest, that you learn that principle to structure your code. I can attest, that it is really helpful.
> 1 votes

---
Tags: arduino-uno, interrupt
---


# Question
Title: Send data to Programmable Power supply from Arduino by RS232
I have a programmable power supply, which has serial communication port. If I send a string "VSET1:11.00" then power supply will be set to 11.00V. But, I need to write a program which will increase the voltage of power supply by 0.10V For ex from 0V to 11.00V in incrementing steps of 0.10V. Also, power supply needs a fixed data frame format like Parity bit, Data bits, stop bit. So, how to create a data frame structure and send from arduino.

Do I need to use Software Serial library?

PS. I'm new to arduino, so may sound foolish.

# Answer
> 3 votes
First you will need a TTL to RS-232 adaptor. These are most commonly known as the "MAX232" and is available as a little module.

This will convert the 0-5V TTL signal the Arudino produces into the ±10V signal that RS-232 uses. There's plenty of tutorials online about how to use them.

Then you need to generate the signal. Yes, for the Arduino UNO the SoftwareSerial library is what you want. Again there's plenty of tutorials on using it.

To actually send the instructions it may be something like:

```
#include <SoftwareSerial.h>

SoftwareSerial PSU(10, 11); // RX, TX

void setup() {
    PSU.begin(9600);
}

void loop() {
    for (int i = 0; i < 11000; i += 100) { // I'm working in millivolts here.
        PSU.print("VSET1:");
        PSU.println(i / 1000.0, 2); // Convert millivolts into volts with 2 DP
        delay(10); // 10ms delay
    }
}

```

I haven't tested it, but that should give you 0-11v rising at 0.1v per 10ms.

---
Tags: arduino-uno, serial, rs232
---


title: Stepper motor not working as expected

text:
# Question
Title: Stepper motor not working as expected
Kunal Gupta: Guys plss help me .... I am having issues in using stepper motor

I have tried both 28bjy with uln2003 and l293d .. giving it output supply of 5V . Motor is vibrating but its shaft is not moving. And even if shaft runs then it is different from what is expected by the logic of code

Similarly tried NEMA 17 stepper motor 4.5 KG using drv8825 driver and L293D driver ... Giving 12 v external supply.

And same results as 28bjy .... motor vibrating but its shaft is mot moving as expected or absolutely not moving

I have read and understood all the concept of driving stepper motor by full step method and hafl step method ....and using at first direct examples from net .. but still not figuring out what is the problem

# Answer
Try lowering the rpm in the code. I had a similar issue with anything over about 18rpm using certain libraries with certain stepper motors.
> 1 votes

---
Tags: arduino-uno, arduino-mega, stepper, stepper-motor, l293d
---


# Question
Title: what happens on Arduino power-on, and how long does it all take?
Here's what I think happens and how long it takes (FIXME means I don't know). I'd like to end up with solid max times for everything if possible.

* Power-on, input caps to the 328P begin charging and Vcc to the 328P rising
* From the time it first comes to life, internal 328P hardware holds an internal reset line low.
* Vcc to 328P climbs past the power-on reset voltage threshold V\_pot, which has a maximum value of 1.6V (see the ATmega328P\_datasheet\_revision\_DS40002061A.pdf Table 29-11). For a 9V battery with a typical internal resistance of 2 ohms, the time constant with the ~100 uF of input capacitance on the Arduino is RC = (2 * 0.0001) = 0.0002 s. So this normally happens pretty fast, but note that if additional loads are connected to the Arduino Vcc or Vin things might take longer.
* A reset timer on 328P begins running. When it expires the internal reset line will be released. How long this timer will run depends on fuse settings. For the default Arduino fuse settings the timer will run for about 65 ms. For a 3.3V Arduino variant the typical time will be slightly longer (~69 ms). See ATmega328P\_datasheet\_revision\_DS40002061A.pdf Table 29-11 Chapter 9 for details.
* The PD7 line of the ATMEGA16U2 chip on on the Arduino holds the external reset line low past the point in time at which the internal reset is released, which causes the EXTRF bit of the MCUSR register on 328P the 328P to end up set (indicating an external reset). FIXME: does it actually work like this (hold it low longer)? FIXME: How long exactly?
* The external reset is released by the ATMEGA16U2
* The bootloader on the 328P begins executing
* The bootloader examines the MCUSR and finds that EXTRF is set, but WDRF of MCUSR is not set. It therefore quickly flashes the on-board LED several times and the attempts to download a new program over the serial line. This process takes about 1.6 s total.
* The download attempt terminates with a watchdog timer timeout and consequent watchdog timer reset. The EXTRF bit of MCUSR remains set (it is sticky and is only cleared by a power-on reset or explicit 0 write). Time: pretty quick
* The bootloader starts executing (again). Time: pretty quick
* The bootloader examines the MCUSR and finds that the EXTRF and WDRF bits of the MCUSR are both set. It interprets this to mean that the bootloader just executed and terminated due to a watchdog timeout, i.e. it decides that an upload attempt has already been made. It therefore clears the WDRF flag (since it thinks it probably set it itself) and jumps to the start of the application flash instead of making an upload attempt. Time: pretty quick
* All the setup code required to provide the C environment your main() program requires runs. This includes for example copying global variable intial values from flash to RAM, etc. Time: FIXME?
* main() begins executing.

# Answer
> 1 votes
This is something that is far far easier to measure than to try and calculate.

Here's an Arduino Uno R2 with a simple sketch that just turns on D2. Green is the power (7V to the barrel jack) and yellow is D2.

As you can see it takes 1.544 seconds (according to the resolution of my oscilloscope which, over those time scales, isn't that great) before D2 is driven high.

The sketch is simply:

```
void setup() {
  pinMode(2, OUTPUT);
  digitalWrite(2, HIGH);
}

void loop() {
}

```

---
Tags: arduino-uno, arduino-mega, bootloader, time
---


# Question
Title: TinyGPS++ Question about gps.encode(ss.read())
I am trying to make an oled gps display, however when looking at multiple examples and other people's code, I am seeing that people are using different methods. I see some code that has `gps.encode(ss.read());` and other people use `if gps.encode(ss.read())`. I am confused on why this is. Also, people either use `.isUpdated`, or `.isValid`, when checking for location/speed, etc. On the TinyGPS++ page it talks about these, but does not say what should be used for certain applications.

# Answer
From http://arduiniana.org/libraries/tinygpsplus/

**Validity, Update status, and Age** You can examine an object’s value at any time, but unless TinyGPS++ has recently been fed from the GPS, it should not be considered valid and up-to-date. The **isValid()** method will tell you whether the object contains any valid data and is safe to query.

Similarly, **isUpdated()** indicates whether the object’s value has been updated (not necessarily changed) since the last time you queried it.

Lastly, if you want to know how stale an object’s data is, call its **age()** method, which returns the number of milliseconds since its last update. If this returns a value greater than 1500 or so, it may be a sign of a problem like a lost fix.
> 1 votes

---
Tags: arduino-ide, library, tinygps
---


# Question
Title: Text send via HC-05 is broken up by first character on the receiving end?
On the receiving end, I have an mit app inventor app which acts like a client.

In arduino, I check for connection status and do a serial write to send the text. The code for that is below:

```
#include <SoftwareSerial.h>

#define D2 2
#define D3 3
#define BT_STATE_PIN 4

SoftwareSerial BTSerial(D3, D2);
long lastMark;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(38400);
  BTSerial.begin(9600);
  pinMode(BT_STATE_PIN, INPUT);

  int counter = 0;
  lastMark = millis();
}

bool isBTConnected() {
  return (digitalRead(BT_STATE_PIN) == HIGH);
}

void sendText(char* message) {
  Serial.println("SEND: " + String(message));
  if(isBTConnected()) {
    BTSerial.write(message);
  }
  else {
    Serial.println("did not send");
  }
}

int msgCount = 0;
void loop() {
  long now = millis();

  if(now - lastMark > 2500) {
    msgCount++;
    String msg = "This is a really really long MSG" + String(msgCount);
    sendText(msg.c_str());
    if(msgCount == 5) {
      msgCount = 0;
    }
    lastMark = millis();
  }
}

```

This is how the device is wired currently:

simulate this circuit – Schematic created using CircuitLab

On the app inventor side of things, I have a very simple app that connects to the bluetooth module; it listens for anything received, and then just receives the text.

aia file

Here is a pic showing the issue I am facing currently:

Sometimes the breaking up happens randomly at some other place. Hoping someone can help sort this issue.

# Answer
Without having experience in AppInventor, I see the following problem:

In your app you are outputting the received data regularly with a timer in form of distinct messages. This code can naturally only display text, that was already received. You seem to think, that only because you use a single line oft code on Arduino for sending the message data, the data would be send in one big chunk. For Serial that is not the case. Actually the `write()` function only fills the libraries buffer and the actual data will then be send serially (thus the name). There is nothing like a chunk of data or a message on a serial interface, unless you yourself impose this principle on the data stream. All the bytes in the libraries buffer are the same and are being send in the order of the buffer. Moreover Bluetooth does consist of packages of data, but they will be automatically packed; in a way that will not correspond to your messages.

So in the end, arbitrary parts of your message will be received by the phone at arbitrary times, that highly depend on timing conditions. In your code you should constantly receive the data and only display a message, when you have received an `\n` character, which is the delimiter of a message. It is a very common and helpful technique to first receive a full message and then processing it, when the message is complete.
> 0 votes

# Answer
I did something similar (multiBT) using HC-05 and PC BT, with the same App. Results: all the incoming data from the PC\_BT to the phone are right, but with the HC-05 sometimes is chunked as @deostrol show. I think is a bug with the HC-05 firmware.

To correct this, I've implemented StartBegin and StopFinish character in the received string before use.
> 2 votes

---
Tags: arduino-nano, hc-05
---


# Question
Title: Streaming integer data from Arduino to Java, integer greater than 0xFF
I need to send how many milliseconds elapsed since the beginning of the time the arduino runs to java using Serial.write(). However, the largest integer that I can throw in there is 255, naturally since the largest 1 byte value we can send is 0xFF.

But if we have an integer like 6000 miliseconds that I want to send into java, how can I do this? I was initially thinking of just checking if the number is greater than 255 then bit shift it by 4 to the left then doing `number<<4 & 0xFF00` and also writing `(number<<4)>>8 &0xFF`

**But**

1. that doesn't work for numbers really large and
2. I believe when I stream these int values into Java they get read as characters...

how do I fix this?

**EDIT** I've created a second version as the following

```
void sendData(int a ){
  while(a>0){
    Serial.write(a&255);
    a = a>>8;
  }
}

```

on the java side I have to somehow multiply the correct x for 16^(x) to the value that we receive since everything is received backwards I'm not sure if this is the best way to go since we don't necessarily know how many bytes that we'll receive

# Answer
I'm assuming you will be using the Arduino `millis()` function for keeping time. The output of the `millis()` function in the Arduino environment is a 32-bit unsigned integer\*.

A 32-bit integer can be split into 4 x 8-bit bytes. To keep things simple you could program the Java receiving side to always expect 4 bytes (or whatever amount you need, see \*). Assuming 32 bits is enough, you could use the following:

```
void sendData (uint32_t uptime) {
    int i;
    for (i = 0; i < 4; i++) {
        Serial.write (uptime & 255);
        uptime = uptime >> 8;
    }
}

```

On the Java side, you would receive the lowest order byte first, and you could reconstruct the 32-bit value by taking the first received 8-bit value, adding the second value shifted left by 8 bits (=multiplied by 256), adding the third value shifted left by 16 bits (=multiplied by 65536) and adding the fourth value shifted left by 24 bits (=multiplied by 16777216). Java is not my strong point so I will leave that to you.

BTW, is there a particular reason you have to use `Serial.write()`? It would be much easier to just write the value as a string with `Serial.println()`.

**After 2^32 milliseconds (a little under 50 days of uptime) the 32-bit counter that feeds the `millis()` function will wrap around to 0. You could keep the amount of times that the timer has overflowed in a separate (integer) variable and make that (i.e. bytes 5 and onward) part of your output.*
> 2 votes

---
Tags: arduino-uno, programming, input, java
---


# Question
Title: How to get an angle from two ultrasonic sensors
I am building a chair for a special 4 year-old with cerebral palsy, I thought it would be a good idea to add two distance sensors on each arm of the chair to measure the angle at which he presses buttons(a gaming chair). Normally I would figure this out on my own but I don't have much time to finish so I thought i'd ask the experts. What's the best way to use to ultrasonic sensors data to produce an angle?

# Answer
> 2 votes
Your question is unclear. You say you want "...to measure the angle at which he presses buttons". I don't know what that means.

If you're using ultrasonic sensors those measure distance. buttons tend to be fixed in place. Maybe you're talking about having a joystick on the gaming chair? Two-axis joysticks should let you input an X and a y value.

If you're trying to calculate the angle between a pair of ultrasonic sensors and something that is in their "line of sight" (line of sound?) then you'd use trig.

You would have your sensors at a known distance from each other. You'd measure the distance to each sensor, form a triangle out of all 3 distances, and use the law of cosines to calculate the angles.

The formulas from that page are:

cos(C) = a² + b² − c²/2ab

cos(A) = b² + c² − a²/2bc

cos(B) = c² + a² − b²/2ca

(Where upper case letters denote the angles of the triangle at a vertex, and lower-case letters denote the legs of the triangle. See the illustration on that page.)

```
 SensorA
    \
     \      SensorB
      \       /
       \     /
        \   /
         \ /
          V
        object

```

(one leg would be the SensorA-to-SensorB distance. Another leg would be the SensorA-to-object distance, and the 3rd leg would be the SensorB-to-object distance.)

However, all of that will only work if the object you are detecting is in the range of angles in which your sensors are able to detect objects, and in the range of distances they provide accurate readings.

## Edit:

When I copied the formulas from the source site, the superscripts were lost. I've edited them back so the formulas are more readable.

---
Tags: ultrasonics
---


# Question
Title: Button and twist knob to send keystroke to PC
As a novice, I would like to create a small breadboard with 5 items on it. 3 toggle buttons, and two constant spin (ie. no stop at 360 degrees) knobs.

Is then like the bottoms to send what ever key stroke (single key pee click) to the pc as if it was from a keyboard (maybe even a shift+key?)

And the knobs send keystrokes too. On each “click” as I don’t want smooth knobs. Ones that kinda of click per degree. Not sure how to explain that.

It’s for Flight Simulator. Doing it with a mouse, from distance, with small buttons is challenging. And twisting knobs with the mouse in bumpy conditions is even worse.

So planning on using my Nana, connected to a USB port for Power and signal.

Can anyone guide me in the right direction? Would I need 3rd party software to convert signals to keystrokes on the pc?

I think there is a keyboard library - but from what I read, it takes over your keyboard. That is, once the Arduino is connected and listening - the main keyboard no longer functions. Is that a misunderstanding? I need both to be operational.

I’m guessing something like this as it has “positions”. https://www.ebay.com.au/itm/Rotary-Encoder-Module-Arduino-Compatible/232624628710?hash=item36298223e6:g:JIIAAOSwg31aVFVW

# Answer
> As a novice, I would like to create a small breadboard with 5 items on it. 3 toggle buttons, and two constant spin (ie. no stop at 360 degrees) knobs.

Those knobs are called "Rotary Encoders".

> Is then like the bottoms to send what ever key stroke (single key pee click) to the pc as if it was from a keyboard (maybe even a shift+key?)

Then you really want an Arduino with a "native" USB connection, like the Leonardo or Micro.

> Can anyone guide me in the right direction? Would I need 3rd party software to convert signals to keystrokes on the pc?

Not with a Micro or Leonardo - you just use the `Keyboard.h` library. If you want to use your Nano then yes, you can only talk serial, and you will have to have some third party software that interprets serial commands and injects keyboard signals into your OS. I think there's some Python projects around that do that kind of thing. Or there is "professional" software, like 232key that can do it for you.
> 2 votes

# Answer
The twisty click per degree thing is called a rotary encoder.

You can already send serial commands to a computer, so to keep it simple, I'd try to find a way of turning the serial commands into a keyboard click.
> 1 votes

---
Tags: arduino-nano, usb, keyboard
---


# Question
Title: How do I control a conveyor to start and stop in same location using optical rotary encoder
I am a complete novice at arduino. I just want to know if this is possible before I start investing in components. I need to start and stop a chain drive conveyor {can't slip} powered by a 12 volt motor in the exact same place each time I manually start the cycle. I want it to stop automatically. The controller would have to power a relay to power the motor due to high amp draw of motor. This is on a piece of equipment without access to any other power supply but a 12 volt battery. I am looking at an optical rotary encoder to count the revolutions of the shaft. I would count the revolutions the shaft makes between my start and stop point and I assume enter that in the program. Is this possible? Thanks

# Answer
> 1 votes
Although your solution would work, it seems open to problems such as missed clicks, starting at a different place etc. A better, more robust and error free solution might be to use a hall sensor. Essentially what a hall sensor does is close a switch when a megnetic force is applied. So all you have to do is add a magnet to your conveyor/chain. This way, you can easily control where you want it to stop just by moving the magnet, and it doesn't matter what the starting position is because it will always stop as soon as the megnet reaches the sensor.

---
Tags: programming, motor, relay, battery, rotary-encoder
---


# Question
Title: Using Arduino Uno as USB to serial converter
Can I use my Arduino Uno as a USB to serial converter to program my Raspberry pi 0 over serial communication?

My idea: Computer connects to Arduino via USB \> Arduino connects with Raspberry pi 0 via GPIO pins.

How do I go about this?

# Answer
> 2 votes
You may also put Arduino in a reset state then Rx & Tx lines of serial converter will be free.

# Answer
> 1 votes
If you load an empty program in your arduino, and make the folowing connections:

Pi --\> Arduino

Pin 8 --\> Pin 1

Pin 10 --\> Pin 0

Gnd --\> Gnd

than you should see your linux console in the arduino serial program is you set the baudrate to 115200.

This method will work for the raspberry pi models without wifi. On the wifi models the pins on the pi will be different.

The Arduino uses FTDI usb-to serial converter. This converters uart side is connected to the AVR-chip via pin 0 and 1. If you load an empty program in your arduino, it wil not use these lines. Now you can connect directly to the FTDI chip thru this pins. The converter does not care if it is communicating with the arduino or the pi over these lines.

# Answer
> 1 votes
In the arduino ide, go to file \> examples \> arduino as isp. Might be a good starting point.

Seems like a lot of work though. If I were in that situation then I'd either use an ethernet cable and SSH, or, use a mobile phone as a WiFi hot-spot.

---
Tags: serial, usb
---


# Question
Title: No response in Serial Monitor from es8266 with Arduino nano
I have exactly this model of esp8266:  I removed Atmega328p IC from Arduino, and powered Arduino with USB cable. After all, I made this connection combinations:

```
1)
ESP Tx > Arudino Tx
ESP Rx > Arduino Rx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd
ESP GPIO0 > GND

2)
ESP Tx > Arudino Rx
ESP Rx > Arduino Tx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd
ESP GPIO0 > GND

3)
ESP Tx > Arudino Tx
ESP Rx > Arduino Rx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd

4)
ESP Tx > Arudino Rx
ESP Rx > Arduino Tx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd

```

I checked both 9600, and 115200 baud, but on any of them I did not get a reply to the `AT` command. Have I done something wrong? I get weird characters when disconnecting ESP's `GND` wire, so some communication exists.

# Answer
If it is not a genuine Arduino (Chinese clone probably) and it has the CH340 USB to Serial converter chip, then it will not work as the digital Signal on TX does not get pulled to ground when transmitting a digital LOW, (if that's the right way to say it). There seem to be resistors on the board that cause this effect, or something. I do not guarantee that this is your problem but it's highly likely.

Use an FTDI USB to Serial board or similar and you might have better results.
> 1 votes

---
Tags: esp8266
---


title: Drawing a bar graph in a LCD

text:
# Question
Title: Drawing a bar graph in a LCD
I'm getting my first steps on Arduino and I'm trying to do an exercise where I have to draw a graph bar in a 16x2 LCD that indicates the values read from a vector of 16 integer elements amplified by the value read from a potentiometer (connected to the analog pin A0) during runtime. The graph should change in real-time as I move the cursor of the potentiometer to the left or right.

I have the following code structure:

> void loop() {
>
> // Read the 16 vector elements and map then to the screen height ...
>
> // Print out their values multiplied by the value read form the potentiometer, to the serial monitor ...
>
> // Draw a bar for each one of the vector elements (you will have 16 bars in the end)...
>
> // If the graph has reached the screen edge do not amplify it anyfurther. If it has reached the bottom, do the same
>
> //Wait a bit. Start drawing everything from scratch.

So far what I have is:

```
#include<LiquidCrystal.h>

// Create an LCD object and connect control wires

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int vector[16] = {3, 7, 10, 15, 28, 12, 43, 1, 6, 19, 29, 23, 54, 76, 57, 66};

int value=0;

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

  // Specify the LCD's number of columns and rows

  lcd.begin(16, 2);
}

void loop(){

  value = analogRead(A0);

  for(int i=0; i<16; i++){
    int vector2[i] = map(vector[i], 0, 1024, 0, 20);
    Serial.println(vector2[i]*value);
  }
}

```

However I'm getting the following error so far:

```
 In function 'void loop()':
28:25: error: array must be initialized with a brace-enclosed initializer
 exit status 1

```

Also I can't think of a way to do the last 3 steps of the code structure I have. I know that if i would want to print a bar like a character I could do:

```
#include<LiquidCrystal.h>

// Create an LCD object and connect control wires

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
byte bar[] ={B11111, B11111, B11111, B11111, B11111, B11111, B11111, B11111};

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

  // Specify the LCD's number of columns and rows

  lcd.begin(16, 2);
  lcd.createChar(0, bar);
}

void loop(){
lcd.setCursor(0,0);
cd.write(byte(0));

}

```

But even this would only print a column in the first row and column and not in both rows and first column of the LCD.

Can someone help me with the error I already have and give me some lights on how to do the last 3 steps of the code structure?

# Answer
First off you're going to need to define some custom characters. There's examples for how to do that. You want characters that gradually fill up from the bottom to full, such as:

▁ ▂ ▃ ▄ ▅ ▆ ▇ █

Now, you have 8 lines per character and two lines of characters, which gives you a possible drawing range of 0-16. So you need to `map` your maximum range into that 0-16 span.

Finally you want to create a function to draw a single bar. This will take two parameters - the position of the bar (x) and the height of the bar (y). A simple little bit of mathematics later and you can work out what to print in the upper and lower characters.

* If the value is = 0:
    + Both top and bottom are spaces
* If the value is \<= 8:
    + The bottom character is the one with the same number of lines as the value
    + The top character is empty.
* If the value is \> 8:
    + The bottom character is the one with all 8 lines filled
    + The top character is the one with the value - 8 number of lines filled.

So you may end up with something like (note - untested):

```
const uint8_t bars[8][8] = {
    { 0, 0, 0, 0, 0, 0, 0, 0xff },
    { 0, 0, 0, 0, 0, 0, 0xff, 0xff },
    { 0, 0, 0, 0, 0, 0xff, 0xff, 0xff },
    { 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff },
    { 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff },
    { 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff },
    { 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff },
    { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff },
};

void setup() {
    // other stuff, like setting up the LCD...

    for (uint8_t i = 0; i < 8; i++) {
        lcd.createChar(i, bars[i]);
    }
}

void drawBar(uint8_t x, uint8_t y) {
    char top, bot;

    if (y == 0) { // Both spaces
        top = ' ';
        bot = ' ';
    } else if (y <= 8) { // Bottom has bar graph, top is empty
        top = ' ';
        bot = val - 1; // Characters start at 0, so 1-8 is 0-7
    } else if (y <= 16) { // Bottom is full, top has bar graph
        top = (y - 9); // Characters start at 0, so 9-16 is 0-7
        bot = 7;
    } else { // Overflow - both top and bottom full
        top = 7;
        bot = 7;
    }

    lcd.setCursor(x, 0);
    lcd.write(top);
    lcd.setCursor(x, 1);
    lcd.write(bot);
}

void loop() {
    // your stuff in here
}

```

Then to draw a bar you just call `drawBar` 16 times:

```
for (uint8_t i = 0; i < 16; i++) {
    uint8_t y = <your calculation on vector2[i] here>
    drawBar(i, y);
}

```

If you've done it right you should end up with something like:

```
▁█ ▄ ▆█▇   ▃ ▃▇
██▃█▇███▅▆▇█▆██▃

```
> 1 votes

---
Tags: arduino-uno, lcd
---


# Question
Title: Combining an NRF24L01 transmitter/receiver with an Adafruit Motor Shield V1?
I'm making a vehicle project as a way to learn Arduino. I've set up motor control for a number of DC-motors plus a servo via an Adafruit Motor Shield V1 that I picked up.

Everything works fine, but now I've started looking at adding wireless control for the setup using a second Arduino and two NRF24L01 wireless units. However, reading up on the specs for the NRF24L01 it seems it requires pin 12 on the Arduino, which is already in use by the motor shield.

So, can I combine a NRF24L01 and an Adafruit Motor Shield V1? And if so, how?

If it's not possible, what would be the pros and cons of slaving the shielded Arduino to a Nano that would carry the NRF24L01, versus replacing the Adafruit motor shield with external DC motor driver(s)?

Edit:

I now found this previous question:

Motor shield and wireless transceiver compete for same pins

A difference in my project is that I'm not using stepper motors, so perhaps that makes a difference?

# Answer
> 2 votes
One of the problems of the Uno is that the hardware SPI pins conflict with some of the PWM pins. If you want lots of motor control then you have it at the expense of no SPI. If you want SPI then you have it at the cost of reduced motor control.

The V1 shield uses a shift register for some of the motor signals, and that has to fit its signals in around the available PWM pins, so that as well has spilled over into the SPI pins (since you can't use SPI because of the PWM pins that really doesn't matter).

So no SPI means no nRF24L01. Or does it?

You *could* (though I don't know of any libraries that handle this) use "bit-banged" software SPI on other pins (such as the analog pins) to communicate with the nRF24L01. Your mileage may vary with that, but it is technically possible - as long as you can find (or write) the right software support for it.

Would it be better to throw more hardware at it and have the wireless connection on a dedicated MCU? I would say, yes. Not only does it mean you can use existing libraries to communicate with the nRF24L01 without any worries of conflicting pins, but you get to compartmentalise your software into discrete units that don't interfere with each other. Parallel processing :)

How to communicate between the two? Well, you have I2C available on the analog pins A4/A5, which is well documented and plenty of examples. Or you could use serial, although the 328P's lack of serial ports means that you'd probably be working with SoftwareSerial which is ropy at best. I'd pick I2C out of those two TBH.

---
Tags: arduino-uno, nrf24l01+, arduino-motor-shield
---


# Question
Title: Using TX/RX serial pins to communicate over USB
I'm using an Arduino Nano with an Atmega 328p.

I would like to attach and use a different USB port instead of the builtin one for supplying power, serial debugging and uploading code.

Currently my board is recieving power from the USB port using vin, but I would like to know how I can get the Arduino to use serial communication with the TX/RX pins and the data+ and data- pins on the USB. I'm especially interested in knowing if I can upload new code to the board through TX/RX.

The official page for the Nano says that the serial communication is handled by an FTDI FT232RL chip, which as I understand, translates the signal from the builtin USB to serial. Is there any way that I can use this chip to communicate over the TX/RX pins instead of builtin USB?

Online documentation about this subject is really lacking, and of the few opinions that I've found, many are conflicting. I would really appreciate any help with this, thanks.

# Answer
There is no "built-in USB" on the Nano. There is only the FT232RL chip which talks USB. That chip is connected directly to the TX/RX pins inside the board.

You are already communicating over the TX/RX pins *through* the FT232RL to the USB.

Yes, you could use your own FT232RL (or FT232-like) board to communicate between USB and the TX/RX pins, but that will be exactly the same as using the one built in to the board - but without the convenience, and with the addition of more wires and expense. So pointless, unless the current USB connection is damaged in some way.
> 1 votes

---
Tags: serial, arduino-nano, usb, uart, ftdi
---


title: Arduino Time Library and RTC Libraries

text:
# Question
Title: Arduino Time Library and RTC Libraries
I am using RTClib.h and TimeLib.h with an Uno.

Have been struggling for days in understanding the various RTC libraries available and how to use them with the Arduino Time Library.

**Question 1**.
If I do not want to create a new now() object each time through the loop, how do I sync the Time Library to the RTC every x seconds? Any time I try to use the RTClib function now.hour now.minute etc it requires me to use DateTime now = RTC.now() creating the now() object.

Is there an equivalent function in RTCLib as setSyncProvider(RTC.get) in DS1307RTC library?

Is there an equivalent to setSyncInterval(5000)

**Question 2**.
Which RTCLib should I call out? There are several used in examples:

\<RTClib.h\>

"RTClib" using quotes

\<RTCLib.h\> with capital L

and sometimes also calling out one of these:

RTC\_DS1307 RTC

or RTC\_DS1307 rtc

or RTC\_DS3231 rtc

**Question 3**
a. Are tmElements\_t tm part of the DS1307RTC library?
b. Are these tm.Hour tm.Minute from the RTC?
c. Is there an equivalent in the RTClib.h ?

And finally I have posted some code below just to show my usage:

```
#include "RTClib.h"
#include <Wire.h>
#include <TimeLib.h>

RTC_DS1307 RTC;

void setup() {

Serial.begin(9600);
Wire.begin();  //sets up the I2C
RTC.begin();   //initializes the I2C to the RTC

if (! RTC.begin()) {
    Serial.println("Couldn't find RTC");
}

//  Set the RTC Time to 5:10:30 Nov 3 2020
      RTC.adjust(DateTime(2020,11,3,5,10,30));

//Set Arduino Time Library different than RTC time to see which is which
setTime(9, 27, 05, 14, 07, 2015);

}

 void loop() {

/*
// How do I sync Time Library to RTC after x seconds?
  setSyncProvider(RTC.get); // This is in the DS1307RTC.h Library
  setSyncInterval(5000);   //  Are there such functions in RTClib ?
*/

DateTime now = RTC.now();   // Pulls RTC time into now().  Does not sync with Time Library
                            // Do not want to do this every loop.

//Print RTC Time
Serial.println();
Serial.print("RTC now.hour        ");
Serial.println(now.hour());
Serial.print("RTC now.minute      ");
Serial.println(now.minute());
Serial.print("RTC now.second:     ");
Serial.println(now.second());
Serial.println();
Serial.println();

//Print Arduino TimeLib Time
Serial.print("Time Lib Hour:       ");
Serial.print(hour());
Serial.println();
Serial.print("Time Lib Min:        ");
Serial.print(minute());
Serial.println();
Serial.print("Time Lib Sec:        ");
Serial.print(second());
Serial.println();
Serial.println();

delay(1000);

 }

```

---

Updated 5 Nov 2020

I think I almost understand. Please let me know if this code is doing what I think it is doing, specifically:

In Setup:
Set the RTC to 5:10:30.
Set Time Library to 9:27:05 with setTime().
Set Time Library to RTC time with DateTime now (over writing 9:27:05)?
Set Time Library variables to RTC using tm.Hour = now.Hour, etc.

In Loop:
Every 5 seconds update hour(), minute() second() with RTC time.
Every loop update tm.hour with hour(), etc.

I know it is still not right since the serial prints show tm.Hour,tm.Minute alternating each loop as shown at the bottom.

```
#include "RTClib.h"
#include <Wire.h>
#include <TimeLib.h>

RTC_DS1307 RTC;

time_t time_provider()
{
    return RTC.now().unixtime();
}

tmElements_t tm;  //part of Time Library

void setup() {
    //setSyncProvider(time_provider);
    Serial.begin(9600);
    Wire.begin();  //sets up the I2C
    RTC.begin();   //initializes the I2C to the RTC

    if (! RTC.begin()) {
        Serial.println("Couldn't find RTC");
    }

    //  Set the RTC Time to 5:10:30 Nov 3 2020
    RTC.adjust(DateTime(2020,11,3,5,10,30));

    //Set Arduino Time Library different than RTC time 9:27:05
    setTime(9, 27, 05, 14, 07, 2015);

    //Setting Time Library to RTC time
    DateTime now = RTC.now();
    tm.Hour = now.hour();
    tm.Minute = now.minute();
    tm.Second = now.second();
}

void loop() {
    setSyncProvider(RTC.now);
    setSyncInterval(5000);

    //Time Library time updates to RTC every 5 seconds
    tm.Hour = hour();
    tm.Minute = minute();
    tm.Second = second();

    Serial.print("tm.Hour:    ");
    Serial.print(tm.Hour);
    Serial.println();
    Serial.print("tm.Minute:  ");
    Serial.print(tm.Minute);
    Serial.println();
    Serial.print("tm.Seconds: ");
    Serial.print(tm.Second);
    Serial.println();
    Serial.println();
    delay(1000);
}

```

Serial Prints:

```
tm.Hour:    5
tm.Minute:  34
tm.Seconds: 56

tm.Hour:    18
tm.Minute:  0
tm.Seconds: 0

tm.Hour:    5
tm.Minute:  34
tm.Seconds: 56

tm.Hour:    18
tm.Minute:  0
tm.Seconds: 0

tm.Hour:    5
tm.Minute:  34
tm.Seconds: 56

tm.Hour:    18
tm.Minute:  0
tm.Seconds: 0

```

# Answer
Let me first give some background about these libraries.

The Time library uses `millis()` for timekeeping. Since this can be subject to significant drift, it provides a means to periodically sync to an external time provider. Hence the functions `setSyncProvider()` and `setSyncInterval()`.

RTClib is meant to interface an RTC. It does not provide timekeeping on its own: you get the current time by querying an RTC through it's `now()` method.

These two libraries can nicely complement each other, as RTClib can be used as a time provider for the Time library:

```
// Provide the RTC time to the Time library.
time_t time_provider() {
    return RTC.now().unixtime();
}

void setup() {
    // ...
    setSyncProvider(time_provider);
}

```

> If I do not want to create a new now() object \[...\]

It is actually called a `DateTime` object.

> Is there an equivalent \[to `tmElements_t`\] in the RTClib

Yes, the `DateTime` class. Note that, unlike the `tmElements_t` structure, the data fields of `DateTime` are not public, and you have to use accessors to get them: `year()`, `month()`, `day()`...

**Alternative timekeeping method**

Since you are using an Arduino Uno, there is a third method of timekeeping you may want to consider. Instead of querying the RTC on every loop iteration (RTClib) or interpolating the RTC readings with `millis()` (Time library), you may route a 1 Hz output of the RTC to an interrupt pin, and count the seconds in the ISR. The avr-libc timing code is designed to provide timekeeping in this fashion. It all boils down to:

```
// Initialize the system time from the RTC.
set_system_time(RTC.now().secondstime());

// Keep the time in sync using the 1 Hz output of the RTC.
pinMode(pin1Hz, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(pin1Hz), system_tick, FALLING);

```

For more details, see the example sketch interrupts1Hz.ino provided with RTClib.

---

**Edit 1**: Answering a comment

> which pin does \[the Arduino interrupt pin\] connect to on the RTC?

It depends on the RTC you are using. I will assume it's a DS1307, as implied by the code in your question. Take a look at the datasheet of the RTC. On page 6, there is a table titled “Pin description”. From this table:

> **pin**: 7
> **name**: SQW/OUT
> **function**: Square Wave/Output Driver. When enabled, the SQWE bit set to 1, the SQW/OUT pin outputs one of four square-wave frequencies (1Hz, 4kHz, 8kHz, 32kHz). The SQW/OUT pin is open drain and requires an external pullup resistor. SQW/OUT operates with either VCC or VBAT applied. The pullup voltage can be up to 5.5V regardless of the voltage on VCC. If not used, this pin can be left floating.

If you are using an RTC *module*, you will have to figure out where this pin is exposed on the module's connector.

In any case, you will have to enable the 1 Hz square wave output with

```
RTC.writeSqwPinMode(DS1307_SquareWave1HZ);

```

---

**Edit 2**: Commenting on the update to the question:

> ```
> // Set the RTC Time to 5:10:30 Nov 3 2020
> RTC.adjust(DateTime(2020,11,3,5,10,30));
>
> ```

Correct.

> ```
> // Set Arduino Time Library different than RTC time 9:27:05
> setTime(9, 27, 05, 14, 07, 2015);
>
> ```

Correct. Date is 2015-07-14.

> ```
> // Setting Time Library to RTC time
> DateTime now = RTC.now();
> tm.Hour = now.hour();
> tm.Minute = now.minute();
> tm.Second = now.second();
>
> ```

No. This is only partially initializing the `tm` variable. It has no effect on the idea the Time library has of the current time. Note that the date fields of `tm` have not been initialized at this point, and could well be invalid (like month 23, day 125).

> ```
> setSyncProvider(RTC.now);
>
> ```

This is incorrect, and should have generated a compiler warning. `setSyncProvider()` expects a function that returns the current time as Unix time (a simple integer, of type `time_t`). You are providing a function that returns the current time in broken down form (year, month...), with type `DateTime`. The Time library will not understand that and may yield garbage like, say, 18:00:00.

The time returned by `RTC.now()` can be converted to Unix time with the `unixtime()` method. That's why I gave you the `time_provider()` function.

Also, you are not supposed to call `setSyncProvider()` and `setSyncInterval()` on every loop iteration. Do it once and for all in `setup()`.

> ```
> // Time Library time updates to RTC every 5 seconds
> tm.Hour = hour();
> tm.Minute = minute();
> tm.Second = second();
>
> ```

Again, this is only updating the variable `tm`. It has no effect on what the Time library believes is the current time.
> 3 votes

# Answer
> Is there an equivalent function in RTCLib as setSyncProvider(RTC.get) in DS1307RTC library?
>
> Is there an equivalent to setSyncInterval(5000)

Those are TimeLib functions. There's no "equivalent to" since you *are* using TimeLib.

The first one just expects a pointer to a function that returns a `time_t`. What is in that function is up to you.

> Which RTCLib should I call out? There are several used in examples:

The capitalisation should match the name of the header file. Windows doesn't care, and OS X usually doesn't care, but can be configured to. Linux *does* care and needs it to match. If you want your code to be portable then you must keep the capitalisation the same as the file.

> and sometimes also calling out one of these:

You need to create an object that matches your physical RTC.

> a. Are tmElements\_t tm part of the DS1307RTC library?

No. They are part of TimeLib.

> b. Are these tm.Hour tm.Minute from the RTC?

They are whatever gets assigned to them by a function that is called. They are just variables. They can contain anything.

> c. Is there an equivalent in the RTClib.h ?

No. But then you don't need there to be if you're using TimeLib.

So: you need to

* Create a function that gets the time from the RTC through whatever library you want to use (RTCLib for example) and calculates the number of seconds since 00:00:00 01/01/1970, which it then returns as a `time_t`.
* Pass that to TimeLib's `setSyncProvider()`
* Set a sync frequency with `setSyncInterval()`.
> 2 votes

---
Tags: arduino-uno, time, rtc
---


# Question
Title: How can I PWM 4 LEDs from 0 to full brightness using a two axiz resistive joystick?
* I am trying to use the Arduino MAP function to allow me to PWM 4 LEDs between 0 and full brightness. I guess the tricky part is that the joystick neutral position is at the venter of the range of the potentiometers so the analog voltage to the inputs is at +2.5V when the joystick at neutral). Ideally I want to make a red LED that is associated with the Y axis to go from 0 to full as the joystick is pushed away. Similarly, I want a blue LED associated with the Y axis to go from 0 to Full on when the joystick is pulled toward me. I want to duplicate that action for the X axis with green and yellow LEDS but I can't seem to be able to figure out how to compensate for the 2.5V offset\* I hoped I could just use mapping of the values.

# Answer
> 2 votes
There's a number of steps you need to go through:

1. Read the ADC to get the joystick position
2. Subtract 50% of the full range (512) to get a ±512 value
3. Note the sign to get the direction
4. Take the absolute value to get the distance
5. Subtract a small amount to create a "dead zone" in the centre of the joystick
6. Map the result to 0-255 for the PWM.

The code might look like (note: untested):

```
int y = analogRead(0);    // Get the current value
y -= 512;                 // Subtract 512

int pin = 2;              // Unless otherwise told, use pin 2
if (y < 0) {              // If it's negative...
    pin = 3;              //    then we'll use pin 3 instead
}

y = abs(y);               // Take the absolute value (discard the sign)
y -= 20;                  // subtract 20 for a dead zone
If (y < 0) y = 0;         // zero any negative
y = map(0, 492, 0, 255);  // map the new full range of 0-492 to 0-255
analogWrite(pin, y);      // light the LED on the pin we chose above.

```

And do the exact same thing for X with different pins.

---
Tags: led, pwm, joystick
---


# Question
Title: Compiling Error - exit status 1 for DHT11 using Arduino UNO (code/process/connections same as website given bellow)
*https://create.arduino.cc/projecthub/MisterBotBreak/how-to-use-temperature-and-humidity-dht-sensors-9e5975*

**Copied Error Message:**

```
Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"

In file included from C:\Users\soumy\OneDrive\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.cpp:15:0:

C:\Users\soumy\OneDrive\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.h:36:10: fatal error: Adafruit_Sensor.h: No such file or directory

 #include <Adafruit_Sensor.h>

          ^~~~~~~~~~~~~~~~~~~

compilation terminated.

exit status 1

Error compiling for board Arduino Uno.

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

```

**The code:**

```
#define DHTPIN 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {

  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  float hif = dht.computeHeatIndex(f, h);
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
}

```

# Answer
I didn't download the "Adafruit Sensor Library" https://github.com/adafruit/Adafruit\_Sensor It ran after I added it.
> 1 votes

---
Tags: arduino-uno
---


title: Use RFID-RC522 with other Pins

text:
# Question
Title: Use RFID-RC522 with other Pins
I'm wondering where the pin setting is manifested in the library. I want to use the RC522 with other digital pins than the default 50-53 pins, because I am using a shield for a display on theese ports.

Where can I change the used ports? why are two ports user-defineable `#define RFID_SS 10 #define RFID_RST 5` while the rest is not?

I am with this Playground-Guide using this library from Github on my Arduino Mega

# Answer
```
#define RFID_SS  10

```

stands for Slave Select on port 10, the SPI is a serial interface, meaning you can connect all kinds of SPI devices to the same wires, as long as slaves have different IO ports.

This is also the reason you don't need to define the other ports because they need to be connected to your SPI.

I suggest you make yourself familiar with this page: http://arduino.cc/en/Reference/SPI

To sum it up. You can change the reset and Slave Select pin out, (those set in the variables) but not the SPI Pins. But you can use the ISCP pins in the middle of the board.
> 1 votes

# Answer
SPI The RFID\_SS pin is the slave select pin. So you can have another arduino pin for a LCD\_SS select. Having RfID\_SS =low - talk to RFID. Having LCD\_SS =low talk to LCD via MISO. Note: Drive other slave select High otherwise they'll both get the data. Having only one device in communication at a time. Cheers Nik V
> 2 votes

# Answer
Sorry I'm a bit late (5 years late) but hopefully this can help someone who's just now trying to do this!

There's an old obscure Sunfounder library, "rfid1.h" that lets you declare every pin. Like this:

```
rfid.begin(IRQ,SCK,MOSI,MISO,NSS,RST);

```

It's a bit hard to find the library online these days, but at the bottom of this page (http://wiki.sunfounder.cc/index.php?title=Mifare\_RC522\_Module\_RFID\_Reader) if you download the "RFID-RC522\_test\_experiment" zip file it will have the library in there. The secret is that this library includes a software SPI which is sort of like a software serial for SPI communication. Letting other digital pins be used as MISO etc...

This library also makes it much easier to use multiple RFIDs reliably since they don't have to share all the same pins.

You can find some example code here: https://www.sunfounder.com/learn/RFID\_kit\_V1\_for\_Arduino/lesson-29-rfid-entrance-guard-system-rfid-kit-v1-0-for-arduino.html
> 2 votes

---
Tags: arduino-mega, pins, rfid
---


# Question
Title: Achieving nanosecond accuracy with MKR Vidor 4000
Can I achieve nanosecond accuracy with Arduino Vidor MKR 4000? Has anyone experience? Obviously by using the FPGA it has on it. I do not find much support on this module on google search...

# Answer
> 3 votes
No. You can't.

To achieve 1ns precision you need a 1GHz clock. That can't happen. The MKR Vidor 4000 uses an FPGA with an "A7" speed grade. That means that (according to Table 20 here) you can't run at any more than 402Mhz internally (200MHz is all Arduino are rating it for).

Not even half.

Around 5ns precision would be the absolute maximum precision you could get if you stick to the Arduino clock specs.

---
Tags: oscillator-clock
---


# Question
Title: if(val == 0) being ignored when it contains another nested if() statement
The issue: In the following example even though complexManoeuvre == 3, `Serial.print(CTA5: "); ...` is executed.

```
void loop()  {
  if(complexManoeuvre == 0) {
    if(timeisup == true && goingForwards == 1)  {   // If time is up while going forward, assume it's stuck
      goingForwards = 0;
      Serial.print("CTA4: "); stuck(stk);
    }
    if(timeisup == true && goingForwards != 1)  {
      Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
    }
  }
}

```

However, if I include the first condition within the other if() statments two then it works:

```
if(complexManoeuvre == 0 && (deltaBegan >= manoeuvreFor) && goingForwards == 1) {
  goingForwards = 0;
  Serial.print("CTA4: "); Serial.print(complexManoeuvre); stuck(stk);
}
if(complexManoeuvre == 0 && (deltaBegan >= manoeuvreFor) && goingForwards != 1) {
  //Serial.print("complexManoeuvre == "); Serial.println(complexManoeuvre);
  Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
}

```

Being completely stumped, I suspected compiler issue so I reinstalled Arduino to clear Meguno-link avrdude wrapper but the problem remains.

The full code (for a robot hoover) is as follows, slimmed down as much as possible to simplify reading:

```
const int fwd = 12000;            // ms duration
const int stk = 1600;
unsigned long beganManoeuvre;     // millis time when manoeuvre began
int manoeuvreFor;                 // Duration
unsigned long lastStuck;
byte goingForwards;               // Yes or no
byte complexManoeuvre;            // 0 = none, 1 = center, 2 = stuck, 3 = doubleStuck
byte progress;                    // complexManoeuvre progress

void setup() {
  Serial.begin(9600);
  Serial.print(F("CTA0: ")); spinR(4800);     // Spin through 360 degrees
}

void loop() {
  bool timeisup = false;
  if((millis() - beganManoeuvre) >= manoeuvreFor) {
    timeisup = true;
  }

  if(complexManoeuvre != 0 && timeisup == true)  {          // If part way through a in a complex
    switch(complexManoeuvre)  {                             // ..manoeuvre (eg; stuck)
    case 1:
      // do other()
      break;
    case 2:
      Serial.print(F("CTA2: ")); stuck(manoeuvreFor);       // return to the complex manoeuvre
      break;
    }
  }

//  if(complexManoeuvre == 0 && timeisup == true && goingForwards == 1) {
//    goingForwards = 0;
//    Serial.print("CTA4: "); Serial.print(complexManoeuvre); stuck(stk);
//  }
//  if(complexManoeuvre == 0 && timeisup == true && goingForwards != 1) {
//    //Serial.print("complexManoeuvre == "); Serial.println(complexManoeuvre);
//    Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
//  }
  if(complexManoeuvre == 0) {
    if(timeisup == true && goingForwards == 1)  {   // If timeisup while going forward, assume stuck
      goingForwards = 0;
      Serial.print("CTA4: "); stuck(stk);
    }
    if(timeisup == true && goingForwards != 1)  {   // If finished another manoeuvre, go forwards
      if(complexManoeuvre != 0) Serial.println("What the?!");
      Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
    }
  }
}

void stuck(int dur)  {
  Serial.print(F("void stuck(int dur == "));  Serial.println(dur);
  switch(progress) {
  case 0:
    Serial.print(F("CTA26: "));
    complexManoeuvre = 2;
    reverse(dur);
    progress = 1;
    break;
  case 1:
    Serial.print(F("CTA27: "));
    spinR(dur);
    progress = 2;
    break;
  case 2:                     // Reset
    progress = 0;
    complexManoeuvre = 0;
    lastStuck = millis();
    break;
  }
}

void forward(int dur)  {
  Serial.print(F("void forward(int ")); Serial.print(dur);
  if(goingForwards != 1) {
      Serial.print(F(") >> if(goingForwards != 1) then do"));
      goingForwards = 1;
      beganManoeuvre = millis();
      manoeuvreFor = dur;
      digitalWrite(9, HIGH);
      digitalWrite(10, LOW);
      digitalWrite(11, HIGH);
      digitalWrite(12, LOW);
  }
  Serial.println();
}

void reverse(int dur)  {
  Serial.print(F("void reverse(int dur == "));  Serial.println(dur);
  beganManoeuvre = millis();
  manoeuvreFor = dur;
  digitalWrite(9, LOW);
  digitalWrite(10, HIGH);
  digitalWrite(11, LOW);
  digitalWrite(12, HIGH);
}

void spinR(int dur) {
  Serial.print(F("void spinR(int dur == "));  Serial.println(dur);
  beganManoeuvre = millis();
  manoeuvreFor = dur;
  digitalWrite(9, LOW);
  digitalWrite(10, HIGH);
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
}

```

The questionable Serial output is:

```
1) 19:59:31.964 -> CTA0: void spinR(int dur == 4800
2) 19:59:36.765 -> CTA5: 0void forward(int 12000) >> if(goingForwards != 1) then do
3) 19:59:48.771 -> CTA4: void stuck(int dur == 1600
4) 19:59:48.811 -> CTA26: void reverse(int dur == 1600
5) 20:11:12.695 -> What the?!
6) 19:59:48.851 -> CTA5: 2void forward(int 12000) >> if(goingForwards != 1) then do
7) 20:00:00.854 -> CTA2: void stuck(int dur == 12000
8) 20:00:00.894 -> CTA27: void spinR(int dur == 12000
9) 20:00:12.860 -> CTA2: void stuck(int dur == 12000
10) 20:00:12.900 -> CTA4: void stuck(int dur == 1600
...

```

Edit to add: Arduino version 1.8.13, Win7, tested on Nano Atmega168PA and Mega2560

# Answer
Your `void Stuck() { ... }`, which is called inside the first `if (timeisup == true && goingForwards == 1) { ... }` can set `complexManoeuvre` to a non-zero value, before reaching the second `if (timeisup == true && goingForwards != 1) { ... }` (the one with *"What the?!"*).
> 1 votes

---
Tags: c++
---


# Question
Title: Digispark uploading not working in KDE Neon (Linux)
I am using KDE Neon and have downloaded the Arduino IDE via the Snap store. It worked well with the ESP8266 and other Arduions. But when I tried to upload a simple sketch or an example sketch to my Digispark, I get an error message. I have selected the right Board and the micronucleus programmer. I have also installed libusb. But I always get the following error message:

/home/myusername/snap/arduino/41/.arduino15/packages/digistump/tools/micronucleus/2.0a4/micronucleus: error while loading shared libraries: libusb-0.1.so.4: cannot open shared object file: No such file or directory

# Answer
> 0 votes
I had the same problem when using the snap package of the Arduino IDE. I solved the problem by installing the Arduino IDE from the official web page: https://www.arduino.cc/en/software

You might have to run the Arduino IDE with sudo or better add a custom udev rule in case you now get following assertion error:

> 'micronucleus\_connect: Assertion \`res \>= 4' failed.'

Solving the assertion error is further described in following post: https://digistump.com/board/index.php?topic=106.0

---
Tags: linux, digispark
---


# Question
Title: Arduino piezo-buzzer melody for car alarm
I would like to play car alarm sound through Arduino buzzer - something like this https://youtu.be/nuPHwijMsIg

Does anybody have a library for such melody?

# Answer
I think what you're really asking for is a library of sounds (in the form of code), rather than a code library in the normal sense. I'd like such a thing too (specifically a retro-gaming style laser noise), but extensive googling hasn't found anything, though someone has made a sketch of the Tetris theme.

A car alarm is probably fairly easy - a couple of for loops changing the frequency of a `tone()`; My Arduino and piezo buzzer are at home but playing that YouTube and using a spectrum analyser app on my phone it looks like (using the waterfall display mode):

* The first alarm is looping from 1000Hz to 2200Hz over about 250ms, then back down again. - The next 2 are falling tones, from 1kHz down to about 500 over 250 or 500ms.
* Then we've got a rising tone 500 Hz to 1kHz over 2s
* A beep at about 2.2kHz, 250ms on/off
* A two-tone siren at 1 and 1.5kHz, 1s of each.

Times and frequencies were indeed a little off, and many of the frequency ramps aren't linear, but here's something to play with. The more interesting alarms are in there, along with a couple of laser zaps. The square-wave drive of a piezo (leading to interesting harmonics), and the complete lack of a low frequency response (nothing below about a few hundred Hz on the one I have here) limit things a little, but it compares well to a Lego siren I have

```
int beep_pin=10;
int gap=1000;

void setup() {
  // put your setup code here, to run once:
  pinMode(beep_pin, OUTPUT);
}

void zap1()
{
    for (float f=3000;f>40;f=f*0.93){
    tone(beep_pin,f);
    delay(10);
  }
}

void zap2()
{
    for (float f=3000;f>10;f=f*0.85){
    tone(beep_pin,2*f);
    delay(5);
    tone(beep_pin,f);
    delay(5);
  }
}
void risefall()
{
  float rise_fall_time=180;
  int steps=50;
  float f_max=2600;
  float f_min=1000;
  float delay_time=rise_fall_time/steps;
  float step_size=(f_max-f_min)/steps;
  for (float f =f_min;f<f_max;f+=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
   for (float f =f_max;f>f_min;f-=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
}
void fall(float rise_fall_time)
{
  int steps=50;
  float f_max=2000;
  float f_min=500;
  float delay_time=rise_fall_time/steps;
  float step_size=0.97;
  for (float f =f_max;f>f_min;f*=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
}
void rise()
{
  float rise_fall_time=2000;
  int steps=100;
  float f_max=1500;
  float f_min=500;
  float delay_time=rise_fall_time/steps;
  float step_size=1.012;
  for (float f =f_min;f<f_max;f*=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
  noTone(beep_pin);
  delay(100);

}

void twotone()
{
  float f_max=1500;
  float f_min=1000;
  float delay_time=800;
  tone(beep_pin,f_max);
  delay(delay_time);
  tone(beep_pin,f_min);
  delay(delay_time);

}
void loop() {
  // put your main code here, to run repeatedly:

  for (int count=1;count<=10;count++)
  {
    risefall();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<=10;count++)
  {
    fall(300);
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<=5;count++)
  {
    fall(600);
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<5;count++)
  {
    rise();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<5;count++)
  {
    twotone();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<10;count++)
  {
    zap1();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<10;count++)
  {
    zap2();
  }
  noTone(beep_pin);
  delay(gap);
}

```

It's also on GitHub, and released into the public domain under the unlicense so anyone can use it however they like
> 1 votes

# Answer
https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody See this example to get the code for each musical note. It should work very well!
> 1 votes

---
Tags: piezo, buzzer
---


title: How to use Multipile millis()

text:
# Question
Title: How to use Multipile millis()
I've a exhaust fan that runs when the humidity is high. When the exhaust fan is on it should work for 3 minutes and should wait another 5 minutes to on. I am a beginner to this struggling for almost 2 days now. with this code the led just blink and off

```
int ledPin =  2;      // the number of the LED pin
int ledState = LOW;             // ledState used to set the LED
unsigned long previousMillis2 = 0;
unsigned long previousMillis = 0;
long interval = 10000;           // in
long OnTime = 1000;           // milliseconds of on-time
long OffTime = 2000;          // milliseconds of off-time

void setup()
{

  Serial.begin(9600);
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{

  unsigned long currentMillis2 = millis();

  if (currentMillis2 - previousMillis2 > interval) {
    // save the last time you blinked the LED

    // check to see if it's time to change the state of the LED
    Serial.print("hellohh ");
    unsigned long currentMillis = millis();

    if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
      Serial.print("hellohh2 ");
      ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      Serial.print("hellohh 3");
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;
      previousMillis2 = 0; // Remember the time
      digitalWrite(ledPin, ledState);    // Update the actual LED

    }
  }
}

```

# Answer
If I understand correctly, you wrote an example code that switches an LED between two states (on and off), and you are stuck because the actual problem you want to solve is more complex than that. And indeed, it seems to me that you want to manage a system with *three* possible states: it can be on or off but, when it is off, it can be ready to turn on if the humidity is high, or it can be in the five minute wait.

The most natural way to think about this kind of systems is a finite state machine, or FSM. An FSM is defined by the set of states it can be in, the conditions that make it switch states, and the actions performed when doing so. If I correctly understood your specification, your system can be either READY, RUNNING or WAITING, and the transitions are:

* when READY, if the humidity is too high it switches to RUNNING; it turns the fan on when doing so
* when RUNNING, if it has been running for 3 minutes, it switches to WAITING and turns the fan off
* when WAITING, if it has been waiting for 5 minutes, it switches to READY

This can be illustrated by the following state diagram:

You should correct me at this stage if I did not fully understand your specification. Otherwise, if the state diagram matches your requirements, converting it to code is quite straightforward:

```
const uint32_t MINUTE = 60000;

void loop() {
    static enum {READY, RUNNING, WAITING} state;
    static uint32_t last_change;
    uint32_t now = millis();
    switch (state) {
        case READY:
            if (humidity_is_high()) {
                turn_fan_on();
                state = RUNNING;
                last_change = now;
            }
            break;
        case RUNNING:
            if (now - last_change >= 3 * MINUTE) {
                turn_fan_off();
                state = WAITING;
                last_change = now;
            }
            break;
        case WAITING:
            if (now - last_change >= 5 * MINUTE) {
                state = READY;
            }
            break;
    }
}

```
> 5 votes

# Answer
For your current issue (turning LEDs on and off after 1s / 2s, much of your code can be simplified:

```
int ledPin =  2;     // Number of the LED pin
int ledState = LOW;  // ledState used to set the LED
unsigned long TimeLedOFF = 0;     //Time at which the LED was last turned off
unsigned long TimeLedON = 0;      //Time at which the LED was last turned on
unsigned long TimeLastCheck = 0;  //Time at which the next LED state was determined last
long interval = 100;  // How often to check for changes in environment - should be shorter than your switching durations
long OnTime = 1000;   // Milliseconds of on-time
long OffTime = 2000;  // Milliseconds of off-time

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT); // set the LED pin as output:
}

void loop() {
  if (millis() - TimeLastCheck > interval) { //If the LED state should be evaluated again - "interval" has passed
    TimeLastCheck = millis();

    Serial.println("Determining next LED state");

    if (ledState == HIGH && (millis() - TimeLedON >= OnTime)) { //If LED was on for long enough
      Serial.println("OnTime elapsed. Turning off.");
      TimeLedOFF = millis(); // Remember the time
      ledState = LOW;        // Turn LED flag off
      digitalWrite(ledPin, ledState); // Update the actual LED
    }
    else if (ledState == LOW && (millis() - TimeLedOFF >= OffTime)) { //If LED was off for long enough
      Serial.println("OffTime elapsed. Turning on.");
      TimeLedON = millis(); // Remember the time
      ledState = HIGH;  // turn it on
      digitalWrite(ledPin, ledState);    // Update the actual LED
    }
  }
}

```

This results in the LED being turned on for one second, then off for two seconds.
> 2 votes

---
Tags: arduino-uno, programming, millis, home-automation
---


# Question
Title: How can I use IRsend with a string or convert a char from serial to uint32_t?
I'm trying to control my arduino with a raspberry pi with python instead of C++ (which I don't know). I've found code to take a string from serial and print it, but instead I'd like to use IRsend to use the code. Unfortunately I'm getting the error invalid conversion from 'char\*' to 'uint32\_t {aka long unsigned int}' \[-fpermissive\]. I know this must be an incredibly dumb question but is there a int() function for uint32\_t for arduino C++? that I could set blah=uint32\_t(buf) and then use my irsend.sendNEC(buf, 32)? If it's not painfully obvious, I don't know C++ and my python isn't great.

```
#include <IRremote.h>

char buf[80];

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0; // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  return 0;
}

void setup() {
  Serial.begin(115200);
}

IRsend irsend;

void loop() {
  if (readline(Serial.read(), buf, 80) > 0) {
    Serial.print("You entered: >");
    Serial.print(buf);
    Serial.println("<");
    irsend.sendNEC(buf, 32);

  }
}

```

Error:

```
/home/pi/Desktop/sendIRfromserial2addingir/sendIRfromserial2addingir.ino: 39:27: warning: invalid conversion from 'char*' to 'uint32_t {aka long unsigned int}' [-fpermissive]
             irsend.sendNEC(buf, 32);

                  ^

```

In file included from

```
/home/pi/Desktop/sendIRfromserial2addingir/sendIRfromserial2addingir.ino:1:0:
/home/pi/Arduino/libraries/IRremote/src/IRremote.h:444:10: note:   initializing argument 1 of 'void IRsend::sendNEC(uint32_t, uint8_t, bool)'
     void sendNEC(uint32_t data, uint8_t nbits, bool repeat = false);
          ^~~~~~~`

```

# Answer
Instead of

```
irsend.sendNEC(buf, 32);

```

cast it to an unsigned int32 type:

```
irsend.sendNEC((uint32_t) buf, 32);

```
> 0 votes

---
Tags: programming, c++
---


title: Arduino.Mk together with MightyCore

text:
# Question
Title: Arduino.Mk together with MightyCore
There's no end to my frustration trying to figure out how the arduino build system works -- despite my best efforts I just can't seem to grok it. Anyhow, I did this:

```
ALTERNATE_CORE_PATH=/path/to/MightyCore/avr
BOARD_TAG=324
...

```

`make show_boards` shows me several boards available, including `324`. Yet whenever I try to build my project, I get this error:

```
avr-g++: error: missing device or architecture after ‘-mmcu=’

```

Can someone point me in the right direction?

Thanks.

# Answer
Resolved with the following Makefile options:

```
BOARD_TAG=324
MCU=atmega324a
VARIANT=standard

```
> 1 votes

---
Tags: makefile
---


# Question
Title: Can AccelStepper accelerate non-linearly?
I am running a Nema 23 motor with an Arduino Uno and a microstepper driver. I am making a torsional vibration demo, which uses a series of springs connected to the motor driveshaft to spin gears. These gears, as changes in shaft speed occur, should begin to weave in- and out-of-phase with one another. In my particular case, I am using three potentiometers, which read 0-1023, to read speed, amplitude, and frequency. The changes in motor speed are where I run into my issues. I need the *speed* of the stepper to be a sinusoidal function - of the form "Speed - Amplitude x sin(frequency x time)".

Below is some rudimentary code I put together with the AccelStepper library, which does not work:

```
#include <AccelStepper.h>

/* Using a stepper motor,
  rotate a vibrational model using gears interconnected by springs
  in such a way as to induce torsional vibration, which should be visible by comparing
  movement of juxtaposed rotating gears with markers painted on. */

AccelStepper stepper(AccelStepper::DRIVER);
void setEnablePin(int enablePin = 8);

int Microstepping = 8; /* Microstepping factor, as set on the ST-M5045 control board.
                          Multiplies the number of steps per revolution on the stepper motor.
                          Reference controller manual for adjustments to this number. */
int Steps = 200; /* Number of steps on your stepper motor.*/
int SPS;
int Amp;
int Freq;
// int SC;
int n = 2;
int i;
int totalSteps = Microstepping * Steps;
int currentPosition();

/* It should be noted that the Microstepping and Steps factors are not necessary, and adjusting the microstepping factor
    on the fly will not break the code. However, be aware that changing the microstepping factor by more than one interval
    at a time can cause the motor to not keep up with the sudden changes, i.e. losing torque or vibrating/stuttering. */

void setup() {               // THIS RUNS ONCE //

  Serial.begin(9600);

  // read potentiometers; raw inputs from 0 to 1023 //
  SPS = analogRead(0) * 0.5; // MAX steps per second should be <1000. Speeds above 1000 unreliable, according to AccelStepper docs.//
  Amp = analogRead(1) / 20;   // MAX AMP ~51//
  Freq = analogRead(2) / 170; // MAX FREQ ~12 Hz//

  stepper.setMaxSpeed(1000);
  stepper.setAcceleration(SPS / 1.5);

  int nextStop = totalSteps / Freq;

  stepper.moveTo(nextStop);
  stepper.run();
  Serial.println("INITIALIZED");
}

void loop() {
  SPS = analogRead(0) * 0.95;
  Amp = analogRead(1) / 20;
  Freq = analogRead(2) / 170;

  float spd = SPS + (Amp*sin(Freq*millis()));
  stepper.setSpeed(spd);
  stepper.run();
  Serial.print("speed:  ");
  Serial.println(spd);
}

```

The issue I am having with the above code is that it enters the loop but does not vary the speed, despite the serial output showing me a speed which oscillates about the desired value several times a second.

And now, folks, what you've all been waiting for: The Point.

Does AccelStepper actually support non-linear accelerations *not as the result of an error?* I cite the following excerpt from the AccelStepper documentation,

```
 /// Sets the maximum permitted speed. The run() function will accelerate
 /// up to the speed set by this function.
 /// Caution: the maximum speed achievable depends on your processor and clock speed.
 /// The default maxSpeed is 1.0 steps per second.
 /// \param[in] speed The desired maximum speed in steps per second. Must
 /// be > 0. Caution: Speeds that exceed the maximum speed supported by the processor may
 /// Result in non-linear accelerations and decelerations.
 void    setMaxSpeed(float speed);

```

which makes the *only* mention of non-linear acceleration in all of the documentation - in the context of an overflow error.

I've thought of possibly using a modified version of the easydriver example program from reply #3 to this post if AccelStepper isn't capable of doing what I need it to do. Included is also an image of the system (minus the arduino and controller).

Thanks for your help in advance

# Answer
> 1 votes
I appreciate the votes for exposure! Here is the answer I got from Mike, the creator of AccelStepper himself: link

Short answer: no!

I've posted the program I'm using now, which accelerates nonlinearly using pulse timing variation, in the linked thread.

Happy stepping!

---
Tags: arduino-uno, stepper
---