Archive for the ‘Arduino Sketch’ Category

Arduino Sketch upload via Bluetooth

October 5, 2016 Leave a comment

After a Smart Robot Kit assembly :

ROBOT_Assembly (1).jpg

Start looking for a way to upload Sketches to the Arduino  wirelessly.

After some Internet searching… decided to go deeper and understand how the HC-06 Bluetooth module works and how is the upload process.

In the HC-06, the STATUS signal indicates when a Bluetooth bind condition is established.

After look at the signal,  the first idea was to use an LM555 as a resettable monostable multivibrator… ok,  an 8 pin DIP IC and several passive components….

Then why no use an ATTINY85 to do the work?

Here is the proof of concept using an Adafruit’s TRINKET 3.3V.


The TRIKET checks the behavior of the STATE signal to identify the bind condition and generates the RESET pulse.



Test made with an Arduino NANO clone:


Testing Arduino Duemilanove (same HC-06 configuration, 57600 bauds):


The Sketch used in the TRINKET:

/*Trinket_BlueReset.ino   Arduining 4 OCT 2016
 Using TRINKET to generate the RESET for Remote Arduino Programming.
 -HC-06 BlueTooth Module as Slave 115200 bauds (UNO, Optiboot loader) 
 -HC-06 BlueTooth Module as Slave 57600 bauds (Duemilanove, NANO)
 -Using the STATUS pin of The HC-06 to identify a Binded condition.
 -The TRINKET LED (pin 1) show the Bluetooth condition:
          5 Hz Not Binded, 1 Hz Binded.

 -STATPIN is the STATUS signal from HC-06 (pin 24).
 -RESETPIN is the RESET signal to start the bootloader in the Arduino.
             |<--200mSeg-->|             |<120mSeg>|
              ______        ______        _______________________________
   STATPIN __|      |______|      |______|
           --------------  Not Binded ------------>|<----- Binded -------
            _______________________________________ _____________________
   RESETPIN                                        |

  -If no changes in STATPIN for 120 milliseconds a RESETPIN pulse is generated.

   [----- (4.3-16)V ----->|o         o|[---- +USB(+5V 500mA) ---->
   <-------- GND -------->|o         o|<PB0>-<0>-[0A>-<SDA>-[MOSI>  ==> RESETPIN
   USB-<4A]-[A4>-<4>-<PB4>|o TRINKET o|<PB1>-<1>-[1A>-------<MISO]-LED>
   USB------[A3>-<3>-<PB3>|o         o|<PB2>-<2>-<A1]-[SCL>-[SCK >  <== STATPIN
   [-------- RESET------->|o         o|+3.3V(150mA)Reg. from BAT->
                          |   [( )] __|
                  Trinket (3.3V) Pinout Diagram  


#define LEDPIN     1               // LED PIN for signaling.
#define RESETPIN   0               // Attached to the RESET pin of the Arduino.
#define STATPIN    2               // Attached to the STATUS pin of the HC-06
volatile bool flag= false;
int pulseTimer= 120;               // Waiting time for pulses in STATPIN (mSeg)

void setup(){
    GIMSK = 0b00100000;            // turns on pin change interrupts
//    PCMSK = 0b00010011;          // turn on interrupts on pins PB0, PB1, & PB4
    PCMSK = 0b00000100;            // turn on interrupts on pin 2 (PB2)
    sei();                         // enables interrupts
    pinMode(LEDPIN, OUTPUT);    
    pinMode(RESETPIN, OUTPUT);
    digitalWrite(RESETPIN, HIGH);  // Set RESET to High.  

void loop(){

    pulseTimer=120;                // Reset waiting time for pulses in STATPIN.
    flag = false;
  else pulseTimer--;
	if(pulseTimer == 0){
    //Here we can check for a '0' in the serial channel (57600 bauds).
	  digitalWrite(RESETPIN, LOW);   // Produce a RESET pulse of 1 millisecond.
    digitalWrite(RESETPIN, HIGH);  // Return to High.
      }                            // Hold until next Binding.


  Pin Change Interrupt of pin 2 (PB2).
    flag = true;                   // signals the change in pin 2.
    digitalWrite(LEDPIN,digitalRead(STATPIN));   //Signaling the HC-06 STATUS.
    sei();                         // enables interrupts


If the Arduino to be programmed works with 3.3V the wiring is simpler:


Now we can program the Arduino without the USB cable. Also we can control the robot remotely via Bluetooth, just remember to use  Serial.begin(57600) in your control program  ….

Any additional ideas will be appreciated,

Thanks for visiting this blog.

Simple Graph With Arduino NANO and TFT Library

September 7, 2016 Leave a comment

This is a simple plotting example to experiment with the TFT Library and the LCD Display with the ST7735 controller (128×160 pixels).


First, a clean wiring diagram to connect the Arduino NANO and the Display. The SD Card adapter was wired  (CS and MISO) but not used in this Sketch.


Then, a wiring plan to put them together in the breadboard:





The Sketch:


/*TFT_Graph.ino      Arduining 7 AUG 2016

-Arduino NANO and ST7735 LCD Display 128×160
-using TFT library
-Brighness control in pin 6
-offset is used to adjust vertical position of the graph.

#include <TFT.h>
#include <SPI.h>

//pin definitions:
#define CS          10
#define DC           9
#define RST          8
#define BKLIGHT      6              // Backlight control pin

#define BRIGHTNESS 204              // Backlight intensity (0-255)
#define RANGE      100              // Vertical size of the graph in pixels.
#define WIDTH      128              // Horizontal size of Display in pixels.
#define HEIGHT     160              // Vertical size of Display in pixels.
#define PERSIST    500              // persistence of the graph (milliseconds).

TFT TFTscreen = TFT(CS, DC, RST);

int value ;
int last_value;
int x_pos= 0;                       // cursor position
int offset= 40;                     // vertical graph displacement in pixels.

void setup(){
TFTscreen.begin();                // initialize the display
TFTscreen.background(0,128,0);    // dark green background
TFTscreen.stroke(255,255,255);    // white stroke
analogWrite(BKLIGHT,BRIGHTNESS);  //Set brightness.

void drawFrame(){
TFTscreen.stroke(255,255,255);      // white stroke
TFTscreen.fill( 255, 255, 255 );    // White fill
TFTscreen.rect(0, 0, WIDTH, 21);
TFTscreen.stroke(0,0,0);            // black text
TFTscreen.text(“Volts: 1.0V/Div”,2,2);  // Example text.
TFTscreen.text(“Time:  10mS/Div”,2,12); // Exanple text
void clearGraph(){
TFTscreen.stroke(127,127,127);      // grey for the border
TFTscreen.fill( 180, 0, 0 );        // dark Blue for the background
TFTscreen.rect(0, 22, 128, 128);
TFTscreen.line(65, 23, 65, 151);    // vertical line
TFTscreen.line(1, 85,127, 85);      // horizontal line
TFTscreen.stroke(0,255,255);        // yellow stroke for plotting.

void plotLine(int last,int actual){
if(x_pos==0)last= actual;                     // first value is a dot.
TFTscreen.line(x_pos-1, last, x_pos, actual); // draw line.
if(x_pos > WIDTH){

void loop(){
last_value= value;
value= analogRead(A0);
value= map(value,0,1023,149,23);
value -= offset;
if(value <= 23) value= 23;         //truncate off screen values.
plotLine(last_value ,value );


Thanks for visiting…

Wiring TFT Display to Arduino NANO

August 27, 2016 2 comments
 Wiring Diagram:


A clean approach to attach the Display to Arduino NANO:


 All the components in place. SD Card adapter also is connected to the Arduino.


Reading the analog input A0:


Plotting the analog channel A0 using vertical lines:


A small video to show the wiring while enjoying a Tchaikovsky’s  Waltz:


Testing my small library. 5×7 font in different sizes.


Testing drawRect() and fillRect() of the small library:


 Using the small library to show A0 value and his histogram:




… this post is in progress… some code and examples…


ESP-201 an ESP8266 breadboard friend

December 31, 2015 Leave a comment

To plug the ESP-201 in the breadboard is necessary to remove the 4 pin connector from the botton of the board and install it in the component side.




A quick pinout reference to start the wiring:


Note: GPIO9 and GPIO10 are connected to the FLASH memory (may be unusable). Here is a “surgery” procedure to use them: ESP-201 board modification

First experiment sending the analog value from A0 to ThingSpeak:



Experimenting with different antennas:


Best results with the external antenna (the metal one):




Experimenting with Deep Sleep:

In progress….SEP-201_DS_Wiring

Boot Modes

Traffic Light , Finite State Machine with Arduino

September 18, 2015 1 comment


This exercise with the Arduino is inspired by the course:

Embedded Systems – Shape The World

Chapter : Finite State Machines

By Dr. Jon Valvano , professor in the Department of Electrical and Computer Engineering at The University of Texas.

-The C code was adjusted to run in the Arduino UNO.

-Some changes were made in labels for better understanding.

-Most of the time was dedicated to make clear ilustrations and diagrams.

As the chapter explain, the Ojetive is:

Design a traffic light controller for the intersection of two equally busy one-way streets.

The goal is to maximize traffic flow, minimize waiting time at a red light, and avoid accidents.

Traffic light Controller using two sensors and 6 lights.

Two sensors detects the presence of cars in each direction.

Two traffic lights (Red,Yellow,Green) to control the traffic flow.

List heuristics describing how the traffic light is to operate:

-If no cars are coming, stay in a GREEN state. (which one doesn’t matter).

-To change from GREEN to RED, implement a YELLOW light of 0.5 seconds.

-GREEN lights will last at least 3 seconds.

-If cars are only coming in one direction, move to and stay GREEN in that direction.

-If cars are coming in both directions, cycle through all four states.

General System Diagram:


Definition of Inputs and Output:

Two Inputs from Switches detecting presence of cars in each direction.

Six Outputs to control the Lights ( RED, YELLOW, GREEN) in each direction.


Finite State Machine Transition Table

Four states are defined:

State O: goS    Cars going in South Direction GREEN signal, West Direction with RED signal.

State 1: waitS  Cars waiting in South Direction YELLOW signal, West Direction with RED signal.

State 2: goW    Cars going in West Direction GREEN signal, South Direction with RED signal.

State 3: waitW  Cars waiting in South Direction YELLOW signal, South Direction with RED signal.


Every state is described graphically in the following form:


The complete Finite State Machine Diagram:


The wiring diagram with the Arduino UNO:


This is the Sketch :

/*Traffic_Light.ino        17 SEP 2015
Implementing the traffic light controller using Finite State Machines modeling.
Using Direct Port Manipulation in the Arduino UNO.
Creating a Data Structure in C.
Port B pins 0 and 1 as inputs (Arduino pins 8 and 9):
Pin 8 = North Switch
Pin 9 = East Switch
Port D pins 2 to 7 as outputs (Arduino pins 2 to 7):
Pin 2 = North Red light
Pin 3 = North Yellow light
Pin 4 = North Green light
Pin 5 = East Red light
Pin 6 = East Yellow light
Pin 7 = East Green light
Based in: Finite State MachinesFrom:
#define SENSORS  PINB      // define the ATmega328 Port to read the switches
#define LIGHTS   PORTD     // define the ATmega328 Port to drive the lights
// Linked data structure
struct State {
  int Out; 
  int Time;  
  int Next[4];}; 
typedef const struct State STyp;
#define goS   0
#define waitS 1
#define goW   2
#define waitW 3
STyp FSM[4]={
 {0x21,3000,{goS,waitS,goS,waitS}},       //State 0 (goS)   go South.
 {0x22, 500,{goW,goW,goW,goW}},       //State 1 (waitS) wait South.
 {0x0C,3000,{goW,goW,waitW,waitW}},    //State 2 (goW)   go West.
 {0x14, 500,{goS,goS,goS,goS}}};        //State 3 (waitW) wait West.
int State;  // index to the current state 
int Input; 

void setup(){
  DDRB &= B11111100;  // Port B pins 0 and 1 as inputs (Arduino pins 8 and 9)
  DDRD |= B11111100;  // Port D pins 2 to 7 as outputs (Arduino pins 2 to 7)

void loop(){
    LIGHTS = (FSM[State].Out)<<2;    // set lights
    Input = SENSORS & B00000011;     // read sensors
    State = FSM[State].Next[Input];  


Any comment to improve this presentation will be appreciated, thanks for visiting

NodeMCU Breathing LED with Arduino IDE

August 20, 2015 15 comments


The first sketch used to test an Arduino compatible board is Blink.
After run Blink in my new NodeMCU Development Kit,
Started experiments with the WiFi connection:
-Mini servers to control leds, servos, etc..
-Send light intensity and temperature to ThingSpeak, Xively, Plotly etc..
-Serial data bridges

The blue led in the board was used to signal the execution of a particular procedure.
Because the GPIO16 (DO) limitation to use the analogWrite() and looking to see my LED doing something else…

Inspired by the Apple’s “breathing” pattern used for the sleep indicator.
Here is the code to generate a “breathing LED”.

The Arduino code runs inside a multitasking application, the ESP8266 is running at the same time TCP and WiFi stacks.
The sketch can breake the multitasking execution if your code runs in a blocking section.
The delayMicroseconds() is one of those blocking functions, delay(0)  was used to prevent watchdog reset inside the PWM loops.

/*LED_Breathing.ino  20 AUG 2015
Using NodeMCU Development Kit V1.0
Going beyond Blink sketch to see the blue LED breathing.
A PWM modulation is made in software because GPIO16 can't
be used with analogWrite().

#define LED     D0        // Led in NodeMCU at pin GPIO16 (D0).
#define BRIGHT    350     //max led intensity (1-500)
#define INHALE    1250    //Inhalation time in milliseconds.
#define PULSE     INHALE*1000/BRIGHT
#define REST      1000    //Rest Between Inhalations.

//----- Setup function. ------------------------
void setup() {                
  pinMode(LED, OUTPUT);   // LED pin as output.    

//----- Loop routine. --------------------------
void loop() {
  //ramp increasing intensity, Inhalation: 
  for (int i=1;i<BRIGHT;i++){
    digitalWrite(LED, LOW);          // turn the LED on.
    delayMicroseconds(i*10);         // wait
    digitalWrite(LED, HIGH);         // turn the LED off.
    delayMicroseconds(PULSE-i*10);   // wait
    delay(0);                        //to prevent watchdog firing.
  //ramp decreasing intensity, Exhalation (half time):
  for (int i=BRIGHT-1;i>0;i--){
    digitalWrite(LED, LOW);          // turn the LED on.
    delayMicroseconds(i*10);          // wait
    digitalWrite(LED, HIGH);         // turn the LED off.
    delayMicroseconds(PULSE-i*10);  // wait
    delay(0);                        //to prevent watchdog firing.
  delay(REST);                       //take a rest...

Interrupts with the TRINKET analog comparator

July 12, 2015 Leave a comment

Here I’m sharing a working example using the analog comparator of the Adafruit’s  TRINKET (ATtiny85).



/*Trinket_comp_ISR.ino 12 JUL 2015
  Sketch to test interrupts fron the analog comparator.
  2.5 Volt in ANI0 (voltage divider).
  Potentiometer input in ANI1  An interrupt is generated in every change of the comparator output (toggle).
  The interrupt set the flag  "triggered".
  The main loop program checks for the flag, if the flag is set, test the output value  of the comparator
  and modify the state of the LED according.*/

#define LED 4 

volatile boolean triggered=false;

//------------ Analog Comparator Interrupt Routine ----------------------------
  triggered = true;
void setup(){
  ADCSRB &= ~(1<<ACME);             //Set AIN1 as the negative input (Potentiometer).
  DIDR0 |= (1<<AIN1D)|(1<<AIN0D);   // disable digital inputs.
//ACSR – Analog Comparator Control and Status Register   
  ACSR = B00001000; // comparator interrupt enabled and tripped on toggle. (compare with AN1)
      //  ||||||||_ ACIS0 ACIS1, ACIS0: Analog Comparator Interrupt Mode Select
      //  |||||||__ ACIS1 10= falling edge; 11= raising edge; 00= toggle.
      //  ||||||___ ACIC  Reserved Bit
      //  |||||____ ACIE  Interrupt Enable
      //  ||||_____ ACI   Analog Comparator Interrupt Flag (R/W), write 1 to clear it.
      //  |||______ ACO   Analog Comparator Output (read only)
      //  ||_______ ACBG  1= Bandgap Select (1.1V); 0= compare with AIN0 (pin 6)
      //  |________ ACD   Analog Comparator Disable

  digitalWrite(LED, HIGH);//LED on for 100 milliseconds.
  //Put the LED status as the analog comparator output (inverted)
  if(ACSR & (1<<ACO))digitalWrite(LED, LOW);
  else digitalWrite(LED, HIGH);

void loop(){
    if(ACSR & (1<<ACO))digitalWrite(LED, LOW);
    else digitalWrite(LED, HIGH);
    triggered= false;