hello every one :
I'm using arduino Uno to receive and read the sensor data by using serial read and then to control the DC motor speed.
the arduino can receive and read sensor data correctly. but the motor speed is not effected by that data.
can any one guide me to solve this problem.
here is my simple code
const int pwm_motor1 =9;
const int pwm_motor2 =11;
const int dir1 =8;
const int dir2 =12;
void setup()
{
// Set pin as output for 'M1'
pinMode(pwm_motor1, OUTPUT);
// Set pin as output for 'M2'
pinMode(pwm_motor2, OUTPUT);
pinMode(dir1, OUTPUT);
pinMode(dir2, OUTPUT);
Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud
}
void loop()
{
while (Serial.available())
{
char angle = Serial.read();
Serial.print(angle);
if(angle >= 0 && angle <= 30)
{
// write output for 'M1'
analogWrite(pwm_motor1, LOW);
digitalWrite(dir1,LOW);
// write output for 'M2'
analogWrite(pwm_motor2, LOW);
digitalWrite(dir2,LOW);
}
else if(angle > 30 && angle <= 90)
{
analogWrite(pwm_motor1, HIGH);
digitalWrite(dir1,LOW);
// write output for 'M2'
analogWrite(pwm_motor2, HIGH);
digitalWrite(dir2,LOW);
}
}
}
char angle = Serial.read(); // You're reading in one char at a time
.
.
if(angle >= 0 && angle <= 30) // but yet you are looking for an actual value.
.
else if(angle > 30 && angle <= 90)
You should write a function or something that gets one or two chars and converts them into the values you want.
Servo test code that shows how to capture a character string representing a number into a number for use in the code.
// zoomkat 7-30-10 serial servo test
// type servo position 0 to 180 in serial monitor
// for writeMicroseconds, use a value like 1500
// use serial monitor to test
String readString;
#include <Servo.h>
Servo myservo; // create servo object to control a servo
void setup() {
Serial.begin(9600);
myservo.attach(9);
}
void loop() {
while (Serial.available()) {
if (Serial.available() >0) {
char c = Serial.read(); //gets one byte from serial buffer
readString += c; //makes the string readString
delay(3);
}
}
if (readString.length() >0) {
Serial.println(readString);
int n = readString.toInt();
Serial.println(n);
myservo.writeMicroseconds(n);
//myservo.write(n);
readString="";
}
}
thank u so much for replay
actually i have tried some coding to change char into integer but it's not working
can i have that coding to see the differences?
so, what should i do?
if the data printed in serial monitor in this form
-0.24
-0.25
-0.3
-0.3
-0.25
-0.24
-0.23
-0.23
-0.32
-0.37
-0.4
-0.65
-0.93
-1.21
-2.94
-4.8
-5.24
Gather a number into a chr array. When you see a CR that is carriage return, replace that with a null meaning a zero then use atof to convert it into a float variable.