Go Down

Topic: How to send numbers from one Arduino to another using Serial (Read 4856 times) previous topic - next topic

Nick Gammon

In other words, set a flag or something when all the figures have arrived (at a newline or something). Then do the logging, and the delay, once, and clear that flag for next time.
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

thrasiel

I managed to get it working, the thing was the switch code for the received numbers as you said it...i rewrote the code and put everything in the last case, that worked.

like this:

Code: [Select]

#include <SD.h>
#include <Wire.h>
#include "Rtc.h"
#include <DHT22.h>



const char inicionumero = '<';
const char finnumero = '>';
char temperatura[10];
char humedad[10];
char polvo[10];
char temperatura2[10];
char humedad2[10];
char polvo2[10];
char datos[100];

float dustValenvio = 0.0;
float a = 0.0;
int dustPin=0;
float dustVal=0.0;

int ledPower=2;
int delayTime=280;
int delayTime2=40;
float offTime=9680;


enum { getTemperature, getHumedad, getDust };

int whichNumber = getTemperature;

float  temperature, humidity, dust;

#define DHT22_PIN 4

// Inicio de Setup DHT22
DHT22 myDHT22(DHT22_PIN);



float enviodatosT = 0;
float enviodatosH = 0;

const int chipSelect = 8;

char time[20];
char date[20];

Rtc rtc;


void setup ()
  {
  Serial.begin (9600);
    pinMode(ledPower, OUTPUT);
    pinMode(10, OUTPUT);
   
   
     if (!SD.begin(chipSelect)) {
       return;
     }
  Rtc rtc = Rtc(0,0,0,1,1,1,11,0xAA);
  }
 

void processNumber (const long n)
  {
  DHT22_ERROR_t errorCode;
  errorCode = myDHT22.readData();
  if(errorCode == DHT_ERROR_NONE)
  {
  enviodatosT = myDHT22.getTemperatureC()/1.0;
  enviodatosH = myDHT22.getHumidity()/1.0;
  }
 
  float x = n/100.0; 
 
  switch (whichNumber)
    {
    case getTemperature:
      temperature = x;
      dtostrf(temperature,1,2,temperatura);
      strcpy(datos, temperatura);
      strcat(datos, ";");
      whichNumber = getHumedad;
      Serial.print ("Temperature = ");
      Serial.println(temperatura);
      break;
     
    case getHumedad:
      humidity = x;
      dtostrf(humidity,1,2,humedad);
      strcat(datos, humedad);
      strcat(datos, ";");
      whichNumber = getDust;
      Serial.print ("Humidity = ");
      Serial.println(humedad);
      break;

    case getDust:
      dust = x;
      dtostrf(dust,1,2,polvo);
      strcat(datos, polvo);
      strcat(datos, ";");
      whichNumber = getTemperature;
      Serial.print ("Dust = ");
      Serial.println(polvo);
           
                dtostrf(enviodatosT,1,2,temperatura2);
                dtostrf(enviodatosH,1,2,humedad2);
                strcat(datos, temperatura2);
                strcat(datos, ";");
                strcat(datos, humedad2);
                strcat(datos, ";");
                      digitalWrite(ledPower,LOW); // power on the LED
                      delayMicroseconds(delayTime);
                      dustVal=analogRead(dustPin); // read the dust value via pin 5 on the sensor
                      delayMicroseconds(delayTime2);
                      digitalWrite(ledPower,HIGH); // turn the LED off
                      delayMicroseconds(offTime);
                      if(dustVal<125)
                        {
                        dustValenvio = 0.0;
                        dtostrf(dustValenvio,1,2,polvo2);
                        }
                       else {
                        a=(dustVal*5)/1023;
                        dustValenvio=(a-0.611)/5.1720;
                        dtostrf(dustValenvio,1,2,polvo2);
                           }
                  strcat(datos, polvo2);
                  strcat(datos, ";");
                  rtc.GetDate();
                  rtc.Time(time);
                  rtc.Date(date);
                  strcat(datos, date);
                  strcat(datos, ";");
                  strcat(datos, time);
     
                  File dataFile = SD.open("datalog.csv", FILE_WRITE);

                  // if the file is available, write to it:
                  if (dataFile) {
   
                  // write file
                  if(enviodatosT>0 && enviodatosH>0 && dustValenvio>0)
                    {
                      dataFile.println(datos);
                      dataFile.close();
                     }
                  }
      Serial.println(datos);
      delay(5000);
      break;
          }
          } 

