User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

How to trigger data sent from Arduino

Mon Jun 19, 2017 1:25 am

Currently I have this script on the Arduino, constantly sending info to the raspberry pi 2:

Code: Select all

float flow = 111.22;
int n = 0;
void setup() {
  Serial.begin( 9600 );    // 9600 is the default baud rate for the serial Bluetooth module
}
void loop() {
  // If there are bytes available in the serial input buffer
  if (Serial.available()) {
    // Read a single byte and write it back over serial
    Serial.write(Serial.read());
  }    
}
The rpi runs this script to receive the data:

Code: Select all

#! /usr/bin/env python
import serial
from time import sleep
ser = serial.Serial(port='/dev/serial0',parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=1)
print "Serial is open: " + str(ser.isOpen())
while 1:
        try:
                if(ser.inWaiting()>0):
                        myData = ser.readline()
                        print myData
        except KeyboardInterrupt:
                exit()
However I dont want to waste resources on the Arduino having it send data constantly. I only want to receive data once a day. The rpi is using bluetooth serial to communicate with the arduino. I have the script ready to make the rpi connect to the arduino at the right time but now I want to make sure the arduino only sends the data when the rpi is connected and waiting and ready to receive?

SurferTim
Posts: 817
Joined: Sat Sep 14, 2013 9:27 am
Location: Miramar Beach, Florida

Re: How to trigger data sent from Arduino

Mon Jun 19, 2017 1:31 am

Sounds like you should send a "send" byte to the Arduino, then the Arduino sends everything, and ends with a "finished" byte.

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Mon Jun 19, 2017 6:52 pm

Im currently using this sketch:

Code: Select all

    float flow = 500.06;
    void setup() {
      Serial.begin( 9600 );}
    void loop() {
        if (Serial.available()>0) {
            if (Serial.read() == 'R') {
                 Serial.print(flow)
                 Serial.write("\n");
            }
        }
    }
and Im using this python to read it:

Code: Select all

    #! /usr/bin/env python
    import serial
    from time import sleep
    ser = serial.Serial(port='/dev/serial0',parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=1)
    # Wait to read from Arduino
    while 1:
            try:
                    time.sleep(10)
                    ser.write("R")
                    myData = ser.readline()
                    print myData
            except KeyboardInterrupt:
                    exit()
This should make the raspberry send R to the arduino after 10 seconds of running the script. But I get blank lines in the raspberry terminal every ten seconds. I guess that is the print myData line, which is coming in blank. The arduino bluetooth led light is on, they are connected. What could be happening?
Last edited by marciokoko on Mon Jun 19, 2017 11:17 pm, edited 1 time in total.

gordon77
Posts: 2980
Joined: Sun Aug 05, 2012 3:12 pm

Re: How to trigger data sent from Arduino

Mon Jun 19, 2017 6:55 pm

