0

So basically I have a circuit with a phototransistor, and want to convert the phototransistor value into a PWM signal that can control the speed of the motor. The code I came up with is below, however it does not work. What have I done wrong in my code? I am using an l293d chip.

int photoTran = A1;
int reading = 0;
int forward=2;
int backward=3;
int motorspeed=0;


void setup(){
  pinMode(photoTran,INPUT);
  Serial.begin(9600);
  pinMode (backward, OUTPUT);
  pinMode (forward, OUTPUT);
}

void loop(){
  lcd.setCursor(0,0);
  reading = analogRead(photoTran);
  lcd.print(reading);
  lcd.print("  ");
  delay(100);
{ 
  if (reading<30){
    digitalWrite(backward,HIGH);
    digitalWrite(forward,LOW);
    motorspeed = map(reading, 30, 1023, 0, 255);
    analogWrite(backward,motorspeed);
  }
  else {
    digitalWrite(backward,LOW);
    digitalWrite(forward,HIGH);
    motorspeed = map(reading, 30, 400, 0, 255);
    analogWrite(forward,motorspeed);
  }
  }
}
  • You need to be a little more specific than that. Do you know that the phototransistor works on its own, and same with the motor driver? Also, what is not working? Is it not compiling, not showing a proper value on the lcd, not affecting the motor, etc? In your code I see "{" after your delay(100) which I don't see that purpose of that and why the if/else statements are inside it. I would get rid of that and test. – Braydon Burkhardt May 18 at 3:45
  • A phototransistor is hard to calibrate, and should rather be used as a switch (digitalRead) – DataFiddler May 18 at 14:51
0

analogRead() returns an integer between 0 and 1023. Using 30 and 400 in the map() function, then passing in a value outside of that range will cause strange results. Here is a sketch to illustrate my point.

void setup(){

  Serial.begin(9600);

  // Prints -20 to 684
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 30, 400, 0, 255));
  }
  Serial.println();

  // Prints -7 to 255
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 30, 1023, 0, 255));
  }
  Serial.println();

  // Prints 0 to 255
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 0, 1023, 0, 255));
  }
}

void loop(){}
0

If you are using l293d you must control the voltage on its ENABLE PIN rather than controlling it on other INPUT PINS (l293d). Here is simple tutorial on controlling the Motor using L293d. here.

And @VE7JRO is right about map() function as your are passing the values that are out of range please take care of that part as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.