Add USB To Your Electronics Projects! - The USB Protocol Explained

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
every single Electronics project has some sort of output why else would we make them this output can mean the form of LEDs or LCD displays but what about interacting with a computer well the traditional method of doing so is via the serial port this is the most widely used because of the simplicity rewind a few decades and you will find many more computers with serial ports but if you have noticed these ports have been long since replaced by USB USB has brought massive advantages to the electronic space most notably for the consumer for them it is very easy to use just plug it in and the computer will handle the rest much more convenient than the traditional serial devices which had to be manually configured the only problem is that USB is very complicated considering that the data sheet is over 600 pages long for this reason implementing USB is no easy task for the engineer luckily for you you're in the right place and in this video I'll be showing you how you can Implement USB into your electronics projects the first and most logical step is to select a microcontroller that will interface to our computer using USB and it can't be any old microcontroller the infamous Mega 328 will not be suitable here instead I'm looking at a very similar microcontroller which is the atmega 16u2 why did I pick this microcontroller specifically well for a few reasons first it is extremely similar to the original AVR series such as the mega 328 that means you won't have to learn too many new skills just to use the USB second is that it is fairly available with it being in stock and Mouser with more to come later this year finally and perhaps the most important it has a hardware USB implementation some of you may have already come up with an objection with regards to the mega 328 which would be that we could use the V USB Library yes it is true that you can use such a software library to bitbang USB but for beginners I believe that it is best to stick to Hardware USBS who knows I may just upload a v USB video in the future as well if you don't want to use this microcontroller specifically you may pick up another just make sure that it has USB capability also be warned that this video may not align with it completely although the general ideas will be the same you will most likely make a prototype for your first project as well and in a lot of cases that is done on our breadboard or perf board with that in mind the first thing you may notice about this microcontroller is its size I mean it's smaller than my thumb what happens next really depends on how comfortable you are with smv soldering if you are comfortable then feel free to produce your own Dev board or solder it to an adapter board if you aren't comfortable then take a look at these adapters they're pretty huge but no surface mount soldering is required it also makes it really easy to swap the microcontroller in case you fry it anyways for the Assembly of the Prototype I set up the bare minimum components required to run the microcontroller along with a few buttons and LEDs for testing purposes these macro controllers require very few parts to function but there is one component that you will need to properly use USB and that is either an 8 megahertz or 16 megahertz Crystal this is because the USB Hardware requires a 48 megahertz clock in the internal PLL needs either an 8 or 16 megahertz clock to generate those 48 megahertz you will also need two 22 ohm resistors in series with the USB data lines anyways the circuit is really simple with a few extra parts go check the link in the description if you want a schematic that you can follow along with the next part is just running our prototype together I didn't bother to make a PCB for this case since I wanted to get to the software as quickly as possible I did end up using the solderless adapter though since this will make very useful drop in programmer down the line if I feel the need to feel free to make a PCB at this stage if you want or just Place everything else on the breadboard now for the part that you have all been waiting for the USB protocol this is also the hard part so buckle in to write code for USB you should probably understand how it works at a low level which I'll explain now if you are interested in the explanation and want to skip ahead feel free to do so anyways we will start at the lowest level of the protocol which is the bits themselves taking a look at the physical USB interface we have four connections one is power another is ground and the other two are D plus and D minus these aren't your typical data lines where one is a clock and the other is data rather USB uses what is called a differential pair it's called that because the data lines usually have inverted logic States from one another this is useful for eliminating noise which can be a big deal at the high speeds that it can reach but how can it use essentially just one signal to deliver so much data where does one bit end in the other bit begin well let's take a look first off I need to explain some relevant terminology there are four basic States j k a single ended zero and a single ended one J and K are opposites of each other and their polarities depend on whether you're running in low or full speed they also set D plus and D minus opposite each other as in D plus would be high and D minus would be low for J in a full speed mode and the opposite in low speed K is always the opposite of J this is how speed is determined by the computer as well the J state is the idle State and whichever polarity it is in will determine the speed of the communications there are two more levels which are a single ended zero and a single ended one they are exactly what they sound like either or both ones or both are zeros now these Levels by themselves do not represent the ones and zeros of the data however for that we use a special form of data transfer in the special form of data transfer is called the nrzi line coding it stands for non-return to zero inverted basically we are looking at the transitions between the JS and the K's to retrieve our data let me draw the lines in between the bits here if there are two JS or two k's in a row we see no transition then that means we'll get a 1 for our data in return but if there is a transition from a j to a k or inversely a k to a j we will get a zero for our data as you can see the JS and the K's themselves do not carry the data rather the transitions do this is also how the devices can recover some sort of data clock without having a dedicated clock pin that's also why the transfers always start with a kjkj KJ KKK sync pattern so that both sides get an idea of how fast the clock is but our problem arises if there are too many non-transitions in a row and the clock would be lost that's why the protocol requires some bit stuffing where a transition is forced after six consecutive non-transitions this transition does not count as part of the data and finally an end to the data is represented with a single ended zero that brings us up the chain into the next highest level of organization which is comprised of packets if you are familiar with internet communication this is sort of a similar idea each packet is a tiny bit of information put together into one sort of package the first part of every packet is the sync that we just talked about then comes the PID the pida basically tells us what the packet is about whether it is Data addressing or acknowledgments the PID is only four bits long and the other four bits of it are just a bit wise complements of the first four bits afterwards we may or may not have some more data depending on what the type of packet is but more on that in a second finally at the end of the packet we have an EOP which stands for end of packet each Erp is comprised of a couple of single-ended zeros in a j and this is the basic structure of every single package that we will talk about but with so many different types of data we need a way to organize these packets and there are actually three types of packets that you should be aware of the first type is a token packet these packets are only sent by the host so no devices are allowed to send these on their own they basically initiate communication these packets use four distinct pids out in setup and start a frame out and in our self-explanatory to indicate that the next packet will either be a host or device or device to host data transfer the setup is similar to an out but it has more to do with the device configuration out in and setup pids are all followed by seven bit device addresses in a 4-bit endpoint that means that each bus can have at most 127 devices attached and endpoints are device specific data locations that indicate different functions for the data being received but more on endpoints later the final PID and token packets are start of frames sofs sofs are not as important but they basically denote the timing of the USB they occur every 1 millisecond and no devices should respond to it they should only take note of it the next type of packet is the data packet day packets follow after a token packet and are either in the in or out Direction the PID of a data packet can either be a data 0 or a data 1. there's little real difference between the two pids other than the device must alternate between them on each consecutive data packet after the PID you'll find the actual data for full speed devices you can have up to 64 bytes per data packet but in low speed devices you are limited to just 8 bytes after the data there's a 16-bit CRC to ensure the correctness of the data and finally we have the handshake packet this is the smallest packet of three because it is literally just a PID the three pids are acknowledged not acknowledge installed acknowledge and not acknowledge our self-explanatory and that the device either receives the data correctly or is too busy to deal with it the stall is a little bit different because it means there is an outstanding error that needs to be resolved I organized the presentation of the previous three packets because I wanted you to see how they are all connected and the combination of the three packets in this order will get what is called a transaction the host initiates all transactions because remember the host is the only one who can issue a token packet they are also named after the token packet pids which are either in out or set up going further collections of the transactions are grouped into categories called transfers and there are four basic types of transfers control transfers are used for a command and Status operations that are initiated by The Host control transfers can be used for things like to get in device information when it is initially plugged in so that the host knows what to do with the new device I synchronous transfers are transfers that occur continuously and with time sensitivity for example audio applications where the sound data must be continuously streamed so that continuity is not broken in the sound that means that if an error occurs no attempt every transfer will occur so the timely continuity is preserved interrupt transfers are similar to asynchronous transfers in that they occur regularly the difference is that the data transmitted is small this means that it can be repeated to ensure full data delivery this is useful for applications like keyboards the final transfer type is the bulk transfer this is for large amounts of data that don't have to be transmitted quickly things like hard drives and mass storage devices will use bulk transfers if the host controls all data transfers on the bus you may be wondering how it differentiates between each transfer method well for that we have to look at device endpoints an endpoint on a device is sort of like a destination or an origin for certain data a keyboard might use endpoint 1 for the keys press for example each endpoint has to configure itself in a certain way such as which transfer type to use and whether data comes in or out of it endpoint0 is the only required endpoint and it must always be configured since it is also a control type endpoint data can go both in and out of it besides endpoint 0 full speed devices can have up to 15 extra endpoints low speed devices can only have two additional endpoints speaking of endpoint0 it is the end point that the host uses to initialize the communication with the device to set up the device the host will first give it a new address since every new device starts with address 0. once the device has received the new address further configuration can occur in the form of descriptors descriptors are exactly what they sound like they describe the device and its functions there's data for the manufacturer of the device what it can do and much more okay that was a lot of information on USB let's get to the fun part and actually implement it if you wanted to you could simply use the core USB peripheral in its registers but I do not recommend that simply for the reason that it can get very messy and very confusing that's why I recommend using some sort of library either the official microchip ASF USB Library or the open source luffa Library I'll leave a link to both in the description for this introductory example we will be creating a USB keyboard using the luffa Library this is the best project to learn USB with since the device logic is simple and you don't have to write any drivers for your PC to get started with it simply download the files to a directory I'd recommend copying the keyboard demo so that you have an example of what to work with first edit your make file in our case the MCU should be at the atmega 16u2 if you decided to use a 16 megahertz Crystal instead of an 8 megahertz one change the fcpu value to that and finally change the loofah path to where you have installed luffa since we are using the atmega 16u2 we do have to make some modifications to the code since it includes references to Port e so go through and remove all references to the joystick and buttons headers do the same with the LEDs since they heavily interfere with Port C which is what we are using we will instead write code to detect our own buttons and turn on the LEDs to do that head over to the Callback hid device create hid report function where if statements used to check the joystick and button code you can replace those with your own conditions I replacing the check for the four buttons on my prototype once we are done editing compile The Code by using make then upload the hex file using AVR dude like you normally would if you are still confused you can find my modified code in the description and already we can see it working the best part is that you can extend this however you want since this is USB you can add further functionality like a Serial port at the same type as the keyboard simply reference the demo projects that are titled with multiple names like keyboard mouse for example you can also write custom USB implementations if you would like but more on that in a future video there's so much more that can be done with this if you want to dive deeper or need to debug your program you can get more information on your USB devices if you're running Linux dmsg is great to see USB device status Wireshark can sniff the USB packets themselves and is available on Windows and Mac 2. well this video is getting rather long so I'll end it here I plan on making more USB related videos in the future anyways if you enjoyed this video and learned something new please consider subscribing so that you can see my other videos have a good one
Info
Channel: Sine Lab
Views: 449,912
Rating: undefined out of 5
Keywords: microcontroller, AVR, PORT, AVR-GCC, Arduino, Atmega328p, how to, registers, 8 bit, IO, I/O, explained, easy, quick, hands on, timer, CPU, hardware, clock, counter, 256, USB, serial, keyboard, LED, ATmega16u2
Id: HbQ6q3skZgw
Channel Id: undefined
Length: 15min 18sec (918 seconds)
Published: Wed Jan 25 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.