Where have you set the pi baud rate?
Eg.
ser = serial.Serial(

port='/dev/serial0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Mon Jun 19, 2017 7:19 pm

ok, I set it, but Im still getting the same thing. I think the parity was hardcoded into the raspberry config files, but I added it like so:

Code: Select all

ser = serial.Serial(
        port='/dev/serial0',baudrate = 9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=1
        )

gordon77
Posts: 2980
Joined: Sun Aug 05, 2012 3:12 pm

Re: How to trigger data sent from Arduino

Mon Jun 19, 2017 7:49 pm

Is the problem you are sending a float?

If you try to send text instead of flow from the Arduino does it work?

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Mon Jun 19, 2017 8:16 pm

Same thing.

I just get a blank terminal with new lines:
Screen Shot 2017-06-19 at 2.15.41 PM.png
Screen Shot 2017-06-19 at 2.15.41 PM.png (12.88 KiB) Viewed 1204 times

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Mon Jun 19, 2017 10:43 pm

My most recent code is:

Code: Select all

float flow = 111.22;
void setup() {
  Serial.begin( 9600 );    // 9600 is the default baud rate for the serial Bluetooth module
}
void loop() {
  if (Serial.available()>0) {
    if (Serial.read() == '4') {
      Serial.write("text");
      Serial.write("\n");
    }
  }    
}
and:

Code: Select all

while 1:
        try:
                sleep(10)
                ser.write("4")
                myData = ser.readline()
                print myData
        except KeyboardInterrupt:
                exit()
When I upload the ino sketch to the arduino, if I type 4 in the serial monitor and hit send, I get "text" as expected. Then I connect the raspberry to the arduino and if I type anything in the arduino ide Serial Monitor, it shows up in the raspberry pi. So I know they are communicating. The issue is that the raspberry pi is sending the 4 every 10 seconds but the arduino response either isnt happening, or the arduino response isnt printing on the arduino.

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Mon Jun 19, 2017 11:16 pm

I also just tested these codes and it works as expected since the raspberry gets the "numberfour-print" text printed on the terminal every 3 seconds. So the arduino is properly connecting and sending data to raspberry:

Code: Select all

float flow = 111.22;
int n = 0;
void setup() {
  Serial.begin( 9600 );    // 9600 is the default baud rate for the serial Bluetooth module
}
void loop() {
      Serial.print("numberfour-print");
      Serial.write("\n");
}
and:

Code: Select all

while 1:
        try:
                sleep(3)
                myData = ser.readline()
                print myData
        except KeyboardInterrupt:
                exit()
So the question is, why doesnt the raspberry pi receive or print the data when the arduino sends it in the other scenario?

User avatar
DougieLawson
Posts: 29715
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website

Re: How to trigger data sent from Arduino

Mon Jun 19, 2017 11:27 pm

I've got this sketch loaded in my Arduino

Code: Select all

#include <SPI.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#include "Adafruit_MAX31855.h"
#define MAXCS   10
Adafruit_MAX31855 thermocouple(MAXCS);
String strRead;
String readCel;
String readFar;
double c;
double f;
int timeout;

LiquidCrystal_I2C  lcd(0x27, 2, 1, 0, 4, 5, 6, 7);

byte customChar[8] = {
  0b00111,
  0b00101,
  0b00111,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000
};

void setup()
{
  lcd.setBacklightPin(3, POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.begin(16, 2);
  lcd.createChar(0, customChar);
  lcd.clear();

  while (!Serial); // wait for Serial on Leonardo/Zero, etc
  readCel = String("ReadC");
  readFar = String("ReadF");
  Serial.begin(9600);
  Serial.println("MAX31855 test");
  lcd.setCursor(0, 0);
  lcd.print("MAX31855 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp
  //Serial.print("Internal Temp = ");

  strRead = Serial.readStringUntil('\r');
  // Serial.print("You entered: >");
  // Serial.print(strRead);
  // Serial.println("<");

  if (readCel == strRead) {
    timeout = 0;
    Serial.print(thermocouple.readInternal());
    c = thermocouple.readCelsius();
    while (isnan(c) && timeout < 255) {
      delay(1);
      c = thermocouple.readCelsius();
      timeout++;
    }
    Serial.print(' ');
    Serial.print(c);
    Serial.print(' ');
    Serial.println(timeout);
    lcd.setCursor(0, 0);
    lcd.print("Temp ");
    lcd.print(c); // nn.nn
    lcd.write((uint8_t)0);
    lcd.print("C     ");
  }
  if (readFar == strRead) {
    timeout = 0;
    Serial.print(thermocouple.readInternal());
    f = thermocouple.readFarenheit();
    while (isnan(f) && timeout < 255) {
      delay(1);
      f = thermocouple.readFarenheit();
      timeout++;
    }
    Serial.print(' ');
    Serial.print(f);
    Serial.print(' ');
    Serial.println(timeout);
    lcd.setCursor(0, 1);
    lcd.print("Temp ");
    lcd.print(f);
    lcd.write((uint8_t)0);
    lcd.print("F");
  }
  delay(100);
}
and this python program reads it

Code: Select all

#!/usr/bin/python

import serial, string, time, sys

output = " "
ser = serial.Serial('/dev/ttyUSB0', 9600, 8, 'N', 1, timeout=0)
CorF = "C"
ser.write(b'ReadF\r')

while True:
  while output != "":
    output = ser.readline()
    temp = output.split()
    try:
      print temp[0], temp[1]
    except:
      pass
  output = " "
  if CorF == "C":
    time.sleep(0.1)
    cmd = "ReadC\r"
    ser.write(cmd)
  if CorF == "F":
    time.sleep(0.1)
    cmd = "ReadF\r"
    ser.write(cmd)
#  if CorF == "F":
#    CorF = "C"
#  else:
#    CorF = "F"
  time.sleep(1)


The arduino program also displays the results from the max31855 sensor on an LCD so I know it's working.
Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

Since 2012: 1B*5, 2B*2, B+, A+, Zero*2, 3B*3

Please post ALL technical questions on the forum. Do not send private messages.

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Tue Jun 20, 2017 2:29 am

Ok so let me understand this, Arduino, relevant steps (imho):

1. Set readCel = "ReadC" - as some sort of flag
2. Set strRead to whatever comes in through the serial until \r
3. If "ReadC" came in through the serial (but ReadF is sent first), set c & print to the Serial, otherwise set f & print to the Serial.

Meanwhile on the rpi
1. slight difference is you have timeout on serial0 = 0 instead of my 1
2. you set output = blank
3. CorF=C - i dont understand the purpose
4. ser.write(b'ReadF\r') - i dont understand, just for default purposes you want to use F?
5. while output is not blank...put serial input into the output var...
6. split that serial input into array elements and print them
7. set output = blank - why, to break out of while loop?
8. if CorF=C, which it was set manually at the start...
9. Set cmd to ReadC & write that cmd to serial

I guess the most important differences are:
A. timeout=0
B. use of flags to trigger the serial0.

My sketch would be:

Code: Select all

float flow = 111.22;
String strRead;

void setup() {
  String readCel = String("ReadC");
  Serial.begin( 9600 );    // 9600 is the default baud rate for the serial Bluetooth module
}

void loop() {
  strRead = Serial.readStringUntil('\r');
  if (readCel == strRead) {
      Serial.print(flow);
      Serial.write("\n");
  }
This should cover 1-3 of your ino sketch. And for the rpi:

Code: Select all

#! /usr/bin/env python
import serial
from time import sleep
ser = serial.Serial(port='/dev/serial0', baudrate = 9600, parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=0)

output = " "
CorF = "C"
ser.write(b'ReadF\r')

while 1:
     while output != "":
              output = ser.readline()
              try:
                   print myData
              except:
                   pass
     output = " "
     if CorF == "C":
     time.sleep(0.1)
     cmd = "ReadC\r"
     ser.write(cmd)
time.sleep(1)

User avatar
DougieLawson
Posts: 29715
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website

Re: How to trigger data sent from Arduino

Tue Jun 20, 2017 6:11 am

I'm not going to write your code for you, just try it (that's how you learn). Put lots of

Code: Select all

Serial.println("stuff goes here");
calls in your Arduino sketch so you can see the flow through your programs.
Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

Since 2012: 1B*5, 2B*2, B+, A+, Zero*2, 3B*3

Please post ALL technical questions on the forum. Do not send private messages.

gordon77
Posts: 2980
Joined: Sun Aug 05, 2012 3:12 pm

Re: How to trigger data sent from Arduino

Tue Jun 20, 2017 7:32 am

If I connect my Pi to a Uno R3, via USB, and use your code in the Pi, with baudrate 9600 added and serial port changed to suit, it works and the Pi receives and prints 500.06 ever 10 seconds !

The Uno has your code in it

Code: Select all

#! /usr/bin/env python
import serial
import time
ser = serial.Serial(port='/dev/ttyACM0',baudrate = 9600,parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=1)
# Wait to read from Arduino
while 1:
   try:
       time.sleep(10)
       ser.write("R")
       myData = ser.readline()
       print myData
   except KeyboardInterrupt:
       exit()
The Uno has your code in it

Code: Select all

    float flow = 500.06;
    void setup() {
      Serial.begin( 9600 );}
    void loop() {
        if (Serial.available()>0) {
            if (Serial.read() == 'R') {
                 Serial.print(flow)
                 Serial.write("\n");
            }
        }
    }

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Tue Jun 20, 2017 12:19 pm

DougieLawson wrote:I'm not going to write your code for you, just try it (that's how you learn). Put lots of

Code: Select all

Serial.println("stuff goes here");
calls in your Arduino sketch so you can see the flow through your programs.
I wasn't asking for the code. I was simply trying to explain it out loud so you could correct me if I was wrong.

Here is my screencast of it:

https://youtu.be/RCN4rMneC5g

gordon77
Posts: 2980
Joined: Sun Aug 05, 2012 3:12 pm

Re: How to trigger data sent from Arduino

Tue Jun 20, 2017 1:57 pm

Which arduno are you using ? Could you connect them with USB, as I said in my earlier response and see if it works ?

Then maybe see why your original system didn't work ?

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Tue Jun 20, 2017 3:45 pm

Its one called Bluno Nano (https://www.dfrobot.com/product-1122.html).

Ill try it via usb when I get home but that is not what I need to do.

gordon77
Posts: 2980
Joined: Sun Aug 05, 2012 3:12 pm

Re: How to trigger data sent from Arduino

Tue Jun 20, 2017 4:20 pm

marciokoko wrote:Its one called Bluno Nano (https://www.dfrobot.com/product-1122.html).

Ill try it via usb when I get home but that is not what I need to do.
Understood, I thought it was somewhere to start to try and work it out.

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Tue Jun 20, 2017 5:20 pm

Gordon,
Thanks, I will try it and post back.

There is a guy on SO that got my original code working but I assume he also did it with the serial port connected via USB:
https://stackoverflow.com/questions/445 ... -bluetooth

Dougie,
Does your setup use a usb serial connection?

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Tue Jun 20, 2017 9:42 pm

Gordon, so do I just plug in the arduino's usb cable to the usb port on the rpi? wouldnt i need to change the python code to ttyusb or something?

gordon77
Posts: 2980
Joined: Sun Aug 05, 2012 3:12 pm

Re: How to trigger data sent from Arduino

Wed Jun 21, 2017 2:22 am

My uno shows as /dev/ttyACM0 your Nano maybe /dev/ttyUSB0

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Wed Jun 21, 2017 9:18 pm

Ok and the results are that I sort of got something. Im using this ino sketch:

Code: Select all

float flow = 111.22;
void setup() {
  Serial.begin(9600);    // 9600 is the default baud rate for the serial Bluetooth module
}
void loop() {
  if (Serial.available()>0) {
    Serial.print(Serial.read());
    if (Serial.read() == 'R') {
      Serial.print(flow);
      Serial.write("\n");
    }
  }    
}
with this python code:

Code: Select all

#! /usr/bin/env python

import serial
from time import sleep

ser = serial.Serial(
        port='/dev/ttyAMA0', baudrate = 9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=0
        )
while 1:
        try:
                sleep(3)
                ser.write("R")
                myData = ser.readline()
                print myData
        except KeyboardInterrupt:
                exit()
I uploaded the sketch to the bluno nano (just to make sure), I then went over to the pi and connected the bluno nano usb cable to the rpi2 usb port and then ran the python script. At first I got nothing, first two or three lines were empty. But then I got the number 82 in every successive line.
tty.jpg
tty.jpg (38.46 KiB) Viewed 801 times
I also took some screenshots of ls -l /dev and dmesg | grep tty both with the bluno plugged into the usb and then with the bluno connected to the rpi via the bluetooth serial module
The attachment tty.jpg is no longer available

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Thu Jun 22, 2017 12:29 am

I just confirmed that 82 is the ascii equivalent of the letter R. So this makes sense because I added this line:***

Code: Select all

void loop() {
  if (Serial.available()>0) {
    Serial.print(Serial.read());***
    if (Serial.read() == 'R') {
      Serial.print(flow);
      Serial.write("\n");
    }
  }    
}
which should be sending the R back to the rpi. So the Rpi is receiving it when connected to the usb serial. But why doesnt it receive it when sent over the bluetooth serial?

gordon77
Posts: 2980
Joined: Sun Aug 05, 2012 3:12 pm

Re: How to trigger data sent from Arduino

Thu Jun 22, 2017 4:19 am

Are you sure ttyAMA0 is correct? In terminal use ls /dev before you plug the USB in the pi, and then after plugging and check for a difference.

User avatar
marciokoko
Posts: 165
Joined: Sat Aug 27, 2016 4:33 pm

Re: How to trigger data sent from Arduino

Thu Jun 22, 2017 1:04 pm

Sorry, I meant ttyACM0. Here are the screenshots:
Screen-Shot-2017-06-22-at-6.51.56-AM.jpg
Screen-Shot-2017-06-22-at-6.51.56-AM.jpg (40.93 KiB) Viewed 733 times
and also I changed the python code to send an S to arduino and I get back 83 in the rpi. But only via serial over USB :-(
Screen-Shot-2017-06-22-at-6.45.41-AM.jpg
Screen-Shot-2017-06-22-at-6.45.41-AM.jpg (40.71 KiB) Viewed 733 times

User avatar
scruss
Posts: 1305
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: How to trigger data sent from Arduino

Thu Jun 22, 2017 2:44 pm

marciokoko wrote:… I only want to receive data once a day. The rpi is using bluetooth serial to communicate with the arduino. I have the script ready to make the rpi connect to the arduino at the right time but now I want to make sure the arduino only sends the data when the rpi is connected and waiting and ready to receive?
Note that on most Arduinos, opening a serial connection will cause the Arduino to reset. This will lose any accrued measurements for the day. Your bluetooth module might be different, but if you're doing serial logging, you need to keep the connection open all the time or data will be lost.

You don't have to explicitly read the data on the Raspberry Pi — serial data appears to stay in the Raspberry Pi's serial buffer indefinitely until read — but you do need to keep the connection open.
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.

Return to “Beginners”

Who is online

Users browsing this forum: Baidu [Spider], ericcooper, OutoftheBOTS and 20 guests