Read data from ATMEGA328P USB device

This article provides a step-by-step guide to building a program that tests data transfer between ATMEGA328P USB device and PC.


Note: if you prefer to test ATMEGA328P USB device without building the software yourself, you can download the precompiled program here instead.


🧩 Environment

Visual Studio (Windows)

📟 Programming language

C++

Building a Data Transfer Program for ATMEGA328P in Visual Studio

  1. Open Visual Studio software.
  2. Click File -> New -> Project
  3. Choose Visual C++ -> Win32 Console Application.
  4. Name your project as USB_Interface_AVR
  5. Click OK, followed by Next > and Finish to create the project.
Visual Studio New Project

The followings are the files needed for the project:

Solution Explorer

  1. Download and extract the archived file libusb-win32-bin-1.2.7.3.zip from sourceforce.
  2. Copy the file libusb.lib from the directory libusb-win32-bin-1.2.7.3\lib\msvc to your project folder USB_Interface_AVR\USB_Interface_AVR.
  3. Add libusb.lib to your Visual Studio project using Solution Explorer. Refer to the diagram above for its correct location.
  4. Navigate to libusb-win32-bin-1.2.7.3\include, and rename the header file lusb0_usb.h to usb.h.
  5. Copy renamed file usb.h to your project folder USB_Interface_AVR\USB_Interface_AVR.
  6. Import usb.h into your Visual Studio project using Solution Explorer. Its correct location is illustrated in the diagram above.

Copy the script below and paste it in USB_Interface_AVR.cpp.

WINUSB_Interface_AVR.cpp

C++
#include "stdafx.h"
#include "usb.h"
#include<stdio.h>
#include<Windows.h>
#pragma comment(lib,"libusb.lib")

#define MY_VID 0x16C0
#define MY_PID 0x05DC

void usb_init(void);
int usb_find_busses(void);
int usb_find_devices(void);
int usb_control_msg(usb_dev_handle *dev, int requesttype, int request, int value, int index, char *bytes, int size, int timeout);
usb_dev_handle *open_dev(void);
char a[4]={0};

usb_dev_handle *open_dev(void)
{
	struct usb_bus *bus;
	struct usb_device *dev;

	for(bus = usb_get_busses();bus;bus = bus->next)
	{
		for(dev = bus->devices;dev;dev=dev->next)
		{
			if(dev->descriptor.idVendor == MY_VID && dev->descriptor.idProduct == MY_PID)
			{
				return usb_open(dev);
			}
		}
	}
	return NULL;
}

void _tmain(int argc, _TCHAR* argv[])
{
	usb_dev_handle *dev = NULL;
	void usb_init(void);
	usb_find_busses();
	usb_find_devices();
	dev = open_dev();
	printf("a=%d %d %d %d\n", a[0], a[1], a[2], a[3]);

	if(dev)
	{
		char *addr;
		addr = a;
		usb_control_msg(dev, 0xc0, 0x3c, 0, 0, addr,4,5000);
		usb_close(dev);
		printf("a=%d %d %d %d\n", a[0], a[1], a[2], a[3]);
	}
	else
	{
		printf("No USB device found!\n");
	}
	system("PAUSE");
}

Connect ATMEGA328P USB device to your PC via a USB cable. Then, click green play icon to build and run the program.

Build_And_Debug
Green Play Icon

You’ll see the output as shown in the diagram below.

AVR_Output