How to fast read and write data to file?

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
skylin008
Posts: 88
Joined: Wed Mar 11, 2015 6:21 am

How to fast read and write data to file?

Post by skylin008 » Thu Nov 15, 2018 9:59 am

Hello everyone. I had a pyboard with stm32f405 chip. I want to read data from SPI port and write to flash with file. I found it every slowly as below code.How to solve with it ? Thanks !

Code: Select all

import pyb
import time
from pyb import Timer
from pyb import Pin
from time import sleep_us
from time import sleep_ms
from time import sleep
from machine import Pin
from machine import SPI

import uio

# spi pin
spi_ss   = 'Y5'
spi_sck  = 'Y6'
spi_mosi = 'Y8'
spi_miso = 'Y7'

# switch pin define
switch = pyb.Switch()

# led pin define
red_led    = pyb.LED(1)
green_led  = pyb.LED(2)
orange_led = pyb.LED(3)
blue_led   = pyb.LED(4)

all_leds = (red_led, green_led, orange_led, blue_led)

pcm_sync = Pin('X1', Pin.OUT_PP)
pcm_sync.low()

sleep_ms(10)

def sync_out(timer):	
	pcm_sync.high()
	sleep_us(10)
	pcm_sync.low()

sample_amount = 2048

class SpiControl:

	def __init__(self):
		self.spi = SPI(2, baudrate = 2048000, firstbit = SPI.MSB, polarity = 0, phase = 0)
		self.ss = Pin(spi_ss, Pin.OUT_PP)
		"""
		self.dummybuf = bytearray(1)
		for i in range(1):
			self.dummybuf = 0xff
		"""

	def read(self):
		response = bytearray(1)
		self.ss.low()
		self.spi.read(1)
		self.ss.high()

		return bytes(response)

spic = SpiControl()

data_buffer = [[] for i in range(sample_amount)]


start_flag = 0

while True:
	print("Programme Start!")	
	sleep (1)	
	if switch.value():
		print("Key Pressed!\r\n")
		tim = Timer(2, freq = 8000)
		tim.callback(sync_out)
		start_flag =1

	if (start_flag):

		print("START2!\r\n")	

		if (spic.read())!= 0xff:
			for loop_value in range(sample_amount):
				data = spic.read()
				data_buffer[loop_value] = '{},'.format(data)
				

		with open('pcm.dat', 'wb') as pcm:
			
			for each_data_value in data_buffer:
				pcm.write(each_data_value)

OutoftheBOTS_
Posts: 847
Joined: Mon Nov 20, 2017 10:18 am

Re: How to fast read and write data to file?

Post by OutoftheBOTS_ » Thu Nov 15, 2018 10:33 am

You are doing it in a very slow way.

You are just reading 1 byte at a time then your also writing 1 byte at a time. It takes much longer to start up the read or start up the write then to do the reading or writing.

You should be able to do it all in 1 hit something like this

Code: Select all

spi = SPI(2, baudrate = 2048000, firstbit = SPI.MSB, polarity = 0, phase = 0)
buff = bytearray(sample_amount)
spi.read(buff)
with open('pcm.dat', 'wb') as pcm:
	pcm.write(buff)

skylin008
Posts: 88
Joined: Wed Mar 11, 2015 6:21 am

Re: How to fast read and write data to file?

Post by skylin008 » Fri Nov 16, 2018 1:51 am

@OutoftheBOTS_ Thanks ,I will be try.

Post Reply