Go Down

Topic: can arduino serial.read() values?? (Read 972 times) previous topic - next topic

Tom@Jerry

i have a project whereby need to input value of rpm into a motor via arduiono..is there any sample coding for me as reference.?? i need to input value of rpm ex : when i input 255rpm = motor runs at 255pwm..

thankx in advance.... :smiley-roll:

bubulindo

Depends on how you send it.

Imagine you send it in ASCII, meaning you'll receive a string.

Code: [Select]


#define DESCRIPTOR    'P'
char temp[4];


temp[3] = '\0';


if (Serial.available() > 5) { //<descriptor><value><value><value><end character>
   if (Serial.read() == DESCRIPTOR) { //first is correct.
      for(int i = 0; i<3; i++) {
         temp[i] = Serial.read();
      }
   if (Serial.read() == '\n') { // the string is correct... sort of ...
      pwm = atoi(temp);
   }

analogWrite(pwm); //there you go...


However, you can avoid that if you control the software that sends the command. What are you using to send the command?
Eu não sou o teu criado. Se respondo no fórum é para ajudar todos mediante a minha disponibilidade e disposição. Responder por mensagem pessoal iria contra o propósito do fórum e por isso evito-o.
Se realmente pretendes que eu te ajude por mensagem pessoal, então podemos chegar a um acordo e contrato onde me pagas pela ajuda que eu fornecer e poderás então definir os termos de confidencialidade do meu serviço. De forma contrária toda e qualquer ajuda que eu der tem de ser visível a todos os participantes do fórum (será boa ideia, veres o significado da palavra fórum).
Nota também que eu não me responsabilizo por parvoíces escritas neste espaço pelo que se vais seguir algo dito por mim, entende que o farás por tua conta e risco.

Dito isto, mensagens pessoais só se forem pessoais, ou seja, se já interagimos de alguma forma no passado ou se me pretendes convidar para uma churrascada com cerveja (paga por ti, obviamente).

Tom@Jerry

const int ledPin = 6;      // the pin that the LED is attached to

void setup()
{
  // initialize the serial communication:
  Serial.begin(9600);
  // initialize the ledPin as an output:
  pinMode(ledPin, OUTPUT);
 
}

void loop() {

  byte brightness;

  // check if data has been sent from the computer:
  if (Serial.available()) {
    // read the most recent byte (which will be from 0 to 255):
    brightness = Serial.read();
    // set the brightness of the LED:
    analogWrite(ledPin, brightness);
   
   
  }
  Serial.println(brightness);
  delay(500);
}
----------------------------------------------------------------------------------------------------------------------------------------------------
i want to do like this, which mean during the serial monitor, i would like to insert "255" means max pwm... then the num "255: will eventually insert into one of the coding to initalize motor at pwm "255" pwm..huuuuu

thanx in advance...8)... i try yours bubulindo..but smehow i dont get it....

PaulS

Quote
i want to do like this, which mean during the serial monitor, i would like to insert "255" means max pwm... then the num "255: will eventually insert into one of the coding to initalize motor at pwm "255" pwm..huuuuu

You'll need to rewrite the Serial Monitor application, then.

The Serial Monitor takes whatever text you have keyed in, and sends it to the serial port.

Unless you intend to rewrite the Serial Monitor application, then you must rewrite the Arduino code to collect the string that the Serial Monitor application sends, and convert the string back to an int.


Nick Gammon

@fendywoo

Read this before posting a programming question

Please edit your post, select the code, and put it between [code] ... [/code] tags.

You can do that by hitting the # button above the posting area.
http://www.gammon.com.au/electronics

Tom@Jerry

thankx for the guide to posting code...im already have the solution of insert numbers like "255", right now im trouble in combining insert(character) and (numbers).. the code as attached.
Code: [Select]

////// to insert values(numbers) for pwm to function.
const int motor = 6;      //pin motor in pwm
int inLetter;


void setup()
{
  // initialize the serial communication:
  Serial.begin(9600);
   Serial.print("BEGIN");
  // initialize the ledPin as an output:
  pinMode(motor, OUTPUT);
 
}

void loop()
{
 
char buffer[] = {' ',' ',' ',' ',' ',' ',' '}; // Receive up to 7 bytes
while (!Serial.available()); // Wait for characters
Serial.readBytesUntil('\n', buffer, 7);
int incomingValue = atoi(buffer);
Serial.println(incomingValue);
analogWrite(motor, incomingValue);
delay(500);


}


Code: [Select]

/////////// insert character acting as a switch to CW@ A-CW motor.
int cw = 7;
int pwm = 6;
int ledPin1 = 8;

void setup()
{
    Serial.begin(9600);
    Serial.print("BEGIN");
    pinMode(cw,OUTPUT);
    pinMode(pwm,OUTPUT);
    pinMode(ledPin1,OUTPUT);
}

void loop()
{
 
  int inLetter;
  if(Serial.available())
  {
    inLetter = Serial.read();
    if(inLetter == 'R')
    {
      digitalWrite(cw,HIGH);///// turns clockwise
      digitalWrite(ledPin1,HIGH);
      analogWrite(pwm,255);
      //Serial.print(pwm);
      Serial.println("R");
      delay(500);
       
    }
   else if (inLetter == 'T')
   {
     digitalWrite(cw,LOW);////turns anti-clockwise
     digitalWrite(ledPin1,LOW);
     analogWrite(pwm,100);
     //Serial.print(pwm);
     Serial.println("T");
     delay(500);
     

  }

 
}

}


this is just a sample that i have been modified, i just need to combine them together... thank you in advanced...

PaulS

Code: [Select]
Serial.readBytesUntil('\n', buffer, 7);
The character array returned by this function is NOT null terminated.

Code: [Select]
int incomingValue = atoi(buffer);
Therefore, it is NOT suitable input to atoi() which expects a NULL terminated array of chars.

Quote
this is just a sample that i have been modified, i just need to combine them together

First thing to do is define the requirements of the resulting program. Then, you pick the bits and pieces from each of the original programs that implement those requirements.

Tom@Jerry

Quote

First thing to do is define the requirements of the resulting program. Then, you pick the bits and pieces from each of the original programs that implement those requirements.



im still new in this arduino coding, so can u show me how to solve it? i really do appreciate it...

billroy

#8
Nov 14, 2012, 01:57 pm Last Edit: Nov 14, 2012, 01:59 pm by billroy Reason: 1
Here's an easy way: install the Bitlash interpreter on your Arduino (http://bitlash.net).  Upload the Bitlashdemo sketch.  Then your problem comes down to defining a function in Bitlash to go clockwise, and another to go counterclockwise (ccw).  You can copy and paste these into Bitlash in the serial monitor:
Code: [Select]

// pwm motor controls
//
function startup { pinmode(6,1); pinmode(7,1); pinmode(8,1); }
function gocw { d7=1; d8=1; a6=255; }
function goccw { d7=0; d8=0; a6=100; }

Then when you type "gocw" it will call the gocw function to make the motor go clockwise, and likewise with "goccw".  I'm guessing you'll also need a function named "stop"...

-br

Edit: Once that's working, to set the rpm, change the functions to look like this:
Code: [Select]

function gocw { d7=1; d8=1; a6=arg(1); }
function goccw { d7=0; d8=0; a6=arg(1); }

And you can type "gocw(237)" or "goccw(10)".  So maybe stop is just gocw(0)?


PaulS

Quote
im still new in this arduino coding, so can u show me how to solve it?

What are the requirements for the new program? That must be step 1, and only YOU can define them.

Tom@Jerry

the requirement is: i have to code a program for a motor with various speed(rpm) and direction.
1. i have to use serial monitor to insert char ( C = clockwise , AC = anti-clockwise) for motor to rotates clockwise or vice versa. then move to step 2
2. i have to use serial monitor again to  insert values (1 till 255) pwm for motor speed which gives user to insert any values within the range of (1 till 255).
hence, u have a choice to insert char ( rotation of motor) while insert( values )for motor to rotates at certain rpm.

thats why i need to combine both coding as shown above..thankx Pauls...

PaulS

Quote
1. i have to use serial monitor to insert char ( C = clockwise , AC = anti-clockwise) for motor to rotates clockwise or vice versa.

I think you are misusing the term "insert" when you mean "enter".

AC is not a character. A is. C is. AC is a string.

Quote
2. i have to use serial monitor again to  insert values (1 till 255) pwm for motor speed which gives user to insert any values within the range of (1 till 255).

The range of PWM values is 0 to 255.

Forget about the motor for now. The goal is to read serial data and parse it. If the Serial Monitor is set to append a carriage return and linefeed to the entered data, enter C35 and hit send.

Write a sketch for the Arduino that simply reads and echoes the serial data. When that works, create a fixed size (you count, don't make the compiler do it) array of chars and an index varaible. Each time you read a character, store it in the array at the location defined by the index, increment the index, and store a NULL in the array at the location defined by the index, if the character is not a carriage return or line feed.

If it is, print what is in the array, reset the index variable to 0, and put a NULL in position 0 of the array.

When that works, making use of the data, instead of just printing it will be trivial.

Tom@Jerry

Code: [Select]

//encoder
volatile byte rpmcount;
unsigned int rpm;
unsigned long timeold;
//motor and keyin data
int cw = 7;
int pwm = 6;
int ledPin1 = 5;
int ledPin2 = 4;

void setup()
{
    Serial.begin(9600);
    Serial.print("BEGIN");
    pinMode(cw,OUTPUT);
    pinMode(pwm,OUTPUT);
    pinMode(ledPin1,OUTPUT);
    pinMode(ledPin2,OUTPUT);

//key in data
   digitalWrite(2, HIGH);
   attachInterrupt(0, rpm_fun, RISING);
   rpmcount = 0;
   rpm = 0;
   timeold = 0;
   
}


 
void loop()
{
 
  int inLetter;
  if(Serial.available())
  {
    inLetter = Serial.read();
    if(inLetter == 'C')
    {
     
     
      char buffer[] = {' ',' ',' ',' '}; // Receive up to 4 bytes
      while(!Serial.available());
      Serial.readBytesUntil('\n', buffer, 4);
      int incomingValue = atoi(buffer);
      Serial.println("R");
      digitalWrite(cw,HIGH);
      digitalWrite(ledPin1,HIGH);
      digitalWrite(ledPin2,LOW);
      analogWrite(pwm,incomingValue);
      //Serial.print(pwm);
      Serial.println(incomingValue);
      delay(500);
     
     
       
     
    }
   else if (inLetter == 'A')
   {
     char buffer[] = {' ',' ',' ',' '}; // Receive up to 4 bytes
      while(!Serial.available());
      Serial.readBytesUntil('\n', buffer, 4);
      int incomingValue = atoi(buffer);
     digitalWrite(cw,LOW);
     digitalWrite(ledPin1,LOW);
     digitalWrite(ledPin2,HIGH);
     analogWrite(pwm,incomingValue);
     //Serial.print(pwm);
     Serial.println("T");
     Serial.println(incomingValue);
     delay(500);
      }
      else
      {
    char buffer[] = {' ',' ',' ',' '}; // Receive up to 4 bytes
      while(!Serial.available());
      Serial.readBytesUntil('\n', buffer, 4);
      int incomingValue = atoi(buffer);
     digitalWrite(cw,LOW);
     digitalWrite(ledPin1,LOW);
     digitalWrite(ledPin2,LOW);
     analogWrite(pwm,0);
     //Serial.print(pwm);
     Serial.println("T");
     Serial.println(incomingValue);
     delay(500);
      }
     }



  if(rpmcount >=20)
     {//Update RPM every 20 counts, increase this for better RPM resolution,
     //decrease for faster update
     float rpm = float (14*60)/(millis() - timeold)*rpmcount;
     timeold = millis();
     rpmcount = 0;
     Serial.println(rpm,4);
}
}
void rpm_fun()
{
   rpmcount++;
   //Each rotation, this interrupt function is run twice
}

this program is functionable and i had test it. 
i had solve the problems...thanks to all who guide and help me...this is the code used in my motor project, hope it can be improved and re-used to others...

Go Up