➡ usb hid host block ! ❄

264 views
Skip to first unread message

charli va

unread,
Oct 26, 2023, 1:43:03 PM10/26/23
to fpga-wars-explora...@googlegroups.com
Hola a todos! os voy a ir introduciendo la nueva colección de bloques usb que estoy preparando.

Aquí he publicado un vídeo por si queréis ver el primer test en funcionamiento:

Inicialmente como os comenté estoy portando la librería de nand2mario que cubre ratón, teclado y mandos (pads) usb, esto nos va a dar mucho juego en todos los sentidos.

He empezado por aquí porque estoy estudiando el protocolo usb y me ha parecido un primer buen ejercicio para enfrentarme este protocolo que es bastante complejo.

Lo bueno es que con icestudio sólo tendremos que arrastrar un bloque y conectar cuatro cables para poder usar usb y así el que símplemente quiera disponer de un teclado , ratón o pad podrá hacerlo muy fácilmente.

Este módulo es muy sencillo, cubre sólo una parte mínima del protocolo hid (es la parte del protocolo usb que permite conectar interfaces humanas como ratones o teclados) y en modo host, esto quiere decir que cuando vayamos avanzando inicialmente necesitaremos dispositivos "puros".

Esto quiere decir que por ejemplo un teclado que tenga una entrada usb no va a funcionar, o un teclado con teclado y ratón táctil tampoco.

Esto es debido a que estos disposivos compuestos, funcionan a modo hub, lo que exponen al exterior es un hub usb y de cara hacia adentro tienen sus hosts.

Esto me gustaría más adelante mejorarlo y aportarlo al proyecto de nan2mario, pero de momento con tener estos bloques iniciales en icestudio ya será un gran avance.

De inicio vamos a probar el ratón, os paso un proyecto de test, como veis es un zip, porque incorporo directamente el proyecto de nand2mario (los dos ficheros verilog y la rom) tenéis que tenerlo todo en el mismo directorio.

Este proyecto me está sirviendo para probar una nueva funcioanlidad que os liberaré dentro de poco para trabajar más cómodamente con ficheros externos verilog, esto es otra batalla pero  es una característica muy interesante, yo trabajo mucho con verilog y utilizo icestudio como un "top layer" o por decirlo de alguna forma, una capa de abstracción que me permite ver mucho más fácilmente los diseños completos o navegar entre sus módulos y bloques, además de simplificar la portabilidad entre tarjetas, pero como os digo esto ya hablaremos más adelante.

Para conectar el usb, tenéis que dependiendo de la tarjeta que uséis incorporar un PMOD usb que compréis si la tarjeta soporta PMODs o si no queréis usar un PMOD o la tarjeta no lo soporta, podéis montaros super fácil el conector usb, como he hecho en el ejemplo con la Alhambra II.

El protocolo usb es muy interesante, un conector usb hid 1.1 como en este caso (baja velocidad) utiliza 4 pines, uno GND otro VCC (5V) y luego dos líneas de diferenciales (D+ y D-) para transmitir los datos.


USB-A-Jack-Pinout.png

Según el voltage que haya entre D+ y D- y su impedancia los elementos interconectados definen si son host, hub....

En nuestro caso, que seremos host, el montaje del conector hembra es el que os adjunto a continuación.

Tenéis que conectar el GND al GND de la placa, el VCC a 5V y D+ y D- a los pines de datos con los que transmitiremos (en el ejemplo de la alhambra II D0 y D1).

Para  indicar que es un host lo que tenemos que hacer es hacer un pulldown con una resistencia de 15k (conectar el pin a GND mediante una resistencia de 15K) de las líneas D+ y D-

FEZ_USB_Host_Cable_Schematic.png

con eso ya lo tenemos todo para poder conectar cualquier dispositivohost  hid 1.1 a nuestras placas.

La imagen anterior es de este blog https://blog.tkjelectronics.dk/2011/03/fez-panda-and-usb-host/ en el cual conectan un usb a un microcontrolador , lo he puesto por aclarar el conexionado.

Aquí os adjunto una imagen del breadboard que he montado para las pruebas, yo he desoldado un conector usb de un modem viejo pero también podéis cortar un cable usb hembra y en una breadboard poner las resistencias y de ahí a la alhambra.

usb-alhambraii.jpg

En el ejemplo que os mando, podéis conectar un ratón usb, una vez cargado, con el botón sw1 de la Alhambra II , arrancais el circuito.

Abrís el terminal seria a 115200bps y al mover el ratón y pulsar los tres botones, si activais el modo hexadecimal, veréis los datos que llegan.

Si utilizais otra tarjeta, es importante que utiliceis un pll para que el reloj del circuito vaya a 12Mhz que es lo que necesita la comunicación usb para funcionar. Ya haré un ejemplo con una colorlight u otra placa a más velocidad y utilizar  múltiples relojes pero para el que quiera probarlo ahora es tan sencillo como pasar al reloj del sistema a 12Mhz

En cuanto termine de preparar el bloque para soportar teclado y ratón prepararé algunas demos más interesantes, de momento si queréis acompañarme en el desarrollo de estos bloques y ayudarme a testearlo en otras placas sería fantástico, creo que todos aprenderemos mucho.

Si tenéis cualquier duda o comentario , será bienvenido!, intentaré ir explicando en detalle todos los pasos y el contenido del circuito pero para los impacientes os dejo aquí el test.

