Hi, new to the forum, first post and looking for some assistance on my first Arduino code attempt.
First of all I should say that I have made something and it works but I just want some more experienced eyes to let me know what could be better.
I am trying to make a program that will control some lights on a remote controlled car. I want them to flash with very specific timing and also be able to turn them on and off using the normal transmitter.
I have therefore taken a PWM signal from the receiver and put it onto D2 on an Arduino Nano, and then used the standard LED out for the rest of the circuit.
The PWM from the receiver is around 1100 when OFF and 1900 when ON. I have therefore written the following code that does what I want it to do i.e. when you flick the switch on the transmitter it loops the flashing sequence, until you flick it off again. It also changes the flash if the signal is lost entirely.
I was just wondering what I have done that could be coded better and have also generated a few questions:
// Variables won't change:
const int PWMinput=2; //Arduino PWM signal input pin
const int LED = 13; // pin that the LED is attached to
// Variables will change:
int ch1 = 0;
void setup() {
Serial.begin(9600);
// Set PWM input pin as an input
pinMode(PWMinput, INPUT);
pinMode(LED, OUTPUT);
}
void loop() {
ch1 = pulseIn (PWMinput,HIGH); //Read and store channel 1
Serial.print ("Ch1:"); //Display text string on Serial Monitor
Serial.println (ch1); //Print the value of ch1
if (ch1 > 1500 && ch1 < 2000)
{
digitalWrite(LED, HIGH);
delay(80);
digitalWrite(LED, LOW);
delay(120);
digitalWrite(LED, HIGH);
delay(20);
digitalWrite(LED, LOW);
delay(140);
digitalWrite(LED, HIGH);
delay(20);
digitalWrite(LED, LOW);
delay(140);
digitalWrite(LED, HIGH);
delay(20);
digitalWrite(LED, LOW);
delay(1000);
}
else if (ch1 > 1000 && ch1 <= 1500)
{
digitalWrite(LED, LOW);
} else
{
digitalWrite(LED, HIGH);
delay(500);
digitalWrite(LED, LOW);
delay(500);
}
delay(1); // delay in between reads for stability
}
Well it works but how badly coded is that?
I created this mainly by using similar ish examples online and the resources on here but a few things are still not clear to me:
-
What's the reason for the "delay for stability" and is it necessary?
-
My code runs the flash sequence once before then looking to see if it should turn itself off. This does not really matter but I wonderer if there was a better way of maybe using nested loops, FOR loops or even the switch/case statement but I could not work out the advantages of doing this.
-
One example I found added a time-out to the pulseIn but this seemed to return results of 0 every other line so I removed this. Is there a benefit to this?
-
I have used an if, elseif and then an else. Would it be acceptable to just miss off the ELSE if it's not required or does that cause problems?
-
I also came across a few different baud rates in use. Does it matter?
thanks already, just for reading