Category Archives: Electronics

Programming an Arduino via WiFi with the ESP8266

Foreword

This is experimental and not exactly for beginners, something may be wrong. Proceed with caution or you can break something!

A (not so) brief introduction.

I’ve been working on a new robot called RoDI for a summer course at my Alma mater. RoDI is a low cost wireless robot to teach robotics and programming I started developing last year (reminder to self: I still need to post about it), but it wasn’t until a month ago that I started to work on it more often.

The first version used a HC-06 Bluetooth module to communicate with the computer. I wanted to to use WiFi, but the cost of the WiFi modules was a problem, since the idea was that the entire robot would cost less than 30 USD.

Then, I read about the ESP8266 WiFi modules on Hackaday, and started working on a new version of RoDI, this time with WiFi :D. I wanted to be able to flash the atmega328 inside the robot via WiFi because the robot doesn’t have a USB to Serial converter.

I found (again on HaD) a blog that showed how to flash an Arduino via WiFi with these modules, but it uses the ESP8266 to connect to a router, as we’re planning to have a few of this robots, and the student will take these robot and it doesn’t have another way of flashing the chip unless they have a programmer, so this method wouldn’t work for the robots. One thing that I learn from the blog was that I was going to need to use the transparent mode and, of course, use the module as an AP. Bad news, transparent mode is not available when using the module in server mode with the at_v0.20_on_SDKv0.9.3 version of the at command example. Time for hacking it!

After reading through the source code for the AT commands firmware I was able to enable transparent mode when using the module as a server. One security issue for this is that it supports up to 5 connections, so is not completely secure. I asked and got this response but wasn’t able to find that method (or variable?). I found another method that consist on configuring the AP using the wifi_softap_get_config method from the SDK, which lets us set the max_connection parameter. Yet another option is to add a password to the AP. But… we plan to use it only for robots in a summer course, so the security isn’t really important for now. 😉

Let’s get to work…

Connecting all together

CAUTION: This assumes you’re using a 3.3V Arduino. I’m not responsible for any broken Arduino or ESP8266 modules.

Simplified connection diagram

Simplified connection diagram

Mods

We need to do some modifications to the ESP8266 AT firmware, arduino bootloader and the programmer software in order to successfully use it to program the Arduino, here are the mods:

  1. I’ve added a new AT command called AT+RODI that set the module as an AP, starts the transparent server mode, configures the GPIO used for resetting the Arduino and starts a TCP server on port 1234. You can find the code on my esp8266_at fork on my github account. For a guide on how to install the toolchain, you can follow this guide. And for a script to build and program the ESP8266 you can take a look here. Note: to enter AT mode, send +++.
  2. Then I’ve modified Arduino’s bootloader to send the ” character so it can be picked up by the programmer script. You can find the modified code here. (I think this is not entirely necessary but made things easier for me) Update: After some testing, I found out that there is not necessary to modify the bootloader, you can omit this step.
  3. Lastly I’ve modified the python script programmer from sistemasorp to add support so it can work as a client connecting to the ESP8266 for programming. You can find the modified code here.

So, the steps needed are:

  1. Build modified AT firmware for the ESP8266.
  2. Program the new firmware onto the module.
  3. Compile the modified bootloader and flash it to the atmega using a programmer. I use the USBasp or the buspirate
  4. Connect via WiFi to the ESP8266’s AP. You should get an IP address like 192.168.4.100
  5. Run the following command specifying the the correct *.hex file
    ./program_rodi.py /tmp/build7763862112848895248.tmp/Blink.cpp.hex
    

Hope you found it useful!

Happy hacking!


Arduino using ATmega328p with internal 8MHz Crystal with Bus Pirate

I am working in a robotics project where keeping the cost low is crucial. So in order to reduce costs and make the robot easy to program and connect to various types of sensors easily, I choose to use an ATmega328p so I can use the Arduino enviroment but using the internal 8MHz clock.

Here are the steps I made to program the bootloader into the ATmega328p chip using the all-mighty Bus Pirate froam Dangerous Prototypes:

Connect the BP to the microcontroller according to this (add link) table.

in a terminal check the connection between the BP and the microcontroller using

avrdude -c buspirate -p m328p -v -P /dev/ttyUSB0

unlock bootloader section on the chip using

avrdude -c buspirate -p m328p -P /dev/ttyUSB0 -U lock:w:0x3f:m

go to the folder where you installed arduino with

$cd /whatever/arduino/hardware/arduino/bootloaders/atmega

and use this command to write the correct bootloader to the chip

avrdude -c buspirate -p m328p -P /dev/ttyUSB0 -U efuse:w:0x05:m -U hfuse:w:0xDA:m -U lfuse:w:0xE2:m -U flash:w:ATmegaBOOT_168_atmega328_pro_8MHz.hex

then lock again the bootloader section with

avrdude -c buspirate -p m328p -P /dev/ttyUSB0 -U lock:w:0x0F:m

now test with a ftdi chip to program with the arduino IDE


Presentación de RODI

En este video se pueden observar las primeras pruebas con el robot RoDI (Robot Didáctico Inalámbrico) desarrollado por el Club de Robótica. El mismo utiliza el entorno de programación por bloques Turtlebots desarrollado por el grupo Butiá de Uruguay y basado en TurtleBlocks.


MMA7455L accelerometer breakout board Free PCB Build

After a few problems with the local post office, I finally received my free PCBs from Dangerous Prototypes. This time I received two MMA7455L accelerometer breakout boards. It has a Freescale’s MMA7455L accelerometer in a LGA-14 package. It was not difficult to solder using the right method (a lot of patience and flux).

After the assembly, I tested both boards using the Bus Pirate and this tutorial.

Thanks to Ian and the Dangerous Prototype’s crew for the free PCBs.


Microchip anounces new cross-platform MPLAB XC compilers

Microchip has announced that it will release new cross-platform MPLAB XC C compilers by the end of March. They come in 3 versions depending on PIC family: XC8 is for 8bit, XC16 for 16bit, and XC32 for 32bit microcontrollers.

Microchip is releasing MPLAB XC C compilers in the upcoming weeks. There will be three, one for each of the major Microchip logic architectures: MPLAB XC8, MPLAB XC16 and MPLAB XC32. By the end of March, we should have all three versions available. In the same open-platform spirit as MPLAB X IDE, MPLAB XC C Compilers will run on Windows, MAC and Linux. XC compilers will come with a new license manager to make installation and license management simple across platforms. Users will be able to install the compiler on any platform of choice.
 
Via dangerousprototypes.com

Esto ya se venía viendo desde un tiempo atrás, cuando la gente de Microchip empezó a unificar varios aspectos del compilador Hitech, para hacerlo mas “parecido” al MPLAB C18.

Personalmente me parece una excelente decisión de parte de Microchip, ya que actualmente existen tres compiladores “oficiales” de microchip para la gama de 8 bits (Hitech for PIC10/12/16, Hitech for PIC18 y MPLAB C18).

Unificar estos tres facilitará enormemente la programación a los usuarios además de proveer mayor facilidad de portabilidad de código y librerías existentes entre los diferentes modelos de microcontroladores de 8 bits de Microchip.


Sumo Controller Board

Este es un proyecto que empecé hace unos meses, y es el diseño de una placa controladora para Robots Sumo (y cualquier otro tipo de Robots). Mi idea era tener en una sola placa todos los componentes y conectores necesarios para un Robot Sumo, entre los que podemos citar, servos o algún otro controlador de motores DC, sensores para medición de distancia (tanto infrarrojos como por ultrasonido), conectores para varios pulsadores/leds indicadores, etc. Además de eso, que sea sencillo para programar (entiéndase, que no se necesite un programador como el pickit 2), ya que la idea es que estas placas sean usadas por los miembros del Club de Robótica. Para esto, la placa tendría que tener un microcontrolador que pueda programarse a si mismo (bootloader).

A continuación el esquemático y una explicación algunas partes de la placa y porque elegí cada componente en particular.

Microcontrolador

Como explicaba anteriormente, la idea es que no se necesite programador para grabar los programas, por lo tanto elegí un microcontrolador que tenga incorporado un modulo USB, en este caso usé un PIC18F47J53 de la empresa Microchip. Elegí este micro además trabaja a 3.3V, esto es una ventaja ya que varios sensores y/o módulos de comunicación (Xbee) trabajan también a esta tensión, además algunos pines del pic soportan hasta 5.5 volts, lo que nos permite conectar dispositivos de 5 volts al PIC. Otra característica muy interesante de este PIC en particular, es que posee una función denominada PPS (Peripherial Pin Select), que nos permite asignar ciertas funciones del PIC (USART, CCP, I2C, SPI) a varios pines posibles (a diferencia de los micros antiguos en los que una función estaba asignada a un pin y no se podía cambiar), facilitando enormemente el ruteado de la placa.

Conectores

La placa posee headers para una facil conexión con dispositivos como servos, o varios sensores, y utiliza la misma ubicación de señales que un servo. Además se tienen otros headers que permiten conectar un sensor de distancia ultasonico, como ser el modulo SDM-IO de la empresa IteadStudio.

También ser tiene un header para la programación ICSP del micro si se quiere hacer por este método o para grabar el bootloader la primera vez, y un header para conectar un conversor USB-Serial para enviar/recibir datos a/de la PC.

El conector mini-USB nos permite conectar la placa a la PC para la grabación de los programas en en microcontrolador una vez que este posea el bootloader. También nos permite alimentar la placa para hacer pruebas, el único cuidado que debemos tener es que el puerto USB de las computadoras pueden suministrar un máximo de 500mA de corriente.

LEDs

La placa cuenta además con 6 Leds (7 en la versión actual) para realizar un debug del codigo o para mostrar algunos datos útiles. Se tiene también un led que indica que la placa está siendo alimentada y dos leds mas que nos indican si se está transmitiendo o recibiendo datos por el puerto serie.

PCB

El diseño de la placa fue hecho con la versión gratuita de Cadsoft Eagle v5.11, y el PCB lo mande a hacer en IteadStudio, utiliando su servicio Open PCB. Es un servicio muy bueno ya que te hacen 10 PCBs (double side, con soldermask a ambos lados, vias, etc.) por 10 dólares (a esto hay que sumarle el envío).

Software

El software utilizado para programar el microcontrolador es el MPLAB C18 de la misma empresa fabricante del microcontrolador, el mismo posee una versión gratuita para estudiantes y ademas nos provee librerías para los periféricos del micro. El bootloader que utilicé está basado en un ejemplo de la Microchip Application Libraries y modificado de acuerdo al hardware de las placas. Sólo la primera vez se necesita un programador (Pickit 2 / Pickit 3) para grabar el bootloader al microcontrolador.

Ya que el bootloader ocupa espacio en la memoria de programa del micro, hay que indicarle al compilador que realice unas modificaciones a la hora de compilar nuestro código. Para eso utilizamos el siguiente codigo:

extern void _startup ( void ); // See c018i.c in your C18 compiler dir
#pragma code AppFirmwareStartLocation = 0x1000

void _reset ( void )
{
	_asm goto _startup _endasm;
}
#pragma code

El código completo para encender y apagar los leds de la placa sería:

#include <p18f47j53.h>
#include <delays.h>

#pragma config WDTEN = OFF     //WDT disabled (enabled by SWDTEN bit)
#pragma config PLLDIV = 3      //Divide by 3 (12 MHz oscillator input)
#pragma config STVREN = ON     //stack overflow/underflow reset enabled
#pragma config XINST = OFF     //Extended instruction set disabled
#pragma config CPUDIV = OSC1   //No CPU system clock divide
#pragma config CP0 = OFF       //Program memory is not code-protected
#pragma config OSC = HSPLL //HS oscillator, PLL enabled, HSPLL used by USB
#pragma config FCMEN = OFF     //Fail-Safe Clock Monitor disabled
#pragma config IESO = OFF      //Two-Speed Start-up disabled
#pragma config WDTPS = 32768   //1:32768
#pragma config DSWDTOSC = INTOSCREF //DSWDT uses INTOSC/INTRC as clock
#pragma config RTCOSC = T1OSCREF//RTCC uses T1OSC/T1CKI as clock
#pragma config DSBOREN = OFF   //Zero-Power BOR disabled in Deep Sleep
#pragma config DSWDTEN = OFF   //Disabled
#pragma config DSWDTPS = 8192  //1:8,192 (8.5 seconds)
#pragma config IOL1WAY = OFF   //IOLOCK bit can be set and cleared
#pragma config MSSP7B_EN = MSK7//7 Bit address masking
#pragma config WPFP = PAGE_1   //Write Protect Program Flash Page 0
#pragma config WPEND = PAGE_0  //Start protection at page 0
#pragma config WPCFG = OFF     //Write/Erase last page protect Disabled
#pragma config WPDIS = OFF     //WPFP[5:0], WPEND, and WPCFG bits ignored

extern void _startup ( void ); // See c018i.c in your C18 compiler dir
#pragma code AppFirmwareStartLocation = 0x1000

void _reset ( void )
{
	_asm goto _startup _endasm;
}
#pragma code

void main ( void )
{
	LATC = 0xC0;
	LATD = 0x00;
	TRISC = 0x00;
	TRISD = 0x00;
	for (;;)
	{
		LATC = ~LATC;
		LATD = ~LATD;
		Delay10KTCYx(250);		// Delay for 500ms
	}
}

Hasta la próxima!


Bus Pirate v3.5 Free PCB Build

A few months ago I won a free PCB from Dangerous Prototypes. I chose the Bus Pirate v3.5 SOIC because it seems a very interesting tool. According to DP,

The Bus Pirate is an open source hacker multi-tool that talks to electronic stuff. It’s got a bunch of features an intrepid hacker might need to prototype their next project.

It uses a PIC24FJ64GA002 and some of the features listed in their webpage are:

Support for many serial protocols with line levels of 0 – 5.5 volts:

After a few months of lying in my bench, I finally decide to build it, so I bought the parts from Mouser Electronics and after a few weeks of waiting for the parts I finally assembled it. It was the first time I worked with 0603 components but it resulted to be pretty easy to solder. Also, I had some trouble soldering the FT232RL (I think I even burned it). Here are some pictures of the finished board.

This slideshow requires JavaScript.

Thanks Dangerous Prototypes!