Teensy 3.2 SD File Read Problem

Status
Not open for further replies.

costelljoe

New member
I have a file containing bytes where each set of 2 bytes represents an integer, which I copy over to the teensy sd card. I generated a sample file with c++ on computer:
Code:
#include <iostream>
#include <fstream>
using namespace std;

int main() {
	ofstream file;
	file.open("record.txt");

	const int n = 128;
	char buffer[n];

	for (int i=0; i<n; i+=2) {
		buffer[i] = i/2 & 0xFF;
		buffer[i+1] = i/2 >> 8;
	}

	file.write(buffer,n);
	file.close();
}

On my computer I can read back the values with:
Code:
file.read(buffer,n);

	for (int i=0; i<128; i+=2) {
		unsigned char lower = buffer[i];
		unsigned char upper = buffer[i+1];
		unsigned short value = (upper << 8) | lower;
		cout << value << endl;

	}


I am trying to get the teensy to read this file from the sd card, and simply print it through serial.
However, the output is just random values. Am I doing something wrong in the file reading or byte array?
What's going wrong?

Teensy code:
Code:
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>


void setup() {
  Serial.begin(9600);

  // Initialize the SD card
  if (!(SD.begin(4))) {
    // stop here if no SD card
    while (1) {
      Serial.println("Unable to access the SD card");
      delay(500);
    }
  }
}


void loop() {
  if (SD.exists("record.txt")) {
    // open file
    File audiofile = SD.open("record.txt", FILE_READ);

    // read one chunk of data
    byte buffer1[128];
    audioFile.read(buffer1, 128);

    // print over serial

    for (int i = 0; i < 128; i += 2) {
      unsigned char lower = buffer1[i];
      unsigned char upper = buffer1[i + 1];
      unsigned short value = (upper << 8) | lower;
      Serial.println(value);
    }
  } else {
    Serial.println("No audio data saved on teensy");
  }
}


I am getting serial output like this (I cut part of the output):
Code:
15962
0
4887
0
37900
8191
8224
0
0
0
32668
8192
65528
4095
7423
0
8192
0
37804
8191
2
0
7571
0
37804
 
You can't be getting any output from that code. It doesn't compile.
Once I'd fixed the bugs it works.
Code:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

Pete
 
Your problem may be that you are reading the data in the loop function and not closing the file. The second and subsequent times the loop function is executed, you open a file that is already open and then try to read from it.
I just moved your code from loop to setup so that it would only execute once - and added a audioFile.close().

Pete
 
Status
Not open for further replies.
Back
Top