hi, im making a project its a remote controlled car, i have an arduino uno, dc motor, servo motor and RGB cathode LED. my problem is that i want the red part of the LED to be dimmable where as the faster it reverses the brighter it is and for the blue the faster it moves forward the brighter it is. below i have two codes one for practicing the dimmable lights and the other is the full project. im using a joystick to control this. the code is the same in both and while it works as desired in the practice code it only comes on fully bright at a certain point in the project code.
is there a reason for this? do i have too much attached to the uno and so it wont dim properly?
int jpin=A1;
int RLED=9;
int jVal;
float RLEDVal;
float BLEDVal;
int del=1000;
int BLED=10;
void setup() {
// put your setup code here, to run once:
pinMode(jpin,INPUT);
pinMode(RLED,OUTPUT);
pinMode(BLED,OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
jVal=analogRead(jpin);
if (jVal<512) {
jVal=analogRead(jpin);
RLEDVal=(255./-512.)*(jVal-512.);
analogWrite(RLED,RLEDVal);
}
if (jVal>512) {
jVal=analogRead(jpin);
BLEDVal=(255./511.)*(jVal-512.);
analogWrite(BLED,BLEDVal);
}
if (jVal==512) {
analogWrite(BLED,0);
}
Serial.println(jVal);
}
#include <Servo.h>
Servo myservo;
int servoPin=6;
int pushButtonPin=7;
int angle =0;
int angleStep=90;
const int minAngle = 0;
const int maxAngle = 180;
int buttonPushed =0;
int speedPin=5;
int dir1=4;
int dir2=3;
int mSpeed=255;
int jpin=A1;
int jVal;
int RLED=9;
int BLED=10;
float RLEDVal;
float BLEDVal;
void setup() {
// put your setup code here, to run once:
pinMode(speedPin,OUTPUT);
pinMode(dir1,OUTPUT);
pinMode(dir2,OUTPUT);
pinMode(jpin,INPUT);
myservo.attach(servoPin);
pinMode(pushButtonPin,INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
jVal=analogRead(jpin);
// DC motor control:
Serial.println(jVal);
if (jVal<512) {
digitalWrite(dir1,LOW);
digitalWrite(dir2,HIGH);
mSpeed=-255./512.*jVal+255.;
analogWrite(speedPin,mSpeed);
}
if(jVal>=512) {
digitalWrite(dir1,HIGH);
digitalWrite(dir2,LOW);
mSpeed=(255./512.)*jVal-255.;
analogWrite(speedPin,mSpeed);
}
// LED control:
if (jVal<512) {
jVal=analogRead(jpin);
RLEDVal=(255./-512.)*(jVal-512.);
analogWrite(RLED,RLEDVal);
}
if (jVal>512) {
jVal=analogRead(jpin);
BLEDVal=(255./511.)*(jVal-512.);
analogWrite(BLED,BLEDVal);
}
if (jVal==512) {
analogWrite(BLED,0);
}
if(digitalRead(pushButtonPin) == LOW){
buttonPushed = 1;
}
if( buttonPushed ){
angle = angle + angleStep;
if (angle <= minAngle || angle >= maxAngle) {
angleStep = -angleStep;
buttonPushed = 0;
}
myservo.write(angle);
delay(100); // waits for the servo to get there
}
}