Pages: [1]   Go Down
Author Topic: DC motor PWM MOSFET problem writing code to allow five different speed.  (Read 633 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 12
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:

//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
Logged

Manchester (England England)
Offline Offline
Brattain Member
*****
Karma: 634
Posts: 34518
Solder is electric glue
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 12
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
{
 if Serial.available(){
    byte incomingbyte = Serial.read();
 motorSpeed = (incomingbyte -48)*51;
    analogWrite(motorPin, motorSpeed);
   
 
}}



in my void loop should rectify this?
Logged

Pages: [1]   Go Up
Jump to: