0

I'm writing a library for Arduino, and I've run into this problem: I need to create an uint8_t variable to define an analog pin (Ax) and I'm not being able to do it in an easy way.

This more or less illustrates my problem, _pin being an uint8_t:

sensortemp::sensortemp(int pin)     // Constructor
{
    // being _pin an uint8_t
    // _pin = A0 if pin = 0;
    // _pin = A1 if pin = 1;
    // etc.
}

The only working solution I've found is one I do NOT want to use...

sensortemp::sensortemp(int pin)
{
   if(pin == 0)
    _pin = A0;
   else if(pin == 1)
    _pin = A1;
   else if(pin == 2)
    _pin = A2;
   else if(pin == 3)
    _pin = A3
}

I hope someone can help me with this uint8_t problem :) Thanks in advance

eduherminio
  • 1,514
  • 1
  • 15
  • 31

1 Answers1

2

There's no problem with type conversion and what you're looking for is:

_pin = pin + A0;

optionally with a range check. Also, if _pin is uint8_t, then make pin the same too. Throw in a static_cast if you're getting a warning:

_pin = static_cast<uint8_t>(pin + A0);

Arduino pins are defined as integers, starting from A0 constant (e.g. 14 for Arduino Uno or 54 for Arduino Mega - because of more digital pins that are listed before). They are all defined to be consecutive integers, so you just have to add the offset (pin) with the first analog pin (A0).


You might want to use member initializer list for best practice if you're not going to check for invalid pin.

Community
  • 1
  • 1
LogicStuff
  • 19,397
  • 6
  • 54
  • 74