void processInput ()
  {
  static float receivedNumber = 0;
  static boolean negative = false;
 
  byte c = Serial.read ();
 
  switch (c)
    {
     
    case finnumero: 
      if (negative)
        processNumber (- receivedNumber);
      else
        processNumber (receivedNumber);

    // fall through to start a new number
    case inicionumero:
      receivedNumber = 0;
      negative = false;
      break;
     
    case '0' ... '9':
      receivedNumber *= 10;
      receivedNumber += c - '0';
      break;
     
    case '-':
      negative = true;
      break;
     
    }
  } 

void loop ()
  {
 
  if (Serial.available ())
  {
      processInput ();
        }   
             
  }


So again, thanks mr. Nick, im not so experienced in this stuff, but you always come with great ideas and patience, now my project is almost finished and that could not be achieved without your help.

greetings.


Ignacio.

robtillaart

Good tutorial Nick, but there is a small flaw in your example parser

if you receive <43-21> what will be the number?  -4321?   [case can happen when 2 chars "><" are lost due to buffer overrun whatever]

To solve this the parser need to check that the '-' sign comes directly after the '<'  start char.  
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Nick Gammon

Good point, although for sake of clarity it didn't do a lot of error checking. By the same token it would accept "<>" as the number zero.

You could modify it to include floats, for example, and then you need to check you only get a single decimal point.

I've added a note to my page to point out the problem you raised. (I haven't changed the code, just pointed out the possibility of that problem).
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

robtillaart

OK, you 're right not to complicate the tutorial code by error handling, that is left as an exercise for the reader ;)
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Nick Gammon

Of course, if data can be lost other things can go wrong as well. "-42" might become "42" if the minus sign is lost. Or "1234" could become "124".

So really, for secure communications, you need some sort of CRC check.
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

PaulS

Quote
OK, you 're right not to complicate the tutorial code by error handling, that is left as an exercise for the reader

I'd just be sure to point out that the exercise IS left for the reader to do. Without any sort of warning, the user will assume that the code is robust, and not add any error checking.

Nick Gammon

OK, I've added extra warnings. Like the ones on packets of peanuts: "Warning: contains nuts.".
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

PaulS

Quote
"Warning: contains nuts."

I think I've been subtly insulted. But, I laughed anyway.

Docedison

No, Paul I think his apparent cynicism is unfortunately right on target.

Bob
--> WA7EMS <--
"The solution of every problem is another problem." -Johann Wolfgang von Goethe
I do answer technical questions PM'd to me with whatever is in my clipboard

Nick Gammon


I think I've been subtly insulted.


Not intentionally. There was one on a tractor: "Warning: avoid death".
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

matinzk

Sorry to bump up this thread:  I have used this and works pretty well.

I only send 1 piece of data from one Arduino to another. First Arduino gathers data and sends it to a second Arduino that received this piece of data. What I'd like to do is to set the received data to a variable. Then re-use it in my "Loop".

Code I am using in my receiving part is this, but doesn't work as expected:-

Code: [Select]


const char startOfNumberDelimiter = '<';
const char endOfNumberDelimiter   = '>';

long _r = 0;

void setup ()
  {
  Serial.begin (115200);
  Serial2.begin (115200);
  Serial3.begin (115200);
 
   pinMode(8, INPUT); 
  } // end of setup
 
void processNumber (const long n)
  {
      _r = n;

  }  // end of processNumber
 
void processInput ()
  {
  static long receivedNumber = 0;
  static boolean negative = false;
 
  byte c = Serial2.read ();
 
  switch (c)
    {
     
    case endOfNumberDelimiter: 
      if (negative)
        processNumber (- receivedNumber);
      else
        processNumber (receivedNumber);

    // fall through to start a new number
    case startOfNumberDelimiter:
      receivedNumber = 0;
      negative = false;
      break;
     
    case '0' ... '9':
      receivedNumber *= 10;
      receivedNumber += c - '0';
      break;
     
    case '-':
      negative = true;
      break;
     
    } // end of switch 
  }  // end of processInput
 
void loop ()
  {
       
        if (Serial2.available ())
        {
          processInput ();
        }
                       
        Serial.println(_r);

  }



Any help is appreciated.

PaulS

Quote
but doesn't work as expected:

How does it work? How do you expect it to work? How are those different?


matinzk

When it's done the original way when I stream lets say the number 8000 it gets there as 8000. However when I use my code it's sometimes 800, sometimes 80 or even 8.


PaulS

Quote
When it's done the original way when I stream lets say the number 8000 it gets there as 8000.

What is "the original way"?

Your code is expecting "<8000>", not "8000". Are you sending it correctly? What does your debug output tell you? Oh wait, you don't have any!

processInput() collects the serial data that is in the buffer. It does NOT block until the end of the packet has arrived. You are printing the value as though the whole packet had arrived, on each pass through loop, even though there is a better then even chance that it has not.


Go Up