fan + servo.

Hi there.

i have a problem and i can’t find the solution maybe someone here can help me.

the problem is this: i want to send a character through the serial monitor and save this character in a variable “a”. this character it is used to modify the speed of my fan and to move the position of a servo, like this: for example I send the character “!” it is 33 in ASCII and the fan will stop and if I send the character “$” the speed will increase, etc. the max value will be the character “,” is 44 in ASCII and i pretend that when i send the character “%” move the fan to the specific speed and meanwhile move the servo to 90º. That is the problem i can’t increase the speed of the fan and move the servo at the same time. here i leave what i have done till now.

Thanks in advance.

#include<Servo.h>
#include <Sensirion.h>

const uint8_t dataPin = 2; //Declaracion patillas arduino
const uint8_t clockPin = 3;
int motor = 9;
int a;
const uint8_t servopin=12;
float temperature; //Declaracion variables
float humidity;
float dewpoint;
float servoang;
int pwmc;


Servo myservo;
Sensirion tempSensor = Sensirion(dataPin, clockPin); //Declaracion objeto sensor
void setup()
{
Serial.begin(9600); //Declaracion puerto serie
myservo.attach(servopin);
pinMode(9, OUTPUT);

}
void loop() {
  tempSensor.measure(&temperature, &humidity,&dewpoint);
  Serial.println(temperature*100);
  Serial.println(humidity*100);
  delay (200);
  
if (Serial.available()>0){ 
a = Serial.read();
servoang = Serial.read();
if (a>='!' && a<=','){
int pwmc = map(a,'!',',',255,0);
analogWrite(motor,pwmc);
if (a=='%'){servoang=90;
myservo.write(servoang);
}
}
}
}

Your help will be really appreciated.

If I understand correctly, you want to achieve the following:

! = fan stop $ = speed increase , = max speed % = set fan at specific speed and move servo to 90 degrees

where the first character is the command code entered through the serial monitor.

You could try using a switch statement:

a = Serial.read();
switch (a) {

case '!'  :
  // statement(s);
  break;

case '

:   // statement(s);   break;

//etc.

  /* you can have any number of case statements / default : / Optional */   statement(s); } ```

The servo library disables PWM (analogWrite) on pins 9 and 10.

From the servo lib reference:

On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

Thanks a lot. I changed the pin and i've used the switch function and now the both are working well.