Read Data ST25DV - nfc

I made my own board with an STM32L031K6 and an ST25DV64K NFC chip. I am using the android App "NFC Tools". I can read the UID of the NFC chip with the app, so the antenna is correctly tuned. I can also read the UID with the microcontroleur via the I2C bus. When I write into the eeprom memory of the NFC chip with the microcontroleur, I can't read the data with the NFC app. It says that the tag is empty. I think I am missing a configuration, but I can't find which one.
Here is my code, executed once:
uint8_t ToWrite = 15;
uint8_t Password[17] = {0}; //Default password is"00000000"
Password[8] = 0x09; //Validation Code
// ST25DV_Address_E21 0x57 << 1; // Device select code= 0b1010111 ; E2 = 1
Password_Address = 0x900
HAL_I2C_Mem_Write(&hi2c1, ST25DV_Address_E21, Password_Address, 2, Password, 17, 0xFFF);
HAL_Delay(200);
//Read the UID
HAL_I2C_Mem_Read(&hi2c1, ST25DV_Address_E21, 0x18, 2, UID_Read, 8, 0xFFF); // This line works, UID displayed in the app and in the debugger are the same
HAL_Delay(500);
//Write some data in the eepprom memory (first address: 0x00)
for(int i = 0; i< 250; i++)
{
ToWrite++;
HAL_I2C_Mem_Write(&hi2c1,ST25DV_Address_E21, i, 2, &ToWrite, 1, 0xFF);
}

When you are writing the data in the EEPROM from address/block 0, you are simply overwriting the capability container values with all zeros. The correct way to do is initialize your tag, then write the data from block 4 and onwards.
The CC values look something like this:
0xE1, /* (block 0) */
0x40, /* (block 1) */
0x40, /* (block 2) */
0x05 /* (block 3) */
Followed by other key header values depending on the NDEF message type. Here I am illustrating for NDEF TEXT:
0x03, /*(block 4) NDEF message type (block 4) */
0x0D, /*(block 5) NDEF message length (blobk 5) eg, 13 byte message starting from here */
0xD1, /*(block 6) NDEF Record header: MB = 1, ME = 1, CF = 0, SR = 1, IL = 0, TNF = 001 > 0xD1 */
0x01, /*(block 7) Type length */
0x09, /*(block 8) Payload length = 9 (from language code) */
0x54, /*(block 9) Msg Type = Text */
0x02, /*(block 10) Language code size */
0x65, /*(block 11) Language = English, 'e', */
0x6E, /*(block 12) 'n', */
'A', /*(block 13+)Payload data */
'B',
'C',
'D',
'E',
'F'
A good reading resource to understand the NDEF payload format is here.
Hope this helps!

Related

Problem in Flash Programming of PIC24FJ128GC006

I am making a USB Bootloader for PIC24FJ. I am now in the process of writing to flash memory the application code hex file through a software and without using ICD3. After downloading the application code hex file, I checked the program memory of the PIC using the PIC Memory Views of MPLAB Window Toolbar, and this is what it looks like. PIC24_BOOT_APP_VECTOR_AREA As you can see in the picture, the opcode is not continuously written in every address. It alternates with 000000.
Also I compared the opcodes of the downloaded app code using the bootloader, to the application code without using the bootloader. I have found out that there are data in the opcodes that are not present in the application alone. Attached are the photos. Application_Code_Alone_User_Area, PIC24_Boot_App_User_Area This may create a problem in jumping to the application.
Below is my code for storing data in the buffer and writing to flash memory. (I use single word programming for flash)
#define WRITE_FLASH_BLOCK_SIZE 0x04
#define USER_MEM_START_ADDRESS 0x004002
unsigned long rxBuff[60];
int rxIndexer;
int xfer;
lineStart = rxBuff[ 0 ];
positionAddress = (rxBuff[ 2 ] << 8) + (rxBuff[ 3 ]); // THIS IS THE ADDRESS WHERE THE DATA SHOULD BE ADDRESSED
numberOfData = rxBuff[ 1 ]; // THIS IS THE TOTAL NUMBER OF DATA RECEIVED IN THE STREAM
recordType = rxBuff[ 4 ];
rxIndexer = 5; //Start of data index in a INTEL Hex file format
for(xfer = 0; xfer < numberOfData; xfer += WRITE_FLASH_BLOCK_SIZE) // THIS SECTION CONTAINS THE PROCESS OF COMBINING THE INFORMATION
{ // FROM THE DATA STREAM TO THIS FORMAT - 0x00AA, 0xBBCC
rxBuff[rxIndexer] = ((rxBuff[START_OF_DATA_INDEX + xfer]) &0x00FF);
rxBuff[rxIndexer] |= ((rxBuff[START_OF_DATA_INDEX + xfer + 1] << 8) &0xFF00); //end of lower word
rxIndexer++;
rxBuff[rxIndexer] = ((rxBuff[START_OF_DATA_INDEX + xfer + 2]) &0x00FF); //start of upper byte
rxBuff[rxIndexer] |= ((0x00 << 8) & 0xFF00); // phantom byte (0x00)
rxIndexer++;
}
if(lineStart == ':')
{
if(recordType == 0x00 && data_checksum == 0)
{
for(xfer = 0; xfer < numberOfData; xfer += 2)
{
FlashWrite_Word(programAddress + positionAddress, rxBuff[5 + xfer], rxBuff[5 + xfer + 1]);
positionAddress += 2;
}
}
else if(recordType == 0x04 && data_checksum == 0)
{
programAddress = USER_MEM_START_ADDRESS;
}
else if( recordType == END_OF_FILE_RECORD)
{
jumpTo_App();
}

AM2320 Sensor: CRCs doesn't match, CRC from sensor(0)

Note: Code is cross-compiled in windows 10.
Code:
package main
import (
"fmt"
"io"
"log"
"net/http"
aosong "github.com/d2r2/go-aosong"
i2c "github.com/d2r2/go-i2c"
)
const i2CAddress = 0x5c
const i2CBus = 1
// Server struct
type Server struct {
Sensor *aosong.Sensor
I2C *i2c.I2C
}
func main() {
var err error
s := Server{Sensor: aosong.NewSensor(aosong.AM2320)}
s.I2C, err = i2c.NewI2C(i2CAddress, i2CBus)
if err != nil {
log.Printf(err.Error())
}
fmt.Println(s.Sensor.ReadRelativeHumidityAndTemperature(s.I2C))
defer s.I2C.Close()
}
Debug info:
2019-02-12T10:29:19.692 [ i2c] DEBUG Write 3 hex bytes: [030004]
2019-02-12T10:29:19.697 [ i2c] DEBUG Read 8 hex bytes: [0304012500d92045]
2019-02-12T10:29:19.698 [ i2c] DEBUG Read 8 hex bytes: [0000000000000000]
CRCs doesn't match: CRC from sensor(0) != calculated CRC(6912).
Any ideea why the CRC from sensor is 0?
I am able to read the sensor on the same bus with the same address with a python script.
#!/usr/bin/python
import posix
from fcntl import ioctl
import time
class AM2320:
I2C_ADDR = 0x5c
I2C_SLAVE = 0x0703
def __init__(self, i2cbus = 1):
self._i2cbus = i2cbus
#staticmethod
def _calc_crc16(data):
crc = 0xFFFF
for x in data:
crc = crc ^ x
for bit in range(0, 8):
if (crc & 0x0001) == 0x0001:
crc >>= 1
crc ^= 0xA001
else:
crc >>= 1
return crc
#staticmethod
def _combine_bytes(msb, lsb):
return msb << 8 | lsb
def readSensor(self):
fd = posix.open("/dev/i2c-%d" % self._i2cbus, posix.O_RDWR)
ioctl(fd, self.I2C_SLAVE, self.I2C_ADDR)
# wake AM2320 up, goes to sleep to not warm up and affect the humidity sensor
# This write will fail as AM2320 won't ACK this write
try:
posix.write(fd, b'\0x00')
except:
pass
time.sleep(0.001) #Wait at least 0.8ms, at most 3ms
# write at addr 0x03, start reg = 0x00, num regs = 0x04 */
posix.write(fd, b'\x03\x00\x04')
time.sleep(0.0016) #Wait at least 1.5ms for result
# Read out 8 bytes of result data
# Byte 0: Should be Modbus function code 0x03
# Byte 1: Should be number of registers to read (0x04)
# Byte 2: Humidity msb
# Byte 3: Humidity lsb
# Byte 4: Temperature msb
# Byte 5: Temperature lsb
# Byte 6: CRC lsb byte
# Byte 7: CRC msb byte
data = bytearray(posix.read(fd, 8))
# Check data[0] and data[1]
if data[0] != 0x03 or data[1] != 0x04:
raise Exception("First two read bytes are a mismatch")
# CRC check
if self._calc_crc16(data[0:6]) != self._combine_bytes(data[7], data[6]):
raise Exception("CRC failed")
# Temperature resolution is 16Bit,
# temperature highest bit (Bit15) is equal to 1 indicates a
# negative temperature, the temperature highest bit (Bit15)
# is equal to 0 indicates a positive temperature;
# temperature in addition to the most significant bit (Bit14 ~ Bit0)
# indicates the temperature sensor string value.
# Temperature sensor value is a string of 10 times the
# actual temperature value.
temp = self._combine_bytes(data[4], data[5])
if temp & 0x8000:
temp = -(temp & 0x7FFF)
temp /= 10.0
humi = self._combine_bytes(data[2], data[3]) / 10.0
return (temp, humi)
am2320 = AM2320(1)
(t,h) = am2320.readSensor()
print t, h
Seems there was an issue with the library itself which was making two reads, but because the read code was not sent the values came as 0, as it can be seen in the logs:
2019-02-12T10:29:19.692 [ i2c] DEBUG Write 3 hex bytes: [030004]
2019-02-12T10:29:19.697 [ i2c] DEBUG Read 8 hex bytes: [0304012500d92045] (first read that was ignored)
2019-02-12T10:29:19.698 [ i2c] DEBUG Read 8 hex bytes: [0000000000000000] (second one that came a 0)
CRCs doesn't match: CRC from sensor(0) != calculated CRC(6912)
Made a PR to fix the issue: https://github.com/d2r2/go-aosong/pull/3

24bit USB Sample Rate Support

My question is quite similar to this question: Link, but i am not allowed to comment.
I'm implementing a PIC32 as a soundcard, and i now have a working USB audio stream, supporting 16-bit at 32kHz and 48kHz sample rates. I now want to change the bit depth to 24-bit, so i change my USB Descriptors to:
bSubFrameSize = 0x03, // 3 bytes per sample
bBitResolution = 0x18, // 24-bit resolution
When i do this, he bit resolution is changed as it is suppose to, but in the properties of the microphone, the dropdown menu where i could change the sampling frequency is grey.
I havn't changed anything in the endpoint descriptors, where both 32kHz and 48kHz still is supported.
My USB topology has 1 Audio control interface with a couple of Units, and 2 Audio Streaming Interfaces, for streaming IN and OUT.
Marc O answered his question by saying that something in his Input Terminal, i have tried changing wChannelConfig but i doesn't work.
I have tried Uninstalling and Installing the device drivers, but doesn't work.
What more do i need to change in the descriptors, to be able to select the sampling Frequency?
Thanks :)
Edit: Added Descriptor code and descriped progress
When i changed the no of channels to 2, and made the wChannelConfig = 0x03 -> right + Left Front, i saw the the field on he picture change to: "2 channel, 24 bit, 48000 Hz (Studio Quality)", but it still didn't make the dropdown menu white, and i couldn't change sample rate.
Below i've added the Audio funcion descriptors:
//CD
0x09, // Size : 9 Bytes
USB_DESCRIPTOR_CONFIGURATION, // Configuration Descriptor (0x02)
0x10, // Total length in bytes of data returned
0x01, // 2. Byte af Total Length
0x05, // Number of Interfaces: 5 3 Audio + 2 Comm
0x01, // Configuration Value, Value to use as an argument to select this configuration
0x00, // iConfiguration, Index of String Descriptor describing this configuration
_DEFAULT | _SELF, // bmAttributes, selfpowered
0xFA, // Maximum Power : 250 mA
// ######## Audio Control Interface Descriptor
//ID - Interface Descriptor
0x09, // Size : 9 Bytes
USB_DESCRIPTOR_INTERFACE, // Interface Descriptor (0x04)
0x00, // Number of Interface: Interface nr 0
0x00, // Value used to select alternative setting
0x00, // Number of Endpoints used for this interface, 0
AUDIO_DEVICE, // Class Code (Assigned by USB Org), AUDIO
AUDIOCONTROL, // Subclass Code (Assigned by USB Org), AUDIOCONTROL
0x00, // Protocol Code (Assigned by USB Org)
0x00, // Index of String Descriptor Describing this interface
// HEADER
0x0A, // Size : 10 Bytes
CS_INTERFACE, // CS_INTERFACE Descriptor Type
HEADER, // HEADER descriptor subtype
0x00,0x01, // Audio Device compliant to the USB Audio specification version 1.00
0x46,0x00, // 64 bytes - Total number of bytes returned for the class-specific AudioControl interface descriptor. // Includes the combined length of this descriptor header and all Unit and Terminal descriptors.
0x02, // bInCollection -> Number of streaming interfaces = 2
0x01, // en form for index: "AudioStreaming interface 1 belongs to this AudioControl interface."
0x02, // beskriver nok streaming interface 2's index
// INPUT_TERMINAL ID = 1 USB Stream
0x0B, // size : 12 bytes
CS_INTERFACE, // CS_INTERFACE Descriptor Type
INPUT_TERMINAL, // INPUT_TERMINAL - Descriptor subtype = 2
INPUT_TER_USB, // ID of this Input Terminal. // Constant uniquely identifying the Terminal within the audio function.
USB_STREAMING, // wTerminalType -> 0x0101 = USB streamming
0x00, // bAssocTerminal -> 0x00 = No association.
0x02, // bNrChannels -> 0x01 two channel.
0x03, // wChannelConfig -> 0x03 = right + Left Front
0x00, // iChannelNames -> 0x00 = Unused.
0x00, // iTerminal -> 0x00 = Unused.
// INPUT_TERMINAL ID = 4 MICROPHONE
0x0B, // size : 12 bytes
CS_INTERFACE, // CS_INTERFACE Descriptor Type
INPUT_TERMINAL, // INPUT_TERMINAL - Descriptor subtype
INPUT_TER_MIC, // bTerminalID -> ID of this Input Terminal = 4
MICROPHONE, // wTerminalType -> 0x0201 = Microphone
0x00, // bAssocTerminal -> 0x00 = No association.
0x02, // bNrChannels -> 0x01 one channel.
0x03, // wChannelConfig -> 0x03 = right + Left Front
0x00, // iChannelNames -> 0x00 = Unused.
0x00, // iTerminal -> 0x00 = Unused.
// OUTPUT_TERMINAL ID = 3 SPEAKER
0x09, // size : 9 Bytes
CS_INTERFACE, // CS_INTERFACE Descriptor Type
OUTPUT_TERMINAL, // OUTPUT_TERMINAL - Descriptor subtype
OUTPUT_TER_SPEAK, // bTerminalID -> ID of this Output Terminal = 3
SPEAKER, // wTerminalType -> 0x0301 = Speaker
0x00, // bAssocTerminal -> 0x00 = Unused
FEATURE_OUT, // bSourceID -> 0x02 = From Input Terminal ID 2 = USB stream
0x00, // iTerminal -> 0x00 = Unused.
// OUTPUT_TERMINAL ID = 6 USB Stream
0x09, // Size : 9 Bytes
CS_INTERFACE, // CS_INTERFACE Descriptor Type
OUTPUT_TERMINAL, // OUTPUT_TERMINAL - Descriptor subtype
OUTPUT_TER_USB, // bTerminalID -> ID of this Output Terminal = 6
USB_STREAMING, // wTerminalType -> 0x0101 = USB streaming
0x00, // bAssocTerminal -> 0x00 = Unused
FEATURE_IN, // bSourceID -> 0x05 = Feature Unit that sets IN features SOURCE = 5 (Feature_IN)
0x00, // iTerminal -> 0x00 = Unused.
// FEATURE_UNIT ID = 2
0x0A, // Size : 10 Bytes
CS_INTERFACE, // CS_INTERFACE Descriptor Type
FEATURE_UNIT, // FEATURE_UNIT - Descriptor subtype
FEATURE_OUT, // bUnitID -> ID 2
INPUT_TER_USB, // bSourceID -> 0x01 = connected to Input Terminal 1 SOURCE = 1 (Input USB)
0x01, // bControlSize -> 0x01 = 1 Byte
0x03, // bmaControls(n = channel nr) -> 0x03 = Mute + volume
0x03, // bmaControls(n = channel nr) -> 0x03 = Mute + volume
0x00, // bmaControls(n = channel nr) -> 0x00 = no master control
0x00, // iFeature -> string Descriptor Unused
// FEATURE_UNIT ID = 5
0x0A, // Size : 9 Bytes
CS_INTERFACE, // CS_INTERFACE Descriptor Type
FEATURE_UNIT, // FEATURE_UNIT - Descriptor subtype
FEATURE_IN, // bUnitID -> ID 5
INPUT_TER_MIC, // bSourceID -> 0x04 = Connected to Unit ID 4 SOURCE = 4 (Input Mic.)
0x01, // bControlSize -> 0x01 = 1 Byte
0x03, // bmaControls(1) -> 0b0000011 = Mute + Volume no. of Channels +1 = no. of bmaControls
0x03, // bmaControls(2) -> 0b0000011 = Mute + Volume no. of Channels +1 = no. of bmaControls
0x00, // bmaControls(3) -> 0x00 = No controls supperted no. of Channels +1 = no. of bmaControls
0x00, // iFeature -> string Descriptor Unused
// ######## AUDIO STREAM INTERFACE 1 OUT SPEAKER
//ID // Alternate Setting 0 - 0 endpoint
0x09, // Size : 9 Bytes
USB_DESCRIPTOR_INTERFACE, // Interface Descriptor (0x04)
0x01, // bInterfaceNumber -> 0x01 Interface ID = 1
0x00, // bAlternateSetting -> 0x00 = index of this interface's alternate setting
0x00, // bNumEndpoints -> 0x00 = 0 Endpoints to this interface
AUDIO_DEVICE, // bInterfaceClass -> 0x01 = Audio Interface
AUDIOSTREAMING, // bInterfaceSubclass -> 0x02 = AUDIO_STREAMING
0x00, // bInterfaceProtocol -> 0x00 = Unused
0x00, // iInterface -> 0x00 = Unused
//ID // Alternate Setting 1 - 1 endpoint
0x09, // Size : 9 Bytes
USB_DESCRIPTOR_INTERFACE, // Interface Descriptor (0x04)
0x01, // bInterfaceNumber -> 0x01 Interface ID = 1
0x01, // bAlternateSetting -> 0x01 = index of this interface's alternate setting
0x01, // bNumEndpoints -> 0x01 = 1 Endpoints to this interface
0x01, // bInterfaceClass -> 0x01 = Audio Interface
0x02, // bInterfaceSubclass -> 0x02 = AUDIO_STREAMING
0x00, // bInterfaceProtocol -> 0x00 = Unused
0x00, // iInterface -> 0x00 = Unused
// ASID GENERAL
0x07, // Size : 7 Bytes
CS_INTERFACE, // CS_INTERFACE Descriptor Type
AS_GENERAL, // bDescriptorSubtype -> 0x01 = GENERAL subtype
0x01, // bTerminalLink -> 0x01 = The Terminal ID of the Terminal to which the endpoint of this interface is connected.
0x01, // bDelay -> 0x01 = Delay (delta) introduced by the data path (see Section 3.4, ?Inter Channel Synchronization? - in Audio Devices). Expressed in number of frames.
0x01,0x00, // wFormatTag -> 0x0001 = PCM
// ASID FORMAT_TYPE
0x0E, // Size : 14 Bytes
CS_INTERFACE, // CS_INTERFACE Descriptor Type
FORMAT_TYPE, // bDescriptorSubtype -> 0x02 = FORMAT_TYPE
0x01, // bFormatType -> 0x01 = FORMAT_TYPE_I -> ref: A.1.1 Audio Data Format Type I Codes -> Audio Data Format Dok
0x02, // bNrChannels -> 0x02 = Two channels
BYTES_PR_SAMPLE, // bSubFrameSize -> 0x03 = 3 bytes pr audio subframe
BIT_RESOLUTION, // bBitResolution -> 0x18 = 24 bit pr sample
0x02, // bSamFreqType -> 0x02 = 2 sample frequencies supported
0x00,0x7D,0x00, // tSamFreq -> 0x7D00 = 32000 Hz
0x80,0xBB,0x00, // tSamFreq -> 0xBB80 = 48000 Hz
//ED ENDPOINT OUT
0x09, // Size : 9 Bytes
USB_DESCRIPTOR_ENDPOINT, // 0x05 -> ENDPOINT Descriptor Type
0x01, // bEndpointAddress -> 0x01 = adress 1, OUT, -> ref 9.6.6 Endpoint -> usb_20 Dok
0x09, // bmAttributes -> 0b00001001 -> Bits 0-1 = 01 = Isochronous , Bits 2-3 = 10 = Adaptive
AUDIO_MAX_SAMPLES * sizeof ( AUDIO_PLAY_SAMPLE ), AUDIO_MAX_SAMPLES * sizeof ( AUDIO_PLAY_SAMPLE )>>8,
0x01, // bInterval -> 0x01 = 1 millisecond
0x00, // Unused
0x00, // Unused
//AS ENDPOINT
0x07, // Size : 7 Bytes
CS_ENDPOINT, // CS_ENDPOINT
EP_GENERAL, // bDescriptorSubtype -> 0x01 = GENERAL
SAMPLING_FREQ_CONTROL, // bmAttributes -> 0b00000001 = Bit 1 = 1 => Sample Freq Control is supported by this endpoint
0x00, // bLockDelayUnits -> 0x00 = Indicates the units used for the wLockDelay field: 0 = Undefined
0x00,0x00, // the time it takes this endpoint to reliably lock its internal clock recovery circuitry.
// ######## AUDIO STREAM INTERFACE 2 IN MICROPHONE
//ID // Alternate Setting 0 - 0 endpoint
0x09, // Size : 9 Bytes
USB_DESCRIPTOR_INTERFACE, // Interface Descriptor (0x04)
0x02, // bInterfaceNumber -> 0x02 Interface ID = 2
0x00, // bAlternateSetting -> 0x00 = Value used to select this alternate setting for the interface identified in the prior field
0x00, // bNumEndpoints -> 0x00 = 0 -> Number of endpoints used by this interface
AUDIO_DEVICE, // bInterfaceClass -> 0x01 = 1 = AUDIO
AUDIOSTREAMING, // bInterfaceSubClass -> 0x02 = AUDIO_STREAMING
0x00, // bInterfaceProtocol -> 0x00 = Unused
0x00, // iInterface -> 0x00 = Unused -> Index of string descriptor.
//ID // Alternate Setting 1 - 1 endpoint
0x09, // Size : 9 Bytes
USB_DESCRIPTOR_INTERFACE, // Interface Descriptor (0x04)
0x02, // bInterfaceNumber -> 0x02 Interface ID = 2
0x01, // bAlternateSetting -> 0x01 = Value used to select this alternate setting for the interface identified in the prior field
0x01, // bNumEndpoints -> 0x01 = 1 -> Number of endpoints used by this interface
0x01, // bInterfaceClass -> 0x01 = 1 = AUDIO
0x02, // bInterfaceSubClass -> 0x02 = AUDIO_STREAMING
0x00, // bInterfaceProtocol -> 0x00 = Unused
0x00, // iInterface -> 0x00 = Unused -> Index of string descriptor.
// ASID GENERAL
0x07, // Size : 7 Bytes
CS_INTERFACE, // CS_INTERFACE Descriptor Type
AS_GENERAL, // GENERAL Descriptor
0x06, // bTerminalLink -> 0x06 = The Terminal ID of the Terminal to which the endpoint of this interface is connected. = 6
0x01, // bDelay -> 0x01 = Delay (delta) introduced by the data path (see Section 3.4, ?Inter Channel Synchronization? - in Audio Devices). Expressed in number of frames.
0x01,0x00, // wFormatTag -> 0x0001 = PCM
// ASID FORMAT_TYPE
0x0E, // Size : 14 Bytes
CS_INTERFACE, // CS_INTERFACE Descriptor Type
FORMAT_TYPE, // bDescriptorSubtype -> 0x02 = FORMAT_TYPE
0x01, // bFormatType -> 0x01 = FORMAT_TYPE_I -> ref: A.1.1 Audio Data Format Type I Codes -> Audio Data Format Dok
0x02, // bNrChannels -> 0x02 = Two channels
BYTES_PR_SAMPLE, // bSubFrameSize -> 0x03 = 3 bytes pr audio subframe
BIT_RESOLUTION, // bBitResolution -> 0x18 = 24 bit pr sample
0x02, // bSamFreqType -> 0x02 = 2 sample frequencies supported
0x00,0x7D,0x00, // tSamFreq -> 0x7D00 = 32000 Hz
0x80,0xBB,0x00, // tSamFreq -> 0xBB80 = 48000 Hz
//ED ENDPOINT IN
0x09, // Size : 9 Bytes
USB_DESCRIPTOR_ENDPOINT, // 0x05 -> ENDPOINT Descriptor Type
0x82, // bEndpointAddress -> 0x82 = adress 2, IN, -> ref 9.6.6 Endpoint -> usb_20 Dok
0x05, // bmAttributes -> 0b00000101 -> Bits 0-1 = 01 = Isochronous , Bits 2-3 = 01 = Asynchronous
AUDIO_MAX_SAMPLES * sizeof ( AUDIO_PLAY_SAMPLE ), AUDIO_MAX_SAMPLES * sizeof ( AUDIO_PLAY_SAMPLE )>>8,
0x01, // bInterval -> 0x01 = 1 millisecond
0x00, // unused
0x00, // unused
//AS ENDPOINT
0x07, // Size : 7 Bytes
CS_ENDPOINT, // bDescriptorType -> 0x25 = CS_ENDPOINT
EP_GENERAL, // bDescriptorSubtype -> 0x01 = GENERAL
SAMPLING_FREQ_CONTROL, // bmAttributes -> 0b00000001 = Bit 1 = 1 => Sample Freq Control is supported by this endpoint
0x00, // bLockDelayUnits -> 0x00 = Indicates the units used for the wLockDelay field: 0 = Undefined
0x00,0x00, // the time it takes this endpoint to reliably lock its internal clock recovery circuitry.
This post is quite old but my reply maybe helpful to others facing the same difficulty.
I noticed that windows does not make changes to the installed drivers when the interface changes. You must manually uninstall the windows driver for your device and let windows reinstall it either on USB re-connection or reset of the device.

