element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Arduino
  • Products
  • More
Arduino
Arduino Forum Serial comm between Arduino using Python.
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Arduino to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • State Verified Answer
  • Replies 3 replies
  • Subscribers 391 subscribers
  • Views 3006 views
  • Users 0 members are here
Related

Serial comm between Arduino using Python.

l!nk
l!nk over 8 years ago

Hi guys,

 

This is my first post. I apologize if it is not the right place for my post.

 

I bought an Arduino a couple of months ago. I had played with it enough with the basic tutorials online, turning on and off LEDs, reading data from sensors, shift registers, etc.

Now I want to make something useful with the Arduino and with what I learned. What I am trying to do is to read data from a sensor that is attached to the Arduino and stored the data in my computer ( in the future in a Raspberry Pi). That way I could ssh to my computer and plot the data and if it is required active a set of relays that I have.

 

I was able to make the communication with my computer and save the data using Python. But I found that the data have a lag. Apparently the communication is getting stored in a buffer and when I change the input it just receive the old data in the buffer. Any one have any idea on how to fix this? Below is the code.

 

The arduino just receive an input (command) from the computer to read the data from pin A0 and send it to the computer through the serial communication.

Arduino code:

int inByte = 0;
int lightSensor = 0;
void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB
  }
}

void loop() {
  if (Serial.available() > 0) //Waiting for request 
  {
       inByte = Serial.read();
       lightSensor = analogRead(A0);
       Serial.println(lightSensor);
  }
}

 

 

The python code send a signal every minute to the Arduino and wait for the arduino to respond with the data which is written into a file.

Python code:

#!/usr/bin/python
import serial as sl
import time
import datetime

ser = sl.Serial('/dev/tty.usbmodem1421',9600) 

flag = 1;
tflag = 0;

oldMinute=100000.;
bufsize=0;
while True: # Run loop indefinitely 
        ts = datetime.datetime.now();
        if (flag==1): %Open a new file every day
                datafile = open('./data_'+str(ts.year)+'_'+str(ts.month)+'_'+str(ts.day)+'.dat','w',bufsize);
                datafile.write('#time      light \n');
                old_Day=ts.day;
                flag=0;

        Minute = ts.minute/60.;
        Hour = ts.hour;
        timeout = Hour + Minute;

        MHP = ts.minute%1.; # Planning to change this line of code such that it writes every 5 or 10 minutes
        print MHP
        
        if (MHP < 1.e-5): # Write data to file every minute
                if(Minute!=oldMinute):
                        tflag = 1;
                        oldMinute=Minute;
        if( tflag == 1):
                ser.write(b'0') #Send data to arduino. Activate arduino read pin and write to serial
                if (ser.inWaiting()>0):
                        data1= ser.readline()
                        datafile.write(' '+str(timeout)+'\t'+str(data1))
                        tflag = 0;
                        print timeout
        time.sleep(10)
        if (ts.day != old_Day): # Close file after day is finished
                datafile.close();
                flag=1;

 

By the way, my programming skills are not that good, I though my self programming mainly for scientific computations. I know there is an unnecessary  if-condition (tflag) which I would later fix. If any of you have any idea on how I could improve the code it would be great.

 

Thanks for any help.

  • Sign in to reply
  • Cancel

Top Replies

  • l!nk
    l!nk over 8 years ago +1 verified
    I just figure out what was the problem. In the python code I sent a request to the arduino using the command ser.write(b '0'). Immediately after I check for the arduino response with an if condition like…
