Pages: [1]   Go Down
Author Topic: How to make the serial read more than one value?  (Read 763 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

Hello

I want my serial to read diferent stuff that I input like:

int [x, y, z] = Serial.read();

So then on Serial Monitor I may use values for my variables like : "1, 2, 3"

All in all what I dont know is how to make the serial read more than one value?

Anyone can help me?
Logged

'round the world...
Offline Offline
Faraday Member
**
Karma: 42
Posts: 3263
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Like this?

Code:

#define X    0
#define Y    1
#define Z    2

char array[3]

for (char i = 0; i <3 ; i++) array [i] = Serial.read();



Although this is not what I would call data transfer.
Logged

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).

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

Ok I will get more specific, heres the code:

void setup() {
 
  Serial.begin(9600);  // initialize serial communication:
}

void loop() {
 
  if (Serial.available() > 0) { 
   
    int freq, duration = Serial.read();   
   

  // play a note on pin 8 for 300 ms:
  tone(8, freq, duration);
  delay(300);

I just want to input the frequency and the duration on the serial monitor. But the code above does nothing. Sorry, I am kind of new to programming.
Logged

Global Moderator
Offline Offline
Brattain Member
*****
Karma: 485
Posts: 18806
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Part of the code, huh?

This line:

Code:
    int freq, duration = Serial.read();   

... defines two variables. freq has an undefined value, and duration is assigned the results from Serial.read ().

Closer to your objective would be:

Code:
if (Serial.available() > 1) {
   
    int freq = Serial.read ();   
    int duration = Serial.read ();
}

Logged


Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 614
Posts: 49372
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Note that all of these suggestions so far will read a one digit number for freq and duration.

"1200, 30" will NOT result in freq = 1200 and duration = 30. That is a completely different process.

http://jhaskellsblog.blogspot.com/2011/05/serial-comm-fundamentals-on-arduino.html
Logged

Global Moderator
Offline Offline
Brattain Member
*****
Karma: 485
Posts: 18806
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Good point. My code would read from your example of "1, 2, 3" a "1" into the first variable and a "," into the second one.
Logged


'round the world...
Offline Offline
Faraday Member
**
Karma: 42
Posts: 3263
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Good point. My code would read from your example of "1, 2, 3" a "1" into the first variable and a "," into the second one.

In case the op doesn't know... "1" = 49.

Arduino is probably the highest level programming language for 8 bit microcontrollers, but it is still not that high. So you have to do some of the dirty work to achieve what you want.
Logged

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).

Global Moderator
UK
Offline Offline
Brattain Member
*****
Karma: 302
Posts: 26324
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
In case the op doesn't know... "1" = 49.
sp. '1'       smiley-wink
Logged

"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

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

Ok this is all still very confusing to me.

Two things I think I got it:

First I need to convert the ASCII char to hexadecimal.

Second I am still confused as to read 2 values on the serial.read.

So: "1200, 30" will NOT result in freq = 1200 and duration = 30

How do I do that?

I wish Arduino Software would have a better interface using Serial Monitor. Something like a ASCII to hex converter. I mean my programming skills are based on trial and error ( much of it) and interaction with the serial comm is the best way to test things.

Anyway, I read the article on the blog, but as expected i became very confused.

The point is I want to test tones at diferent frequencies and durations using serial interface. Anyone knows a good solution?

Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 614
Posts: 49372
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
First I need to convert the ASCII char to hexadecimal.
Why do you think you need to do this? What is sending the data?

Quote
How do I do that?
I'm not in the habit of posting random useless links. Read the link I posted.

Quote
Something like a ASCII to hex converter.
The Arduino can convert a character array containing hex characters to a value.

Quote
but as expected i became very confused.
Read it again, then. It is pretty straightforward. If you have questions, ask.

Quote
Anyone knows a good solution?
If you mean "does anyone want to write the code for me", no.
Logged

0
Offline Offline
Tesla Member
***
Karma: 145
Posts: 9627
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

The below code is for servos, but it shows a simple way to send two values together from the serial monitor, split the values, and convert the vaues into numbers for use with the servos.

Code:
// zoomkat 10-20-11 serial servo (2) test
// for writeMicroseconds, use a value like 1500
// for IDE 0022 and later
// Powering a servo from the arduino usually DOES NOT WORK.
// two servo setup with two servo commands
// send eight character string like 15001500 or 14501550

#include <Servo.h>
String readString, servo1, servo2;
Servo myservo1;  // create servo object to control a servo
Servo myservo2;

void setup() {
  Serial.begin(9600);
  myservo1.attach(6);  //the pin for the servo control
  myservo2.attach(7);
  Serial.println("servo-test-22"); // so I can keep track of what is loaded
}

void loop() {

  while (Serial.available()) {
    delay(1);  
    if (Serial.available() >0) {
      char c = Serial.read();  //gets one byte from serial buffer
      readString += c; //makes the string readString
    }
  }

  if (readString.length() >0) {
      Serial.println(readString); //see what was received
      
      // expect a string like 07002100 containing the two servo positions      
      servo1 = readString.substring(0, 4); //get the first four characters
      servo2 = readString.substring(4, 8); //get the next four characters
      
      Serial.println(servo1);  //print to serial monitor to see results
      Serial.println(servo2);
      
      int n1; //declare as number  
      int n2;
      
      int n1 = servo1.toInt();
      int n2 = servo2.toInt();
      
      myservo1.writeMicroseconds(n1); //set servo position
      myservo2.writeMicroseconds(n2);
    readString="";
  }
}

Logged

Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   smiley-cool

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

Thanks all for the help.

zoomkat: Straight to the point! I like it! Your example is very much appreciated, and serves me right  smiley-wink
Logged

Global Moderator
UK
Offline Offline
Brattain Member
*****
Karma: 302
Posts: 26324
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Just be aware that zoomkat's example may not work reliably if you change the serial line speed.
Logged

"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Pages: [1]   Go Up
Jump to: