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.