Is [0x02, 0x03, 0x00] valid data?

I am trying to write a program that returns valid data according to a message protocol within a byte[] array.
I have:
STX: 0x02
ETX: 0X03
DLE: 0x10 //Delimiter
Valid data is when the byte[] array contains STX, ETX, data and a correctly calculated LRC, for example:
byte[] validMsg1 = {0x02, // STX
0x10,0x2,0xA,0x10,0x10,0x7,0x8, // Data 2 A 10 7 8
0x03, // ETX
0x2^0xA^0x10^0x7^0x8^0x03}; // LRC calculated from the data (with the DLE removed) plus the ETX
Invalid data example:
byte[] invalidMsg1 = {0x02, // STX
0x10,0x2,0xA, // Data 2 A
0x03, // ETX
0x2^0xA^0x10^0x7^0x8^0x03,
0x02, //STX
0x05,0x44};
The byte might also contain random values around the valid data:
byte[] validMsgWithRandomData1 = {0x32,0x32,0x32, //Random data
0x02, // STX
0x31,0x32,0x10,0x02,0x33, // Data 31 32 02 33
0x03, // ETX
0x31^0x32^0x02^0x33^0x03,// LRC calculated from the data (with the DLE removed) plus the ETX
0x2,0x3,0x00,0x02 //Random data
};
My problems is that when I use the message with random data in and have 0x2,0x3,0x00,0x02 it breaks because it sees 0x02 and 0x03 as the STX and ETX and then it calculates LRC which results in 0x03 which results in this being returned: 0x2,0x3,0x00 with the last 0x03 seens as the LRC.
Question is this valid data:
byte[] data = {
0x02, // STX
0x03, // ETX
0x00, // LRC
};
I am supposed to return the most recent valid data which is that but there is better data within this which is:
byte[] validData = {
0x02, // STX
0x31,0x32,0x10,0x02,0x33, // Data 31 32 02 33
0x03, // ETX
0x31^0x32^0x02^0x33^0x03,// LRC calculated from the data (with the DLE removed) plus the ETX
};

