0
I would really appreciate if anyone could give an advice or directions on how to start and stop data logging for accelerometer MPU6050 with a button press. So far I have a script that I start manually through raspberry pi os. So when I test the script it’s working and collecting data in the csv file with no problems. The only thing that I need, if I use accelerometer outside for testing, is to start data logging on a button press and to stop data logging when the button is pressed again. The code that I currently use is below.
thank you,
M
"""
Read Gyro and Accelerometer by Interfacing Raspberry Pi with MPU6050 using Python
http://www.electronicwings.com
"""
import os
import argparse
import datetime
from csv import DictWriter
# SMBus module of I2C
from time import sleep, time
import smbus
# MPU6050 Registers and their Address
DEVICE_ADDRESS = 0x68
# 0 for older version boards
BUS_NO = 1
PWR_MGMT_1 = 0x6B
SMPLRT_DIV = 0x19
CONFIG = 0x1A
GYRO_CONFIG = 0x1B
INT_ENABLE = 0x38
ADDRESS_MAP = {'gx': 0x43, 'gy': 0x45, 'gz': 0x47, 'ax': 0x3B, 'ay': 0x3D, 'az': 0x3F}
VALUE_NORMS = {'gx': 131., 'gy': 131., 'gz': 131., 'ax': 16384., 'ay': 16384., 'az': 16384.}
OUT_DIR = 'output'
def mpu_init():
# write to sample rate register
bus.write_byte_data(DEVICE_ADDRESS, SMPLRT_DIV, 7)
# write to power management register
bus.write_byte_data(DEVICE_ADDRESS, PWR_MGMT_1, 1)
# write to Configuration register
bus.write_byte_data(DEVICE_ADDRESS, CONFIG, 0)
# write to Gyro configuration register
bus.write_byte_data(DEVICE_ADDRESS, GYRO_CONFIG, 24)
# write to interrupt enable register
bus.write_byte_data(DEVICE_ADDRESS, INT_ENABLE, 1)
def read_raw_data(addr):
# accelerometer and gyro value are 16-bit
high = bus.read_byte_data(DEVICE_ADDRESS, addr)
low = bus.read_byte_data(DEVICE_ADDRESS, addr+1)
# concatenate higher and lower value
value = ((high << 8) | low)
# to get signed value from mpu6050
if value > 32768:
value = value - 65536
return value
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--filename', type=str, help='Name of the file to write data to')
parser.add_argument(
'--log', default=list(ADDRESS_MAP.keys()), nargs='+', choices=list(ADDRESS_MAP.keys()),
help='What parameters you would like to log from the MPU'
)
parser.add_argument('--hertz', type=int, default=100, help='Sampling rate from the MPU')
args = vars(parser.parse_args())
bus = smbus.SMBus(BUS_NO)
mpu_init()
if not os.path.isdir(OUT_DIR):
os.makedirs(OUT_DIR)
sleep_time = 1 / args['hertz']
if args['filename'] is not None:
output_path = os.path.join(OUT_DIR, f'{args["filename"]}.csv')
else:
output_path = os.path.join(OUT_DIR, f'{datetime.datetime.now().strftime("%Y%m%d_%H%M%S")}.csv')
log_keys = sorted(args['log'])
print(f'Outputting data to {output_path:s}')
print(f'Logging at a sampling rate of {args["hertz"]:d} Hz')
print(f'Logging: {log_keys}')
start = time()
with open(output_path, 'w', newline='') as fp:
csv_writer = DictWriter(fp, delimiter=',', fieldnames=log_keys + ['time(ms)'])
csv_writer.writeheader()
while True:
csv_writer.writerow({
**{key: f'{read_raw_data(ADDRESS_MAP[key]) / VALUE_NORMS[key]:.3f}' for key in log_keys},
**{'time(ms)': f'{(time() - start) * 1000:.1f}'}
})
sleep(sleep_time)
New contributor
-
Hi @Maksym Kepskyy, Welcome and nice to meet you. Ah, let me see. Can I “simplify” your specific question to a bit generic, like this? Suppose I have a “printing” program that repeatedly prints “Hello World” every second. Now I want to have another “master” “button” program which reads a button and starts or stops a “slave” program, perhaps the printing program. Now say, if I press button once, the printing starts, and if I press button again, printing stops. If you think my simplified, generic question solves your complicated, “accelero + csv” question, I can try to answer. Cheers. – tlfong01 5 hours ago
-
This seems to be a general programming question, i.e. not specific to the Pi. – joan 2 hours ago
Categories: Uncategorized