Go Down

Topic: DC motor PWM MOSFET problem writing code to allow five different speed. (Read 650 times) previous topic - next topic

Richard_N

Hi

I'm trying to write a piece of code which will allow me to enter a number from 0-5 on my computer keyboard which will then through the use of PWM select drive my motor at given speed.

Code: [Select]


//Program by Jeremy Blum
//www.jeremyblum.com
//Test Motor Speed Using a Transistor

//Define Pins
int motorPin = 6;
int motorSpeed = 0;
void setup()
{
  Serial.begin(9600);
  //Set the PWM Motor pin as an output
  pinMode(motorPin, OUTPUT);
}

void loop()
{

    byte incomingbyte = Serial.read(); // this is value entered in serial monitor
motorSpeed = (incomingbyte -48)*51; // subtracting 48 to get decimal value. Multiply by 51 as 255/51 = 5
    analogWrite(motorPin, motorSpeed); // write to the motor pin the motorSpeed
   

}}



This is for a university project so unfortunately I only have an arduino simulator here at home to test with but I'm having the following problems:

This doesn't seem to drive the motor at the desired speed
It doesn't loop

Also I want to hold the speed selected until a new value is entered how would this be achieved?

Hope this is clear, thank you for your help

Grumpy_Mike

Quote
This doesn't seem to drive the motor at the desired speed

How do you know if you only have a simulator?

Quote
It doesn't loop

You have one to many closing braces at the end.

Quote
Also I want to hold the speed selected until a new value is entered how would this be achieved?

By not changing the speed until you have a new byte.

Code: [Select]
byte incomingbyte = Serial.read(); // this is value entered in serial monitor
No this reads the buffer if it contains anything or not. You need to use serial available to see if you actually have data to read.

Richard_N

I know because the simulator displays a value next to the output pin. When I used a piece of source code which cycled the motor speed periodically it displayed the expected values.

Ok so something like

Code: [Select]

{
if Serial.available(){
    byte incomingbyte = Serial.read();
motorSpeed = (incomingbyte -48)*51;
    analogWrite(motorPin, motorSpeed);
   

}}



in my void loop should rectify this?

Go Up