Parents
  • l!nk
    0 l!nk over 8 years ago

    I just figure out what was the problem.

     

    In the python code I sent a request to the arduino using the command ser.write(b'0'). Immediately after I check for the arduino response with an if condition like this if (ser.inWaiting()>0): to then write the data to the file. The thing is that obviously the computer and the arduino are not executing in sync which as the if condition statement is note instantly returned, the python code just wait again another minute to receive the data and receive the old data from the arduino. I added a while loop while (ser.inWaiting()<0): to wait for the arduino to return the data.

     

    Here is the python code:

     

    #!/usr/bin/python
    import serial as sl
    import time
    import datetime
    
    ser = sl.Serial('/dev/tty.usbmodem1421',9600) 
    
    flag = 1;
    tflag = 0;
    
    oldMinute=100000.;
    bufsize=0;
    while True: # Run loop indefinitely 
            ts = datetime.datetime.now();
            if (flag==1): %Open a new file every day
                    datafile = open('./data_'+str(ts.year)+'_'+str(ts.month)+'_'+str(ts.day)+'.dat','w',bufsize);
                    datafile.write('#time      light \n');
                    old_Day=ts.day;
                    flag=0;
    
            Minute = ts.minute/60.;
            Hour = ts.hour;
            timeout = Hour + Minute;
    
            MHP = ts.minute%1.; # Planning to change this line of code such that it writes every 5 or 10 minutes
            print MHP
            
            if (MHP < 1.e-5): # Write data to file every minute
                    if(Minute!=oldMinute):
                            tflag = 1;
                            oldMinute=Minute;
            if( tflag == 1):
                    ser.write(b'0') #Send data to arduino. Activate arduino read pin and write to serial
                    while (ser.inWaiting()<0): #Do while loop waiting for data 
                            time.sleep(0.1)
                    data1= ser.readline()
                    datafile.write(' '+str(timeout)+'\t'+str(data1))
                    tflag = 0;
                    print timeout
            time.sleep(10)
            if (ts.day != old_Day): # Close file after day is finished
                    datafile.close();
                    flag=1;

     

    Thanks for the help Mr Wong.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Reject Answer
    • Cancel
Reply
  • l!nk
    0 l!nk over 8 years ago

    I just figure out what was the problem.

     

    In the python code I sent a request to the arduino using the command ser.write(b'0'). Immediately after I check for the arduino response with an if condition like this if (ser.inWaiting()>0): to then write the data to the file. The thing is that obviously the computer and the arduino are not executing in sync which as the if condition statement is note instantly returned, the python code just wait again another minute to receive the data and receive the old data from the arduino. I added a while loop while (ser.inWaiting()<0): to wait for the arduino to return the data.

     

    Here is the python code:

     

    #!/usr/bin/python
    import serial as sl
    import time
    import datetime
    
    ser = sl.Serial('/dev/tty.usbmodem1421',9600) 
    
    flag = 1;
    tflag = 0;
    
    oldMinute=100000.;
    bufsize=0;
    while True: # Run loop indefinitely 
            ts = datetime.datetime.now();
            if (flag==1): %Open a new file every day
                    datafile = open('./data_'+str(ts.year)+'_'+str(ts.month)+'_'+str(ts.day)+'.dat','w',bufsize);
                    datafile.write('#time      light \n');
                    old_Day=ts.day;
                    flag=0;
    
            Minute = ts.minute/60.;
            Hour = ts.hour;
            timeout = Hour + Minute;
    
            MHP = ts.minute%1.; # Planning to change this line of code such that it writes every 5 or 10 minutes
            print MHP
            
            if (MHP < 1.e-5): # Write data to file every minute
                    if(Minute!=oldMinute):
                            tflag = 1;
                            oldMinute=Minute;
            if( tflag == 1):
                    ser.write(b'0') #Send data to arduino. Activate arduino read pin and write to serial
                    while (ser.inWaiting()<0): #Do while loop waiting for data 
                            time.sleep(0.1)
                    data1= ser.readline()
                    datafile.write(' '+str(timeout)+'\t'+str(data1))
                    tflag = 0;
                    print timeout
            time.sleep(10)
            if (ts.day != old_Day): # Close file after day is finished
                    datafile.close();
                    flag=1;

     

    Thanks for the help Mr Wong.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Reject Answer
    • Cancel
Children
No Data
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube