Code optimization

int throttleDutyCycle(int throttleVal, int mode){
  int defaultMode = 275;
  switch(mode){
    case 0:
      return map(throttleVal, 0, 1023, 100, defaultMode);
      break;
    case 1:
      return map(throttleVal, 0, 1023, 100, 425);
      break;
    case 2:
      return map(throttleVal, 0, 1023, 100, 575);
      break;
    case 3:
      return map(throttleVal, 0, 1023, 100, 725);
      break;
    case 4:
      return map(throttleVal, 0, 1023, 100, 875);
      break;
    case 5:
      return map(throttleVal, 0, 1023, 100, 1025);
      break;
    default:
      return map(throttleVal, 0, 1023, 100, defaultMode);
      break;
  }
}#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(5,6);
const byte address[6] = "00001";

const uint8_t modePin = 7;
const uint8_t throttleInPin = 3;
const uint8_t throttleOutPin = 2;
const uint8_t relayPin = 0;
const uint16_t pwmFreq = 5000;
const int inputVals[5] = {100,300,500,700,900};

void setup() {
  pinMode(modePin, OUTPUT);
  pinMode(throttleInPin, OUTPUT);
  pinMode(throttleOutPin, OUTPUT);
  pinMode(relayPin, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);
  
  //delay(5000);
  digitalWrite(relayPin, HIGH);
  
  //Start RX code
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.startListening();
}

void loop() {
  //Radio Code
  bool buttonState;
  if(radio.available()){
    radio.read(&buttonState, sizeof(buttonState));
    digitalWrite(LED_BUILTIN, !buttonState);
  }
  if (!buttonState){
    //Throttle code
    int opMode = operatingMode(analogRead(modePin));
    int throttleVal = analogRead(throttleInPin);
    int dutyCycle = throttleDutyCycle(throttleVal, opMode);
    pwm(throttleOutPin, pwmFreq, dutyCycle);
  }
  else{
    digitalWrite(throttleOutPin, LOW);
    delay(5000);
  }
  buttonState = LOW;
}

// for default analog resolution of 10-bit
int operatingMode (int modeVal){
  // 900, 700, 500, 300, 100, 0
  // int mode;
  // int inputVals[5] = {100,300,500,700,900};
  
  
  if(modeVal < inputVals[0])
    return 0;
  else if (modeVal < inputVals[1])
    return 1;
  else if (modeVal < inputVals[2])
    return 2;
  else if (modeVal < inputVals[3])
    return 3;
  else if (modeVal < inputVals[4])
    return 4;
  else if (modeVal >= inputVals[4])
    return 5;
}

Here's some code I have. It's going to control a 0-5V output (using level-shifting, pwm, and a low-pass filter) which will be a throttle input to a motor controller for an electric go-kart I built. I have a 6-position switch in which I installed 1k resistors to make a voltage divider to use as a selector switch. That selector switch will essentially result in a reduction of throttle output, effectively functioning as a sort of speed limiter. In addition to that, I'm using 2.4GHz transceiver modules to act as a remote kill switch, as well. I've used INPUT_PULLUP and reset the value to of the variable to LOW so if there's a disconnection of any sort, then it should default to essentially shutting off. (Sidenote: this code is currently untested and may be unfinished.)

So basically, just asking if anyone sees a good way to improve my code, make it more efficient/streamlined, or any other improvements anyone can suggest?

You could make throttleDutyCycle() look something like this (not tested!):

int throttleDutyCycle(int throttleVal, int mode) {
  int defaultMode = 275;
  return map(throttleVal, 0, 1023, 100, defaultMode + (mode > 5 ? 0 : (mode - 1) * 150));
}

PS.: Does mode ever become larger than 5 or smaller than zero? If not, it can be done even simpler:

  return map(throttleVal, 0, 1023, 100, defaultMode + (mode - 1) * 150);

Could be shorter using arrays to hold your limits.
But it’s probably plenty fast and small as-is.

Erik_Baas:
You could make throttleDutyCycle() look something like this (not tested!):

int throttleDutyCycle(int throttleVal, int mode) {

int defaultMode = 275;
 return map(throttleVal, 0, 1023, 100, defaultMode + (mode > 5 ? 0 : (mode - 1) * 150));
}




PS.: Does `mode` ever become larger than 5 or smaller than zero? If not, it can be done even simpler:



return map(throttleVal, 0, 1023, 100, defaultMode + (mode - 1) * 150);

No, in normal operation it won't ever be less than 0 or greater than 5. That's a neat, tidy way to do it, I'll consider that implementation. I did change a couple lines in other places, adding a couple extra lines and operations to make it more readable.

westfw:
Could be shorter using arrays to hold your limits.
But it’s probably plenty fast and small as-is.

I did think to do that in one part, but nowhere else. Should be easy enough, thanks.

....
void loop() {
  //Radio Code
  bool buttonState;
  if(radio.available()){
    radio.read(&buttonState, sizeof(buttonState));
    digitalWrite(LED_BUILTIN, !buttonState);
  }
  if (!buttonState){
...

Ooh. That's going to be a fun bug.

Elaborate?

What is the value of buttonState if there's no radio data to read?

Some variables have a null value if not initialized, but my understanding is that bool has initial state of 0 in the Arduino code. I could test it really quick though.

Yes, I was correct. Upon creation, at least for the Seeeduino Xiao (not sure if it's different for different boards), a bool variable has an initial state of 0 or false.

likethesandwich:
Some variables have a null value if not initialized...

Java programmers. Ugh.

likethesandwich:
Yes, I was correct.

Specious reasoning. Lisa Simpson has an anti-tiger rock that will spark your interest.

[quote author=Coding Badly link=msg=4942268 date=1616958881]
Java programmers. Ugh.
[/quote] "byte" is going to come as something of a surprise too.

No clue what you're talking about. But the implication by, "I can test it real quick," followed by a confirmation, was that I did indeed test it. So not sure what's "specious" about, "I tested this, and I was correct," but ok.

TheMemberFormerlyKnownAsAWOL:
"byte" is going to come as something of a surprise too.

To whom, by/about/regarding what? I really don't understand your context, or what you're trying to communicate...

Don't count on automatic variables (like "buttonState") having a defined value is the takeaway message here , "testing" notwithstanding.

You got lucky. Don't rely on luck.

(To Java programmers, the byte data type is signed, but unsigned on Arduino)

TheMemberFormerlyKnownAsAWOL:
Don't count on automatic variables (like "buttonState") having a defined value is the takeaway message here , "testing" notwithstanding.

You got lucky. Don't rely on luck.

(To Java programmers, the byte data type is signed, but unsigned on Arduino)

Historically I haven't counted on it. While I've done little programming for the last 8 years, I did take 4 years of programming in high school and college. Sometimes I initialize variables with a value and sometimes I don't. I think I did test this one before but dismissed it since it worked as expected. Also in my programming experience, it seems that most languages initialize numeric variables as 0, and strings as null. I tend to test my code rather thoroughly, and am fairly thoughtful in its function. I've hit enough issues even recently with uninitialized variables that I usually know to check for that. To improve code readability and clarity, it would be good practice to initialize the bool value. And truthfully, I should initialize it as TRUE/HIGH for my purposes.
Ah, I see. I don't recall that ever coming up in my Java programming before.

Also in my programming experience, it seems that most languages initialize numeric variables as 0, and strings as null.

Your programming experience doesn't include C or C++.

But now you know that automatics are not initialised in those languages, so you can take that into consideration, and adapt your programming to account for that.

TheMemberFormerlyKnownAsAWOL:
Your programming experience doesn't include C or C++.

But now you know that automatics are not initialised in those languages, so you can take that into consideration, and adapt your programming to account for that.

My earliest was C, but also my least, only one C class about 13 or 14 years ago. I loved it, but also used it the least. C++, my experience is severely limited, only a little bit of experimentation. As I said, the fact that bytes are signed never came up. It may have been taught, but never actually mattered for any program I wrote.

EDIT: Also if only C and C++ initialize ints and other variables as null, then my statement would still stand that most languages don't.

likethesandwich:
EDIT: Also if only C and C++ initialize ints and other variables as null, then my statement would still stand that most languages don't.

Except your statement was that " most languages initialize numeric variables as 0, and strings as null. ".

C and C++ do initialise global and static variables, but not automatics.

Maybe go and have a lie-down.

To disprove my statement, you'd have to demonstrate that 50% or greater of programming languages have a different behavior from what I described. If that's the case, I will gladly concede and we can both go about our days. If you can't demonstrate it, you can still counter it by saying that your experience indicates otherwise. Since my original statement was partially subjective, you can simply state that your subjective experience is different and we can similarly both go about our days.

So maybe you should go and have a lie down instead. :wink:

Also in my programming experience, it seems that most languages initialize numeric variables as 0, and strings as null.

How many programming languages have you used and what were they ?

UKHeliBob:
How many programming languages have you used and what were they ?

At a minimum (I'll include scripting in the interest of being thorough), PHP, JavaScript, HTML, CSS (HTML and CSS probably don't really count, but being thourough...), C, C++, Java, Visual.BASIC, Windows PowerShell (does that count?), Game Maker, Python, Arduino IDE (I know, nearly the same as C++, bust still technically separate), SQL (not sure if that counts either), and probably a couple of others I can't remember. It's also worth noting too that some of these, such as C and C++, have different compilers available, and those compilers can handle variable initialization differently.

likethesandwich:
It's also worth noting too that some of these, such as C and C++, have different compilers available, and those compilers can handle variable initialization differently.

Nope.