Connect an SPI SD Card to Your Arduino - connection and coding

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
arduinos are great for project work but with only two kilobytes of ram and one kilobyte of e-squared prom there's nowhere to store information if you need images or want to log and retrieve data you need to add an sd card let me show you how hi and welcome to bytes and bits for simple control projects microcontroller boards like the arduino are ideal but if you need to store or retrieve larger blocks of data you simply can't fit it into small amounts of on-board storage so maybe you're using an lcd screen and you want to display an image maybe as a background for your control panel or maybe your arduino is doing some data logging and you want to store maybe some megabytes or gigabytes worth of information for later analysis either way round you're going to need some sort of large-scale persistent storage and sd cards are the ideal solution for this and they're remarkably easy to connect to your arduino project now in this project i'm going to be using an spi based sd card and mine comes built into my tft screen that i've been using in some other projects so a little sd card slot in here but everything we're going to do will work just as well for a standalone sd card board so let's get straight into it get the board connected and then get some software running connecting up our spi sd card is very much like any other spi device so this is our card reader here and again we have our normal spi connections on that so again um quite often your sd card reader will be working at 3.3 volt logic so you will need to use some sort of level shifting to bring down the 5 volts from the arduino to make it compatible with that so i'm using a little level shifter i see in this circuit or or you could use a little voltage divider but level shifter does actually make it a bit more reliable especially if you're connecting a number of devices and in a later video we're showing you how we can combine our our lcd screen our touch screen and our sd card to make a little sort of data logging system so um what's happening here then is we have our our level shifter so we have a 3.3 volt feed down on this side we have a 5 volt fade up on this side so we're just powering both sides of our level shifter i'm driving my sd card reader from 3.3 volts because that's a 3.3 volt one and again you need to check with the data sheet on your particular card reader as to what voltage supply it needs then we're using our spi signals so these three spi signals then coming from our arduino so pin 13 is our clock so that feeds through our level shifter onto the serial clock pin number 12 is our miso so our master input slave output so that should be coming into the arduino from all the way back down here from the data out from our sd card then pin number 11 is our mosi so this is the master out slave in so it's coming out of the arduino through our level shifter and then on the data input on our sd card and then the final connection we need then is um a a chip select signal so i'm using pin six on mine you can use whatever pin you want to be honest um so i'm just using pin six because that matches up with um when i add in my other spi devices so pin 6 coming out of the arduino through the level shifter then and on to the chip select on my sd card and this particular little sd card symbol here has an extra connection which is the card detect and that's just little switch that turns on and off to tell you when there is a little card plugged into the device but i'm not going to use that in this so we're just using our normal spi connections power and ground and of course then we need with our spi connections we need our chip select signal and just running that into any normal um i o port on the uno so looking at the actual devices i'm using on my circuit i'm using an 8 channel bi-directional level shifter and as shown on the screen there and i'll put some links in the description down below so you can have a look at these on amazon and so on and this really then has two voltages so the va side is the low voltage 3.3 volt side and vb is the 5 volt side and you can see there we've got a common ground and then this one has one other output which is the output enable this oe one and that lets you then turn on and off the signal so when you just need to connect that up to um the 3.3 volts then after that the a1 and the b1 they then match as the two sides of the level shifted circuit then for my sd card reader i'm using one that's built into my tft lcd screen and you can see there the connections on the left hand side so this one is being labeled with the actual sbi connections so we have my the the sd um cs is of course chip select then i have the mosi that is the data input to the sd card the miso plus master input slave output so that's the output from the sd card and then of course the sck which is the clock for this one before we can use the sd card in our arduino we need to make sure it's in the right file system so if we put it into our pc you should then be able to well on a windows machine i right click on that and select properties but you want to be able to go and see how that drive has been formatted so for mine here it's coming back reporting that i've got a usb drive in there which is my sd card and it is using the fat32 file system and that is exactly what we need now if if it's a brand new unformatted drive or if you've been using it somewhere else you'll need to reformat that so on the windows machine i would simply come in here and i would then go to format and then format that as my fat32 but again on whatever system you're using you'll need to work out how you get that formatted into this file system but once we've got that done we should have a nice clean sd card now to use in our arduino so now that we have the card formatted and ready to use we need to just make sure that we build up our circuit so again the circuit i've built up here is my full one with my lcd screen touch screen and the sd card so we have my sd card lead coming across and teaming up then with the common spi connections and of course its own individual chip select signal one of the things with the sd card and the arduino um if you are going to take it in or or take it out do make sure that you turn the power off these are quite prone to corrupting your card if you insert or remove them while it's actually powered up so turn your card off insert your card and then we can plug it back in and we are ready to now program this and get some data onto it so the software library that we're going to use is the built-in one from the arduino ide which then they do have this sd library now if you go to this web address you'll be able to get to this reference page and that tells you everything you need to know about how to use this class so if we scroll down here you'll see there's some information about the file systems it supports one of the important things here is that it supports these 8.3 file names and that really means that you have an eight character file name a full stop and then a three character extension okay so the file name can be anything up to eight characters it doesn't have to be eight characters and the file extension can be up to three characters but do make sure that that is what you buy if you try and make a file name which is longer than that it just simply won't work and it's sometimes hard to work out that you've just simply made a file name too long there's nothing actually wrong with your code the the second important things are that it uses your spi connection so you'll need to make sure that um you have your um that set up and we include the spi library when we're building our arduino sketch we also have to make sure that um we are aware that the was there's something called a working directory which in effect is any time you specify a file name or directory file name that is relative to the working directory and that working directory is always the root of the sd card so you can't actually move your working directory to one of the sub directories so every time you reference a file you have to reference it from the root directory and that that becomes important when we start putting files inside folders and so on but once you've got that idea of the the 8.3 file names the working directory always being the root and it working on spi and very much the whole thing just works using a very simple set of methods so we can see here that we have really two classes associated with this one is the sd class itself which lets us do sort of the more um overall and directory based commands where we can sort of um set up the sd card using the begin and then we can check for various things we can make directories remove files and so on and then we want when we want to actually open a file we will use a file class and then once we have that file class that in effect connects that object to that particular file and you can see we can then start reading the file and writing to the file and so on so let's start by putting together a simple little sketch so we'll start by including the two libraries that we need so our spi library and our sd card library i'm then defining a few constants which will tell us which pins we're using again you don't really have a choice here um the spi pins are whatever they happen to be on your board so i'm using an arduino uno so my clock my spi clock is on pin 13 the master and slave out 12 and the master out slave in on pin 11. pin number 10 on the arduino is the default chip select for the spi device but because i'm eventually going to be using this with a number of different devices i'm not using that for my sd card so i'm defining a chip select pin on number six then for my sd card now the at the arduino end you there's nothing really to say everything's happening obviously internally to the sd card so we're going to use the serial monitor to allow us to send some messages up for debugging so we can see exactly whether things have worked or not so i'm starting off then in my setup function by initializing my serial channel to the correct speed and again you can see i'm matching that down on my serial monitor down in this bottom right hand corner here to the same baud rate once we've done that it's always a very good idea if you have any spi devices to set their chip selects to the inactive state which which is high so i'm setting so you can see here i'm taking the um sd card c chip select pin setting as an output and driving it high and that basically disables that spi device so that as we are then setting up various other devices we're not having um one of them defaulting into an active state so it's going to be sort of interfering with um our other devices being set up so just it's just a good thing to do just set everything to inactive and then we know that as we initialize each individual device we're only talking to one device at a time so down here is where we actually start to um initiate it then so as soon as we include this sd.a file and that will instantiate an object variable so what's this is sd and that is an instance of this sd class which is the one which handles the overall running of the sd card so we have a function here called our method called begin which will actually initialize the card and the connection with our arduino sketch now that takes one parameter if if you leave out that parameter the sd card will use the default hardware chip select which as i said on the unit was pin number 10 and and that's fine if you've only got one device but we are here of course as i said we are specifically telling it i want you to use pin number six as the chip select for my sd card so calling sd dot begin with our chip select pin that will try to initialize a connection with the sd card so that function returns back a true or a false true means that our sd card has been found and we're now connected to it or false will tell us that something's gone wrong so i'm just catching here so i'm calling my function um if that returns back a false then we're simply going to output the sd card initializing initialization field and we're just going to trap the code in this little while loop else we're going to say that the sd card is okay and at that point we would go off in and do the other things so so to get this working i'm going to first of all try this by unplugging my sd card and we can then upload this sketch and see what happens so we can see there that our arduino has correctly identified then that the sd card isn't in the slot or there's something happened with the sd card so if i plug the sd card back in again and come back in here and reset it we should find then that our sd card is detected so we're now ready to go and start writing some files to that so let me just paste in a block of code just here okay so what we're going to do is we're going to create a text file write some information to it and then read it back in and send that contents back up to our serial channel so we've already got our sd card initialized so our sd object is now able to communicate with that so we need to create an instance of a file so we're just creating a new variable here so it's a file variable and we're creating that by calling the open method on the sd object so we give it a file name so remember that's got to be in this 8.3 format so up to eight characters and the actual file name full stop then up to three characters in the extension to be able to write to a file we have to open it with the file write permission at the end of that and that just simply then it what so what that does is if the file doesn't exist it will then create a new file and open it up so we can write to it if the file does exist as we'll see in a little bit that opens the file up for us to then append the file so we're saying then is if if that comes through okay then we're going to just send back up to serial channel that we have created the new file we're then going to send some information out to that file and again there's a number of ways in which we can do this and this is very very similar to the way that the serial channel works so you'll see that there is a print well if i come across to the class here so we're looking at the file class and you can see here we have our print our print line are read and are right and those are very work very similar to the way in which our serial channel works um so you should be familiar with how these how these work so we can just simply then say okay so we use my my file instance we are printing a line of text to that so that will print this is the first line of the file it will because i've used the print ln function that will then append onto that a new line character and at that point then we're just going to simply close the file so remember once you open a file it will stay open in the writing state until we then close the file and at that point the file is then completed it is important that you do get into the habit of closing so any files you open either for reading or for writing once you've finished doing your work on them it is important that you close those if your program does end without you having properly closed the file and that can cause a bit of corruption sometimes i think the arduino is quite good at making sure the files are closed but just it is good practice to always close the files before you go off and do something different so we've opened open a new file we've put some text inside it we've closed it we're then going to reopen the file this time but this time in the raid mode so once you're in read mode you cannot write to it which makes pretty much good sense so we're opening it up for writing we're then going to simply loop through it so we've got a loop here and we're using this method called available and that basically says are there so i've opened the file up and that's telling me are there still some characters available for me to read so if there are then i'm going to read in the next character so i've created a little sort of character variable here so we read in that character and i am just writing it out to my serial channel and once i've gone through and read all of the characters in the file i can then just simply close the file and that'll be the program finished now this read method it does return back actually a byte so we can either read that byte as a character or as we'll see in a second we can actually read it as an integer byte and again that lets us then do much lower level file handling so the moment we're dealing with text files um so reading it back as a character is fine and that will then make it easy for us to send that information back up to our serial channel what we'll do in a second is we'll switch that across into byte mode and we'll see we can actually read them as individual bytes but let's let's just do this one to begin with and see if that's all working so i'm going to send that down to the arduino and there we have the output from our serial terminal so we can see that it's picked up the card create the file out the first line and this last bit there is actually that line being read back out of the file now if i take that card and put it back into my pc and bring this across here we can see that we now have on my usb drive you can see that we have now got this myfile.txt and the first thing notice is that the file name is has been capitalized and that's what will happen with this uh filing system uh the actual file names are case insensitive so you can call them as we did in the file itself uh using lowercase um but that will relate to this file because it just simply assumes that everything is uppercase and if i try and open that file in my notepad let me just bring that across so you can see and there we have just confirm that we have created a text file which has got this is the first line of the file and it has got a new line character as you can see at the end of that line let me just close that down so for now i'm just going to delete that file and then just drop that back into my arduino so that's some basic file operations uh a couple of things to watch out for with this so let's let's just re-flash that uh arduino again so we know that we have a blank sd card and we're getting back then our reporting of it creating that file if i then just press the reset on the arduino to get that code to run a second time what we'll find on a third time and so on what we'll find is that this block of code here so this return here that is the actual contents of the file and you can see that we are gradually building up that line repeated over and over again and if you think about it what's happening is we're running the code where we're creating a file here and we're opening that file in file right mode and again the logic here is that if that file does not exist we open a brand new file but if that file does exist we will open it in write mode and our right cursor will be at the end of the file so in other words if we then start writing stuff to it we will simply be appending that onto the end of the existing file and that's exactly of course what's happening here and each time we reopen that file we then append a new line which is what we've seen on on this side over here so let's get around that then what we will do is when when our code first runs we're going to assume this is this is going to be some sort of data file that we're creating and that we want to make sure that this is the brand new data so we're going to start off by checking to see if that file does exist and if it does exist we're going to delete it so that when we come to this piece of code we will always be writing into a brand new clean file so i've just dropped in some code and basically we're saying here is we're using the again this sd object is the main control for sd card so we're saying using its exist method and then we're just giving it a file name so if this file exists then we're going to use the remove method to delete it and at that point we could then go off and at this point when we try to open that file of course the file doesn't exist anymore so we get a brand new clean file so let me just see um if that works okay so let's just make sure we save that and write that down to the arduino and there we go um okay let me just clear that out there so if i press the reset button we will get our code and we get one line in our file press it again and we get one line our file so now we have a brand new clean file being generated each time we run through our code so the last thing i want to have a look at with you is the use of folders for storing our files so i've added a bit of extra code into our file handling uh sketch so what we're doing is we're starting off as normal and getting the sd card up and running but now what we're going to do is we're going to create a folder called data into which we're going to be putting our results so our our code has to first of all check if that folder already exists so again we're using our sd object the exists method and then we're specifying a folder name now all for all file operations on our sd card have to be referenced from the root folder remember that idea of our working directory is always our root directory so any file names you give and any folder names you give must be referenced to that root directory so i have put in here slash data so that preceding slash is sort of implied because we always will be in the root directory but i always tend to put that in just so i know that i am referencing this from the root so that's just personal preference you don't actually need that in there so i'm saying does is there a folder in the root directory called data if there isn't then we need to make that directory so we have a make directories mkdir method on the sd object which lets us make that directory so when we pop out of this line here we will know that there is a folder called data in that root directory now um as we go through we'll see that there are different ways in which we can manage our files so i'm just pretending here that this sketch is going to create some data for some sort of experiment or whatever that we're running and as opposed to previously where we just simply deleted the previous data and then created new data what we're going to do here is keep all of the old ones um live on our sd card so that we are building up a a series of data runs and we're going to put each of the blocks of data so each of these myfile.txt files will go into its own folder and that's all we're doing here then and we can do the same process either with with folders or with files but the real idea is that we are generating a number we have got a base name for our folders so we're going to be in effect generating folders called slash data slash run one then we're the next time we run this code with generate a folder called slash data slash run two and so on so we have a little counter we're using this again be careful with the way in which you put or concatenate uh strings together so it's best to create a string variable which has your base file name and then we can concatenate easily against that um if you don't do if you just try to use that pure string in this area here you can sometimes get odd things happening but anyway um so we're doing a little while loop here so we're checking to see if a folder exists with the name of our base folder followed by this counter value so again as i said that will go slash data run one slash data slash run two and so on so as soon as we find a folder um name that doesn't exist we're going to log that folder name we're going to report that back up to our serial channel so we can see what's going on there and then we're going to make that folder so at this point we will have a folder which is slash data slash run and then whatever run this is as we're going forwards you can see that every time we now reference our file we have to put our folder name in front of it and again those are all referenced to that root directory so between our folder name and our file name we do have to put in that sort of trailing slash so all i'm doing here is before we go off and start using that i'm just adding a new trailing slash onto that string for run folder then after that everything else is as before just with this referencing the folder in front of my file name so this should let us then run this code a number of times and we will build up a a log of all the data that was created on each of the individual runs so let's upload that into the arduino and there we have our run starting and again i've obviously been doing a little bit of testing on here but if i now keep pressing my reset button you can see that each time i do that or our card runs again and we create the new folders for each of the individual data runs okay so if i then put that card back into my pc so there we have our drive open and you can see we have our data folder inside that we have a folder for each of our runs and if i look at my final run then we have our myfile.txt in there and if i open that again we can see that that one there was created on run number seven so that pretty much covers how we need to set up our sd card and then some basic file operations and folder management so do make sure you check out the project page on my website i'll put link in the description down below together with some links to the various bits of equipment that i'm using in this particular project going on from this then i'll be doing some more work with my system and the tft screen partly that will be in better handling of your files so we'll have a look at how we can both generate um csv files so there's some some actual spreadsheet files from our arduino so if we are taking sort of experimental results and so on we can log things like time readings and so on all as lines in a spreadsheet which can then be read straight into our excel on our pc how we can both then create those on our arduino and how we can then read those files back in on arduino and perhaps display those values as some data display on our tft screen i'll also be having a look at how we can use our our sd card then to store some images which we can display on our tft screen so again those are coming on on some subsequent videos after this one so if you are interested in that end of things do make sure you subscribe to the channel so you don't miss any of the videos and do turn your notification butt bell on and hopefully then i will see you soon in another video so bye for now for more games programming electronics projects and retro gaming please make sure you like this video subscribe to my youtube channel and visit my website
Info
Channel: Bytes N Bits
Views: 9,897
Rating: undefined out of 5
Keywords: arduino, sd card
Id: FI7yXDi-fKA
Channel Id: undefined
Length: 31min 23sec (1883 seconds)
Published: Sun Mar 28 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.