Go Down

Topic: Serial coms (Read 208 times) previous topic - next topic

pmoniz

Apr 26, 2019, 06:48 pm Last Edit: Apr 26, 2019, 09:26 pm by pmoniz
Hi guys
I'm trying to write data to the serial monitor by sending an "s" from the serial monitor. Another program will send an "s" and read it's serial monitor capturing the data. I'm having some difficulties with it. Any character will generate the serial print and it prints 3 lines.

Thanks

code in question;

Code: [Select]


Serial.flush();

while (Serial.available() == 0);
char key = Serial.read();
if (key == 's');
 {
  //if (now.hour() < 10){Serial.print('0');}   Serial.print(now.hour(),DEC);   Serial.print(':');    
  //if (now.minute() < 10){Serial.print('0');} Serial.print(now.minute(),DEC); Serial.print(':');
  //if (now.second() < 10){Serial.print('0');} Serial.print(now.second(),DEC); Serial.print(",");
  //Serial.print("bmeTemp: ");   Serial.print(bmeTempC); Serial.print(" °C");
  //Serial.print(", dhtTemp: "); Serial.print(dhtTempC); Serial.println(" °C");
  //Serial.print("TempAve: ");  Serial.print(tempAve);  Serial.println(" °C");
  //Serial.print("Temp: ");    
  Serial.print(TempF); Serial.print(",");     //" °F"
  //Serial.print("dhtHum: ");  Serial.print(dhtH);     Serial.print(" %");
  //Serial.print(", bmeHum: ");  Serial.print(bmeH);     Serial.println(" %");
  //Serial.print("AveHum: ");    
  Serial.print(humAve); Serial.print(",");  
  Serial.print(baro); Serial.println(",");   // Serial.println(" inHg");
  //Serial.print("~Altitude: "); Serial.print(bmeA);     Serial.println(" M");
  //Serial.print("Altitude: ");  Serial.print(Altitude); Serial.println(" FT");
  }
}


Full code

Code: [Select]

// Include Libraries
#include "Arduino.h"
#include "DHT.h"
#include "LiquidCrystal_PCF8574.h"
#include "Wire.h"
#include "RTClib.h"
#include "Adafruit_BME680.h"

// Pin Definitions
#define DHT_PIN_DATA  3

// Define LCD characteristics
#define LCD_ROWS 4
#define LCD_COLUMNS 20
#define BACKLIGHT 255
#define LCD_ADDRESS 0x27

//Set sealevel pressure hectopascals
#define SEALEVELPRESSURE_HPA (1013.25)