Using USBASP programmer for SPI communication

I'm trying to send some data from PC to ATmega328P chip through USBASP programmer.
It is able to transmit up to 4 bytes over SPI. These 4 bytes сan be set in USB Setup Packet (2 bytes for wValue and 2 bytes for wIndex). To enable SPI in ATmega328P I've connected USBASP Reset pin to SS. At PC side I'm using libusb to send USB Setup Packets.
ATmega328P code:
int main()
{
char spiData = 0;
// Enable SPI
SPCR |= 1 << SPE;
DDRB |= 1 << 4;
// Main cycle
while(1)
{
while(!(SPSR & (1 << SPIF))); // Wait for transmission end
spiData = SPDR; // Read SPI Data Register
// Do something with first byte
while(!(SPSR & (1 << SPIF)));
spiData = SPDR;
// Do something with second byte
while(!(SPSR & (1 << SPIF)));
spiData = SPDR;
// Do something with third byte
while(!(SPSR & (1 << SPIF)));
spiData = SPDR;
// Do something with fourth byte
}
return 0;
}
PC code (C#):
static void Main(string[] args)
{
// Find USBASP
var device = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(0x16C0, 0x05DC));
// Set Clock and RESET pin to enable SPI
int bytesTrasferred;
var usbSetupPacket = new UsbSetupPacket(0xC0, 1, 0, 0, 0);
device.ControlTransfer(ref usbSetupPacket, null, 0, out bytesTrasferred);
// Send Setup Packets
while (Console.ReadKey(true).Key == ConsoleKey.Enter)
{
byte[] buffer = new byte[4];
usbSetupPacket = new UsbSetupPacket(0xC0, 3, 200, 200, 0);
device.ControlTransfer(ref usbSetupPacket, buffer, 4, out bytesTrasferred);
Console.WriteLine("Done. Return result: [{0}, {1}, {2}, {3}]", buffer[0], buffer[1], buffer[2], buffer[3]);
}
// Disable SPI
usbSetupPacket = new UsbSetupPacket(0xC0, 2, 0, 0, 0);
device.ControlTransfer(ref usbSetupPacket, null, 0, out bytesTrasferred);
// Free resources
device.Close();
UsbDevice.Exit();
}
USBASP -> ATmega328P SPI communication works well, but it seems that data in wValue and wIndex fields of Setup Packet comes corrupted to USBASP, because I'm getting this output (while it should be constant - [0, 200, 0, 200]):
[0, 153, 0, 128]
[0, 136, 0, 128]
[1, 209, 1, 217]
[1, 128, 0, 145]
[1, 153, 0, 128]
[0, 145, 1, 209]
[1, 217, 1, 136]
[0, 209, 1, 209]
[1, 217, 1, 136]
so on...
Also I see these numbers on LED digit display connected to ATmega328P.
Can anyone explain that?
P.S. For programming purposes this USBASP works well.
The problem was in SPI though. My ATmega328P was set by default to 8MHz internal clock with 1/8 divider, so it had 1MHz frequency which is too small for proper SPI communication. I fixed that by setting ATmega328P to external 16mHz crystal.
You can also set the data transfer rate to 750kb in libusb or if that program does not support changing transfer rates, use a program such as avrdude which can do that.

Resources