Importante, tenéis que utiilizar la última versión WIP de Icestudio (https://downloads.icestudio.io) porque necesitáis utilizar una versión que soporte las entradas inout (instalando apio developtment 0.9.0 desde la toolchain de icestudio)

Espero que os sea útil!


// ENGLISH =>

Hi everyone! I will be introducing the new collection of USB blocks that I am preparing.

Initially, as I mentioned, I am porting the nand2mario library, which covers USB mice, keyboards, and controllers. This will give us a lot of play in all respects.

I started here because I am studying the USB protocol and it seemed like a good first exercise to face this protocol, which is quite complex.

The good thing is that with icestudio, we will only have to drag a block and connect four cables to be able to use USB, so anyone who simply wants to have a keyboard, mouse, or controller can do it very easily.

This module is very simple, it only covers a minimal part of the HID protocol (it is the part of the USB protocol that allows you to connect human interfaces such as mice or keyboards) and in host mode, which means that when we advance initially we will need "pure" devices.



USB-A-Jack-Pinout.png

This means that, for example, a keyboard that has a USB input will not work, or a keyboard with a touch mouse and keyboard will not work either.

This is due to the fact that these compound devices operate in hub mode, they expose a USB hub to the outside and have their hosts facing inward.

I would like to improve this later and contribute it to the nan2mario project, but for now, having these initial blocks in icestudio will already be a great advance.

To start, we will test the mouse, I will pass you a test project, as you can see it is a zip, because I incorporate directly the nand2mario project (the two Verilog files and the ROM) you need to have everything in the same directory.

This project is serving me to test a new functionality that I will release soon to work more comfortably with external Verilog files, this is another battle but it is a very interesting feature, I work a lot with Verilog and I use icestudio as a "top layer" or in a way, an abstraction layer that allows me to see much more easily the complete designs or navigate between their modules and blocks, in addition to simplifying portability between boards, but as I say this we will talk about it later.

To connect the USB, depending on the board you are using, you need to incorporate a USB PMOD that you buy if the board supports PMODs or if you do not want to use a PMOD or the board does not support it, you can easily assemble the USB connector, as I did in the example with the Alhambra II.

The USB protocol is very interesting, a USB HID 1.1 connector like in this case (low speed) uses 4 pins, one GND, another VCC (5V), and then two differential lines (D+ and D-) to transmit the data.

According to the voltage between D+ and D- and its impedance, the interconnected elements define whether they are host, hub, etc.

In our case, since we will be host, the assembly of the female connector is the one I attach in the next pictures.

You need to connect GND to the GND of the board, VCC to 5V, and D+ and D- to the data pins with which we will transmit (in the example of the Alhambra II D0 and D1).

To indicate that it is a host, what we have to do is make a pulldown with a 15k resistor (connect the pin to GND through a 15K resistor) of the D+ and D- lines.



FEZ_USB_Host_Cable_Schematic.png

With this we already have everything we need to connect any HID 1.1 host device to our boards.

The previous image is from this blog https://blog.tkjelectronics.dk/2011/03/fez-panda-and-usb-host/ in which they connect a USB to a microcontroller. I have placed it to clarify the wiring.

Here I attach an image of the breadboard that I have assembled for testing. I have desoldered a USB connector from an old modem, but you can also cut a female USB cable and in a breadboard put the resistors and from there to the Alhambra.


usb-alhambraii.jpg

In the example I send you, you can connect a USB mouse. Once loaded, with the sw1 button on the Alhambra II, you start the circuit.

Open the serial terminal at 115200bps and when you move the mouse and press the three buttons, if you activate the hexadecimal mode, you will see the data that arrives.

If you use another card, it is important that you use a PLL so that the circuit clock goes to 12Mhz which is what the USB communication needs to work. I will already do an example with a colorlight or another board at a faster speed and use multiple clocks but for those who want to try it now it is as simple as switching to the system clock to 12Mhz

As soon as I finish preparing the block to support keyboard and mouse, I will prepare some more interesting demos. For the moment, if you want to accompany me in the development of these blocks and help me test them on other boards, it would be fantastic, I think we will all learn a lot.

If you have any questions or comments, they will be welcome! I will try to explain in detail all the steps and the content of the circuit, but for the impatient I leave you the test here.

One important thing is that you need to use the last wip (download from https://downloads.icestudio.io) because you need an icestudio version that supports inout pins, and install from toolchain install menu, the apio development version (0.9.0).

I hope it is useful!

usb_hid_mouse_test1.zip

charliva

unread,
Oct 26, 2023, 2:03:42 PM10/26/23
to FPGAwars: explorando el lado libre
==> ENGLISH BELOW

He publicado un vídeo de la demo en funcionamiento, para el que le interese:


Gracias!

==> ENGLISH

I have published a video with the demo in action:

In the previous email i have forgot  the "ENGLISH BELOW" label at the beginning, if you are an english speaker you can go to the middle of the initial email in this thread and found the text in english.

Thanks!

Jo mo

unread,
Oct 26, 2023, 5:01:45 PM10/26/23
to FPGAwars: explorando el lado libre
Muchas Gracias Carlos,

I didn't test it, but looks super nice.
For visualization of "analog" moving values like X and Y of your mouse, it will be great to have a serial plotter included in our serial monitor(like the one in arduino)!
Maybe i will do it one day if i find some time ;-) !

This way of using verilog code available in other v.files is really straight-forward and useful! 
It make the conversion to icestudio of "complex" existing verilog projects ( made without icestudio) very easy !
it is much faster then creating icestudio block for each one of this verilog files( "to include").
it's better to have two ways of doing thinks that having only one !

Keep up this good work man ;-) !  And have a good night.

charli va

unread,
Oct 26, 2023, 5:29:34 PM10/26/23
to fpga-wars-explora...@googlegroups.com
Thanks for your words Joaquim!!! one of the most ambitious features that i'm working (slowly but in progress) is importing automatically verilog files, i hope  finish it soon.

The serial plotter will be awesome, we need a lot of improvement in the "test features".

I hope you are fine and soon came back with a lot of energy!

A big hug!

--
Has recibido este mensaje porque estás suscrito al grupo "FPGAwars: explorando el lado libre" de Grupos de Google.
Para cancelar la suscripción a este grupo y dejar de recibir sus mensajes, envía un correo electrónico a fpga-wars-explorando-el...@googlegroups.com.
Para ver esta conversación en el sitio web, visita https://groups.google.com/d/msgid/fpga-wars-explorando-el-lado-libre/4216b1fe-ad6f-4dcc-a5b2-653d76f2e6d3n%40googlegroups.com.