// object initialization
DHT dht(DHT_PIN_DATA);
LiquidCrystal_PCF8574 (lcd);
RTC_DS3231 (rtcDS);
Adafruit_BME680 (bme);

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void setup()     // Setup the essentials for your circuit to work. It runs first every time your circuit is powered.
{          
  dht.begin();                                               //start dht
  lcd.begin(LCD_COLUMNS, LCD_ROWS, LCD_ADDRESS, BACKLIGHT);  // initialize the lcd
                           
   // Setup Serial for debugging
   Serial.begin(9600);
   while (!Serial) ; // wait for serial port to connect. Needed for native USB
   //Serial.println("start");

   if (!bme.begin()) {
      Serial.println("Could not find a valid BME680 sensor, check wiring!");
      while (1);
      }
      // Set up oversampling and filter initialization
      bme.setTemperatureOversampling(BME680_OS_8X);
      bme.setHumidityOversampling(BME680_OS_2X);
      bme.setPressureOversampling(BME680_OS_4X);
      bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
      //bme.setGasHeater(22, 150);                            // 22*C for 150 ms

   if (!rtcDS.begin()) {
      Serial.println("Couldn't find RTC");
      while (1);
      }
   if (rtcDS.lostPower()) {
      Serial.println("RTC lost power, lets set the time!");
      // following line sets the RTC to the date & time this sketch was compiled
      rtcDS.adjust(DateTime(F(__DATE__), F(__TIME__)));
      // This line sets the RTC with an explicit date & time, for example to set
      // January 21, 2014 at 3am you would call:
      //rtcDS.adjust(DateTime(2019, 4, 16, 19, 0, 0));
      }
   if (! bme.performReading()) {
      Serial.println("Failed to perform reading :(");
      return;
      }
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void loop() // Main logic of the circuit. It defines the interaction between the components you selected. After setup, it runs over and over again, in an eternal loop.
{
  DateTime now = rtcDS.now();
  float bmeTempC = (bme.temperature);                                                  //BME680 temp in *C
  float dhtTempC = dht.readTempC();                                                    //DHT22 temp in *C
  float tempAve = ((bmeTempC+dhtTempC)/2);                                             //Averages bme & dht temps
  float TempF = ((tempAve*1.8)+32);                                                    //Converts average temp to *F
  float dhtH = dht.readHumidity();                                                     //DHT humidity
  float bmeH = (bme.humidity);                                                         //BME680 humidity
  float humAve = ((dhtH+bmeH)/2);                                                     //averages dht & bme humidities
  float baro = (bme.pressure*0.00029529983071445);                                     //converts hPascals to inHg
  int bmeA = (bme.readAltitude(SEALEVELPRESSURE_HPA));                               //BME680 Calculated altitude
  int Altitude = (bmeA*3.280839895);                                                 //converts BME680 altitude(meters) to feet

   lcd.clear();                                                                            // Clear LCD screen.
   lcd.selectLine(1);                                                                      // Set cursor at the begining of line 1
   lcd.print(TempF,2 ); lcd.print(" F  ");                                                 // Print print the average temp from the dht and bmp to LCD on first line
   lcd.print(baro,2); lcd.print(" inHg");                                                  // Print print the barometric pressure to LCD on first line
   lcd.selectLine(2);                                                                      // Set cursor at the begining of line 2
   lcd.print(humAve,2);lcd.print(" %  ");                                                  // Print print average humidity to LCD on second line
   lcd.print(Altitude);lcd.print(" FT");                                                 // Print print Altitude to LCD on second line
   lcd.selectLine(4);                                                                      // Set cursor at the begining of line 4
   if (now.hour()<10){lcd.print('0');}                                                     // if statement prints leading 0 if hours are single digit(<10)
   lcd.print(now.hour());lcd.print(":");
   if (now.minute()<10){lcd.print('0');}                                                   // if statement prints leading 0 if minutes are single digit(<10)
   lcd.print(now.minute());lcd.print(":");                                                
   if (now.second()<10){lcd.print('0');}                                                   // if statement prints leading 0 if seconds are single digit(<10)
   lcd.print(now.second());                                                                
   
delay(2000);
//Serial.flush();
//serial print testing debugging section
//while (Serial.available() == 0);
//char key = Serial.read();
//if (key == 's');
//   {
  //if (now.hour() < 10){Serial.print('0');}   Serial.print(now.hour(),DEC);   Serial.print(':');    
  //if (now.minute() < 10){Serial.print('0');} Serial.print(now.minute(),DEC); Serial.print(':');
  //if (now.second() < 10){Serial.print('0');} Serial.print(now.second(),DEC); Serial.print(",");
  //Serial.print("bmeTemp: ");   Serial.print(bmeTempC); Serial.print(" °C");
  //Serial.print(", dhtTemp: "); Serial.print(dhtTempC); Serial.println(" °C");
  //Serial.print("TempAve: ");  Serial.print(tempAve);  Serial.println(" °C");
  //Serial.print("Temp: ");    
  Serial.print(TempF); Serial.print(",");     //" °F"
  //Serial.print("dhtHum: ");  Serial.print(dhtH);     Serial.print(" %");
  //Serial.print(", bmeHum: ");  Serial.print(bmeH);     Serial.println(" %");
  //Serial.print("AveHum: ");    
  Serial.print(humAve); Serial.print(",");  
  Serial.print(baro); Serial.println(",");   // Serial.println(" inHg");
  //Serial.print("~Altitude: "); Serial.print(bmeA);     Serial.println(" M");
  //Serial.print("Altitude: ");  Serial.print(Altitude); Serial.println(" FT");
//   }
}

Robin2

It's all the fault of the little guy with the dark glasses!



To make it easy for people to help you please modify your post and use the code button </>


Code: [Select]
so your code looks like this and is easy to copy to a text editor. See How to use the Forum

Your code is too long for me to study quickly without copying to my text editor. The text editor shows line numbers, identifies matching brackets and allows me to search for things like all instances of a particular variable or function.

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

pmoniz

So I tried just a test with this code.

Code: [Select]


void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
while (Serial.available() == 0);

int key = Serial.read()-'0';

Serial.println(key);

}



this is what I get when I send a 1. See attached image.


Power_Broker

Code: [Select]

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


I'm guessing you learned to code in MATLAB, lol


So I tried just a test with this code.
This can be fixed by setting the line ending to "None" in your serial monitor. You can also exclude any whitespace chars in your code, but that's not as easy.
"The desire that guides me in all I do is the desire to harness the forces of nature to the service of mankind."
   - Nikola Tesla

