0

I am working on making a separate txt file with the output data from str(velocity). Currently it prints fine in the terminal but no success in printing it to a txt file.

import socket
import numpy as np
import pigpio
#------------------------Definingfunctions and variables ------------------#
pi = pigpio.pi()
pi.set_mode(21,pigpio.INPUT)
pulseDegrees = 2*np.pi/38
T_old = 0
count = 0
def cbf(g ,L ,t):
    T_new = t
    global velocity, T_old
    velocity = pulseDegrees/(T_new-T_old)*(1/0.000001)
    print(str(velocity))
    T_old = T_new

def sendData():
    conn.recv (1024)
    conn.send(str(velocity).encode('UTF-8'))
#--------------------------Communication--------------------#
# The units ipaddress
print ("Awaiting connection")
port=5555
s=socket.socket()
s.bind(('' ,port))

s.listen(1)
(conn,addr)=s.accept()
print ("Connected to " + str(addr))
#--------------------------Main loop--------------------#
cb = pi.callback(21,pigpio.RISING_EDGE, cbf)
while True:
    sendData ()-
khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

0

Use open(file, mode) with the pathname of a file as file and mode as "w" to open the file for writing. Call file. write(data) with data as the string formats "%s %d" followed by % and a tuple containing a string of the variable name, and the variable. Hope this works!

0

You can try

file = open("fileName.txt","w") 
file.write(str(velocity) + "\n") 
file.close()

"w" in line 1 means you are writing to the file. Adding "\n" means here is the end of the content.

Jiao Dian
  • 31
  • 5