Democrito

unread,
Oct 26, 2023, 5:39:30 PM10/26/23
to FPGAwars: explorando el lado libre
Este finde lo pruebo y te cuento!

charli va

unread,
Oct 26, 2023, 5:46:12 PM10/26/23
to fpga-wars-explora...@googlegroups.com
Gracias Demócrito contaba contigo! ;)

En los próximos días iré cerrando el teclado y el pad, lo bueno de tunear un conector usb es que para los siguientes experimentos que hagamos ya sólo será conectar.

Mil gracias!


El jue, 26 oct 2023 a las 23:39, Democrito (<spo...@gmail.com>) escribió:
Este finde lo pruebo y te cuento!

--
Has recibido este mensaje porque estás suscrito al grupo "FPGAwars: explorando el lado libre" de Grupos de Google.
Para cancelar la suscripción a este grupo y dejar de recibir sus mensajes, envía un correo electrónico a fpga-wars-explorando-el...@googlegroups.com.

Democrito

unread,
Oct 27, 2023, 6:10:30 PM10/27/23
to FPGAwars: explorando el lado libre
Me ha funcionado!

Así hice el cableado:

0.jpg      1.jpg

Le puse las dos resistencias de 15K en configuración pull-down (a masa) en los pines D+ y D-. Utilicé epoxi de dos componentes transparente para fijar los cables y no moviese los pines soldados a los cables y además quedase todo compacto, resistencias incluidas.

Utilicé la última WIP, que ya la tenía instalada desde que la subiste.

Subí el ICE-HID a la FPGA. En el terminal serie habilité la opción "Hex View", pulsé en SW1 de la Alhambra II FPGA y se ve esto:

HID with FPGA serial demo x axis.gif

Utilicé un mouse con cable. Antes de usar este mouse, usé uno inalámbrico, pero con ese no funcionó.

Vista general del montaje:

vista general del proyecto HID FPGA.jpg




Ahora te comento algo que no sé si es por la nueva WIP o porque Windows 10 ha tenido un lapsus. Tube que ir a Administrador de dispositivos para habilitar algo que se tenía que hacer antiguamente, el puerto virtual de comunicaciones o VCP.

administrador de dispositivos.png


vcp.png

Igual esto sólo me ha pasado a mí, con el tiempo ya veremos lo que dicen los demás.

Enhorabuena por la adaptación!

Un abrazo!

Democrito

unread,
Oct 27, 2023, 6:14:55 PM10/27/23
to FPGAwars: explorando el lado libre
Fe de erratas:

Puse "Tube" en vez de "Tuve". Perdón, a mí también me duele los ojos cada vez que lo veo.

Democrito

unread,
Oct 27, 2023, 6:18:56 PM10/27/23
to FPGAwars: explorando el lado libre
Hace mucho tiempo compré 10 USB hembras, el que puse en las fotos fue el primero que estrené.

charli va

unread,
Oct 28, 2023, 1:57:27 AM10/28/23
to fpga-wars-explora...@googlegroups.com
Millones de gracias Demócrito!!!!

Lo del VCP no lo había visto. nunca, eso habrá que estar al tanto, en sí eso tiene que ver con la Alhambra y no con Icestudio, puede que haya cambiado algo en las últimas actualizaciones de windows....si a alguien más le salta que nos avise.

Sobre el inalámbrico y los hubs no funcionan, son otros protocolos, ahora mismo he integrado el módulo de nan2mario tal cual,  y solo soporta dispositivos host hid 1.0 (básicamente dispositivos sencillos y puros)

Ya me he mirado el código y he visto como va, en paralelo estoy aprendiendo el protocolo usb que  llevo tiempo ya con ello e intentaré ampliar la funcionalidad para soportar dispositivos algo más modernos (ratones y teclados wireless y mixtos por ejemplo).

Pero bueno de momento lo primero es tener estos tres bloques básicos de ratón ,teclado y mando. Cuando los tenga quiero hacer alguna demo más chula, posiblemente con alguna pantalla y crearé una colección para que esté todo reunido y podamos ahí colaborar en mejoras.


El sáb, 28 oct 2023 a las 0:18, Democrito (<spo...@gmail.com>) escribió:
Hace mucho tiempo compré 10 USB hembras, el que puse en las fotos fue el primero que estrené.

--
Has recibido este mensaje porque estás suscrito al grupo "FPGAwars: explorando el lado libre" de Grupos de Google.
Para cancelar la suscripción a este grupo y dejar de recibir sus mensajes, envía un correo electrónico a fpga-wars-explorando-el...@googlegroups.com.

Democrito

unread,
Oct 29, 2023, 3:31:18 AM10/29/23
to FPGAwars: explorando el lado libre
Dejo un ejemplo de HID 1.1 donde todo ocurre en la FPGA. Se trata de mover el mouse (de los que tienen cable, los inalámbricos no sirven) y que una aguja indique la posición en una pantalla TFT monocroma de 128x64 pixeles (SH1106 ó SDD130x con protocolo I2C).


La posición de la aguja sólo admite 7 bits (0..127 es una vuelta completa), es por eso que al poco que se mueve lo hace rápidamente. En el vídeo, aunque no se note mucho, muevo el mouse de forma diagonal para tratar de mover la aguja más lentamente.

Adjunto ICE, si tenéis cualquier pregunta, aquí estamos.

Saludos!
HID_mouse.zip

charli va

unread,
Oct 29, 2023, 3:55:47 AM10/29/23
to fpga-wars-explora...@googlegroups.com
Fantástico Demócrito!!! mil gracias por currarte este ejemplo!! el tema de la resolución hay que escalarlo simplemente, prepararé un ejemplo con eso o modificaré el tuyo.

De verdad mil gracias!

--
Has recibido este mensaje porque estás suscrito al grupo "FPGAwars: explorando el lado libre" de Grupos de Google.
Para cancelar la suscripción a este grupo y dejar de recibir sus mensajes, envía un correo electrónico a fpga-wars-explorando-el...@googlegroups.com.

Democrito

unread,
Oct 29, 2023, 4:15:38 AM10/29/23
to FPGAwars: explorando el lado libre
Otro millón de gracias para ti, Carlos.

Jesus Arias

unread,
Oct 30, 2023, 4:37:06 AM10/30/23
to FPGAwars: explorando el lado libre
Intentaré probarlo cuando tenga un rato, que una interfaz USB siempre es útil, y un USB host todavía más.
Tengo una duda/curiosidad acerca de la interfaz eléctrica: Parece que D+,D- no se están usando como una señal diferencial, es decir, no es necesario que estén conectados a una pareja de pines del banco 3 configurados como tal ("SB_LVDS_INPUT"), ¿verdad?
(De todos modos en el bus USB la señal diferencial sirve de poco cuando se usa un estado single-ended-zero para señalizar el final de los paquetes de datos)
Saludos

Jesus Arias

unread,
Oct 30, 2023, 5:16:28 AM10/30/23
to FPGAwars: explorando el lado libre
Olvidé añadir otro comentario:
Sería conveniente poner unas resistencias de 22 o 27 ohm en serie con D+ y D-. Seguramente en un USB low-speed esto tiene poca importancia, pero ayuda a mejorar la integridad de la señal evitando las reflexiones en el lado del host (el lado del device ya debería estar bien terminado). En realidad la resistencia que se necesita es de 45 ohm, pero como los pines tienen una resistencia de salida de unos 20 ohm con unos 22 ohm adicionales basta.

Saludos

El jueves, 26 de octubre de 2023 a las 19:43:03 UTC+2, charliva escribió:

charli va

unread,
Oct 30, 2023, 6:02:13 AM10/30/23
to fpga-wars-explora...@googlegroups.com
Muchas gracias Jesús por tus comentarios! los pondré en prácticas, en cuanto tenga todo más rodado lo dejaré bien documentado y todas las pruebas que hagamos entre todos.

Esta semana liberaré el teclado y el joystick y ya prepararé bien el código, colecciones...

Muchas gracias!

--
Has recibido este mensaje porque estás suscrito al grupo "FPGAwars: explorando el lado libre" de Grupos de Google.
Para cancelar la suscripción a este grupo y dejar de recibir sus mensajes, envía un correo electrónico a fpga-wars-explorando-el...@googlegroups.com.

Jo mo

unread,
Oct 30, 2023, 9:15:25 AM10/30/23
to FPGAwars: explorando el lado libre
Ola Carlos, Jesus e Democrito,

This usb input interface looks super useful !
With it we should be able to connect input devices working at lows/full speeds (1.5mbps /12mbps)!

As wrote Jesus, for connecting faster usb devices, a good use of differential pairs may be necessary !
I also see that you are using D0 and D1 for the usb D+ and D-. its is good because D1 and D0 are on the same differential pair circuitry of the Ice40.
But to configure well the differential pair (especially at higher usb frequencies), we can lower the voltage of  D+,D-  from 3.3v to about +/- 350mV.

For doing that, we can change the mode of these two FPGA pins from IO_TYPE=LVCMOS33 to IO_TYPE=LVDS25.
IO_TYPE=LVCMOS33 being the default icestudio value written by compiler.js (see lines 906 and 928) in the .pcf/.lpf file (for all used pins)

Jesus mentioned the use of the ("SB_LVDS_INPUT") to change this type of input!
 
I fear (to be checked) that the primitive will not work, if we maintain the writing by compiler.js
of IO_TYPE=LVCMOS33 for all pins inside the .PCF file.
In nextpnr the .pcf file informations (IO_TYPE=...) may override/have priority above the info/primitives (defparam differential_input.IO_STANDARD = "SB_LVDS_INPUT") supplied inside verilog file (main.v)

For info, here is a good read for ice40 differential pairs use.

These last month i was playing with this differential pair subject for ecp5 boards. And i only got a good working case by removing IO_TYPE=LVCMOS33 from compiler.js, i will post, these week, those results in the thread (Pullup settings for ECP5 fpgas)

But again, for the low speed usb application that you are using here, we may not need to worry too much about proper differential pair use ?!

a huh and, have a nice day guys!

Jesus Arias

unread,
Oct 30, 2023, 10:42:41 AM10/30/23
to FPGAwars: explorando el lado libre
Hi, let me present an example of a working differential input:

Verilog source:
wire din;
SB_IO #(.PIN_TYPE(6'b0000_01), .IO_STANDARD("SB_LVDS_INPUT")) lvds0
(
   .PACKAGE_PIN(lvds),
   .D_IN_0(din)
);

And PCF file:
set_io lvds 2 # differential positive input, negative is pin #1

This input works with small amplitude inputs, but also with 3.3V signals.
But the problem I see with USB is that a differential input isn't enough, you also need the single-ended inputs. And when a pin pair is set as differential nextpnr refuses to also route the individual inputs to your logic.

So, I'm affraid the differential input couldn't be used, so our data can be affected by common-mode interference. But it already is because a too smart guy at Intel, long time ago, decided to use single-ended signaling for the end of data packets (that guy ought to be fired... by a firing squad! just kidding ;) So, our purely single-ended USB host shouldn't be much worse than any commercial part.

Best regards.

charli va

unread,
Oct 30, 2023, 11:07:11 AM10/30/23
to fpga-wars-explora...@googlegroups.com
Very interesting! Now I'm starting to understand the entire USB protocol, which is very complicated in general, but step by step I think we can have reasonably good hosts as Jesus says XD

When slow devices are well supported, I would like to delve into high speed hubs and devices, another thing I am interested in is creating a module to act as a USB device that can be recognized by Linux or Windows, step by step. But together we will achieve it!!

Joaquim, do you think it could be interesting that we can integrate the io_type selection? I am working on the new panel for cards, I hope to have the first version by next week, I think you could contribute a lot from there.

I want to see your progress on compiler.js!

 Thank you very much for all your work my friends!

Jesus Arias

unread,
Oct 30, 2023, 12:13:59 PM10/30/23
to FPGAwars: explorando el lado libre
I got it working at 1st try!
With just 519 logic cells and one BRAM and now the 3 mouse buttons are displayed in the board's LEDs. Amazing!!!
And it looks like it's going to run with a 96MHz clock, so, a full-speed host seems to be possible.
Best regards

charli va

unread,
Oct 30, 2023, 12:23:26 PM10/30/23
to fpga-wars-explora...@googlegroups.com
Thanks Jesús!!!! :)  keyboards are comming!!

Jo mo

unread,
Oct 30, 2023, 1:49:52 PM10/30/23
to FPGAwars: explorando el lado libre
Sorry guys, i made a mistake! the "IOtype=... " (understood by nextpnr) is only for ecp5 (lpf files)  and not for ice40  (pcf) files

this is why the Ice40 example for "Differential pairs" that you wrote Jesus should work straight away in icestudio !


@ Carlos:  The more i think about all this special fpga hardware function/features, it seams to me that we should do the user settings in verilog users code (eg. inside an icestudio block)!
So better do a minimum setting in icestudio pop-up windows ! (Or we will need different popup windows for ice40 and ecp5 boards)

This way we will also be closer to the use of fpga outside the icestudio word !
And, we can easier import any verilog code found on github (or generated with an AI)

And then we may need to improve icestudio ability to analyse al this verilog code and update correctly all the child files(main.v, .pcf, lpf, ) to make in sort to support a maximum of the features of yosys and nextpnr for both families(ice40 and ecp5))

For the usb keyboard support, I am looking forward to .see your result

charli va

unread,
Oct 30, 2023, 2:00:22 PM10/30/23
to fpga-wars-explora...@googlegroups.com
Hi Joaquim!! my work in this way is tha convert icestudio in a powerful ide to work with verilog and blocks simultaneously but more affordable than now, the first importer from verilog files is very close, in the same way i'm closing other way to edit verilog inside icestudio .

I think you are in the good way, this kind of customizations should do into blocks like de first inout blocks, step by step!


Jesus Arias

unread,
Nov 6, 2023, 3:29:28 AM11/6/23
to FPGAwars: explorando el lado libre
Hi,
While trying to simulate the usb core (with little success yet) I found this line in the source:
line 251:                         if(inst==4) begin ug <= 9; up <= 0; um <= 0; end
This looks to me like a mistake because "ug" was only 1-bit wide ¿right?
Regards

charli va

unread,
Nov 6, 2023, 10:22:01 AM11/6/23
to fpga-wars-explora...@googlegroups.com
Hi! Indeed Jesus!, ug is a 1-bit register, in fact its possible states are: ug=1 output enabled, ug = 0 hi-Z

I will restart the USB towards the end of the week, if you make progress and want to share things with us, even if they are thoughts, count on me.

Have a nice day!

Jesus Arias

unread,
Nov 6, 2023, 10:25:30 AM11/6/23
to FPGAwars: explorando el lado libre
Hi again,
I think it is convenient not to clear the mouse_dx and mouse_dy variables after a report pulse. In my test design I commented these lines out in your sources:

always @(posedge usbclk) begin : process_in_data
    data_rdy_r <= data_rdy; data_strobe_r <= data_strobe;
    report <= 0;                    // ensure pulse
    //if (report == 1) begin
    //    // clear mouse movement for later
    //    mouse_dx <= 0; mouse_dy <= 0;
    //end

    if(~data_rdy) rcvct <= 0;