Montmorency

#4
Apr 27, 2019, 02:46 am Last Edit: Apr 27, 2019, 02:50 am by Montmorency
Code: [Select]

int key = Serial.read()-'0';


this is what I get when I send a 1.
This means that you are making things up. You are NOT sending 1.

You are sending 49 (aka '1') and then you are sending 10 (which is LF - line feed -character code).

On your receiving end you are receiving the very same 49, from which you subtract 48 (aka '0') and end up with 1.
Then you are, expectedly, receiving 10, from which you again subtract 48 and end up with -38.

That 1 followed by -38 is what you see in the output.

Please, stop mixing integer constants and character constants. This will only confuse people. And it obviously confuses you as well. 1 and '1' are two completely different things.

Power_Broker

This means that you are making things up. You are NOT sending 1.

You are sending 49 (aka '1') and then you are sending 10 (which is line-feed character code)
You're splitting hairs - he knows he's sending 49 else he wouldn't have subtracted '0' from the read value.


Then you receive 10, from with you again subtract 48 and end up with -38.
Although I didn't specify exactly why, my previous suggestion already remedies this...


Please, stop mixing integer constants and character constants. This will only confuse people. And it obviously confuses you as well. 1 and '1' are two completely different things.
Subtracting by '0' is commonplace and isn't confusing to those who have a basic understanding of ASCII
"The desire that guides me in all I do is the desire to harness the forces of nature to the service of mankind."
   - Nikola Tesla

Montmorency

#6
Apr 27, 2019, 03:01 am Last Edit: Apr 27, 2019, 03:19 am by Montmorency
You're splitting hairs - he knows he's sending 49 else he wouldn't have subtracted '0' from the read value.
He's obviously using a text-based interface to send data (`Serial.print` and `Serial.println`) and at the same time is using binary interface (`Serial.read`) to receive that data. There's nothing wrong with it, but this distinction is what apparently led to certain confusion.

Subtracting by '0' is commonplace and isn't confusing to those who have a basic understanding of ASCII
Well, and that subtraction is exactly what one should never be applying directly to the result of `read()` (!!!), which is my point here. Subtracting '0' should be done only after one made sure that 1) the next byte is received successfully, 2) the next byte is actually an ASCII digit code.

If subtracting '0' right away, as in the above code, is "commonplace" here, then I'm officially declaring the upcoming month a "Back to school" month, which we all are going to dedicate to rooting out this stupid habit. That's how "basic understanding of ASCII" begins.

pmoniz

Thanks for the responses. I'm not a programmer at all. So I don't know what I don't know.

I'm trying to interface my weather station data with another program. It sends the letter "s" and I need to serial.print my temp, humidity,baro pressure, wind speed, wind direction end line so the program can capture it.

I'm trying to apply what I'm getting from sources like https://www.youtube.com/watch?v=g0pSfyXOXj8 to accomplish it but it's not working out for me. This video is clearly showing the binary side.

Thank you power_broker I'll give your suggestion a try. I have no idea what Montmorency is trying to have me do.




Power_Broker

He's obviously using a text-based interface to send data (`Serial.print` and `Serial.println`) and at the same time is using binary interface (`Serial.read`) to receive that data. There's nothing wrong with it, but this distinction is what apparently led to certain confusion.
The only apparent confusion was on your part - OP's only real problem was that OP was not expecting the extra whitespace chars, not a confusion on the difference between different functions to read and write data to/from a serial bus.


Well, and that subtraction is exactly what one should never be applying directly to the result of `read()` (!!!), which is my point here.
I can respect that, but OP will figure that out in time and isn't currently the problem. Even still, OP can throw away negative results of the operation to filter out whitespace chars. There is more than one way to skin a cat.


If subtracting '0' right away, as in the above code, is "commonplace" here, then I'm officially declaring the upcoming month a "Back to school" month, which we all are going to dedicate to rooting out this stupid habit. That's how "basic understanding of ASCII" begins.
LOL. I was saying that subtracting '0' from a char is commonplace (not specifically the return value of .read())
"The desire that guides me in all I do is the desire to harness the forces of nature to the service of mankind."
   - Nikola Tesla

Power_Broker

Back to the actual question at hand...

This tutorial will help you learn the basics of forming and parsing a serial data packet.
"The desire that guides me in all I do is the desire to harness the forces of nature to the service of mankind."
   - Nikola Tesla

pmoniz

Thanks will look at it this evening.

Go Up