In my system I'm using a quite different frequency for the CPU (32.5MHz) and I resorted to a fractional divider for the generation of the USB clock:

// DDS clock divider 189/512 * 32.5MHz = 11.997MHz
reg [8:0]dds_ph=0;
wire [8:0]next_ph = dds_ph + 189;
wire next_rise=next_ph[8]&(~dds_ph[8]); // Rising edge on next cycle

always @(posedge clk) dds_ph<=next_ph;
wire clk12=dds_ph[8]; // 12 MHz clk

And, I'm signaling a new valid data with a flag that gets set on reports and cleared when reading mouse_dx. (It could be an interrupt signal)

reg mousvalid=0;      // Flag: new mouse data, to input register #2 (along other flags)
always @(posedge clk)
if (mousreport & next_rise) mousvalid<=1;
else if ((addr==0)&in) mousvalid<=0; // CPU reads mouse_dx

wire [7:0]mousbut;   // To input register #2 (along other flags)
wire [7:0]mousdx;    // To Input register #0
wire [7:0]mousdy;    // To input register #3
wire mousreport;

usb_hid_host USBhost0 (
.usbclk(clk12),
.usbrst_n(~reset),
.usb_dm(dm),
.usb_dp(dp),
.report(mousreport),
.mouse_dx(mousdx),
.mouse_dy(mousdy),
.mouse_btn(mousbut)
);


And it still works...
Regards

El lunes, 30 de octubre de 2023 a las 17:23:26 UTC+1, charliva escribió:

charli va

unread,
Nov 6, 2023, 11:55:25 AM11/6/23
to fpga-wars-explora...@googlegroups.com
Sounds great! Also, from what I see, you have already separated the logic for a mouse-only module, it's great, the truth is that it was something pending. With the improvements you make I will port them and follow your example for the keyboard.

Thanks!

Democrito

unread,
Nov 25, 2023, 10:26:01 AM11/25/23
to FPGAwars: explorando el lado libre
I don't know if this will help, but it's about reading a mouse with an Arduino. I leave you with a video and a GitHub with the code.

Video: https://www.youtube.com/watch?v=CMv6bJRJzyY

GitHub: https://github.com/michalin/ardumouse

Democrito

unread,
Nov 25, 2023, 11:24:57 AM11/25/23
to FPGAwars: explorando el lado libre
Analysis of the USB protocol. It's really complex, it's 650 pages. I leave a video explaining the most basic things and yet it has many complexities. The video is very good, but it is for people with a high learning curve. An interesting thing is that USB works by changing bits, to consider that something is 1 or 0.

https://www.youtube.com/watch?v=wdgULBpRoXk

charli va

unread,
Nov 25, 2023, 2:38:34 PM11/25/23
to fpga-wars-explora...@googlegroups.com
Thanks for your references Democrito!, i'm adding other  some interesting and useful links:


For hid, the specification here:


Now, i'm studing it slow but without  stop, i think this is very useful and necessary protocol to implement, usb hid is the most basic and simple but the idea is grow up and understand hubs, hosts and usb-c at final step.

usb is an obscure and extense protocol and if we work together i think we get successful results in short time.

This will be a very interesting travel!



El sáb, 25 nov 2023 a las 17:25, Democrito (<spo...@gmail.com>) escribió:
Analysis of the USB protocol. It's really complex, it's 650 pages. I leave a video explaining the most basic things and yet it has many complexities. The video is very good, but it is for people with a high learning curve. An interesting thing is that USB works by changing bits, to consider that something is 1 or 0.

https://www.youtube.com/watch?v=wdgULBpRoXk

--
Has recibido este mensaje porque estás suscrito al grupo "FPGAwars: explorando el lado libre" de Grupos de Google.
Para cancelar la suscripción a este grupo y dejar de recibir sus mensajes, envía un correo electrónico a fpga-wars-explorando-el...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages