Quantcast
Channel: Arduino Sketch – Arduining
Viewing all 10 articles
Browse latest View live

Serial Commands to Arduino ( LED control )

$
0
0

Serial_LED_control A small sketch to show how to implement a command menu using the Serial Monitor of the Arduino IDE. In this example the switch statement is used to identify the received command and execute the corresponding action.

— Command list: —

? -> Print this HELP

a -> LED On  “activate”

d -> LED Off “deactivate”

s -> LED     “status”


The SKETCH:

/*Serial_LED_02.ino  Arduining 4 May 2015
Controlling the LED in pin 13 with the Serial Monitor.
--- Command list: ---
? -> Print this HELP 
a -> LED On  "activate"
d -> LED Off "deactivate"
s -> LED     "status" 

Example using the switch statement.
*/
 
#define LED 13          // Pin 13 is connected to the LED
char rxChar= 0;         // RXcHAR holds the received command.

//=== function to print the command list:  ===========================
void printHelp(void){
  Serial.println("--- Command list: ---");
  Serial.println("? -> Print this HELP");  
  Serial.println("a -> LED On  \"activate\"");
  Serial.println("d -> LED Off \"deactivate\"");
  Serial.println("s -> LED     \"status\"");  
  }
  
//---------------- setup ---------------------------------------------
void setup(){
  Serial.begin(9600);   // Open serial port (9600 bauds).
  pinMode(LED, OUTPUT); // Sets pin 13 as OUTPUT.
  Serial.flush();       // Clear receive buffer.
  printHelp();          // Print the command list.
}

//--------------- loop ----------------------------------------------- 
void loop(){
  if (Serial.available() >0){          // Check receive buffer.
    rxChar = Serial.read();            // Save character received. 
    Serial.flush();                    // Clear receive buffer.
  
  switch (rxChar) {
    
    case 'a':
    case 'A':                          // If received 'a' or 'A':
	if (digitalRead(LED) == LOW){        // If LED is Off:
          digitalWrite(LED,HIGH);      // Turn On the LED.
          Serial.println("LED turned On");
	}
        else Serial.println("LED already On!");
        break;

    case 'd':
    case 'D':                          // If received 'd' or 'D':
	if (digitalRead(LED) == HIGH){       // If LED is On:
          digitalWrite(LED,LOW);       // Turn Off the LED.
          Serial.println("LED turned Off");
	}
        else Serial.println("LED already Off!");
        break;
        
    case 's':
    case 'S':                          // If received  's' or 'S':
	if (digitalRead(LED) == HIGH)        // Read LED status.
          Serial.println("LED status: On");
        else Serial.println("LED status: Off");
        break;
        
    case '?':                          // If received a ?:
        printHelp();                   // print the command list.
        break;
        
    default:                           
      Serial.print("'");
      Serial.print((char)rxChar);
      Serial.println("' is not a command!");
    }
  }
}
// End of the Sketch.



Arduino and Two Stepper Motors

$
0
0

 

Two_Steppers

This project consist in moving two stepper motors “simultaneously”.
Really there is a loop where both motors are moved “one step at a time” to reach their final position.
5 Volts steppers with external power source are used.

 

Here is the video in YouTube:

Here is the Sketch:

—————-

/*------------------------------------------------------
Two_Steppers.ino     Arduining.com  30 MAY 2015

Driving two steppers concurrently with the Arduino Nano.
stepperX follows potentiometer on analog input 0.
stepperY follows potentiometer on analog input 1.
A timeout is used to turn off coils and save energy in battery
operated applications.

Hardware:
Arduino NANO.
Drivers: ULN2003A
Stepper Motors: 28BYJ48, 5VDC, step angle 5.625 °
                Gear reduction 64:1
                No-load starting frequency:> = 500PPS (4 rpm)
                Coil resistance 60 Ohms.               
 -----------------------------------------------------*/

#include <Stepper.h>

#define  STEPSREV    4096    // 64(fullsteps) * 64 (reduction ratio)
#define  SPEED       4       // motor speed (RPM)

#define  COIL_1X     11
#define  COIL_2X     9
#define  COIL_3X     10
#define  COIL_4X     8

#define  COIL_1Y     7
#define  COIL_2Y     5
#define  COIL_3Y     6
#define  COIL_4Y     4

#define  POT_X       0
#define  POT_Y       1                
#define  TIMEOUT     1000    //Turns off after 1 sec of inactivity.
#define  NOISE       8       //inmunity in steps because analog noisy readings.

// create the instances of the stepper class.
Stepper stepperX(STEPSREV, COIL_1X, COIL_2X, COIL_3X, COIL_4X);
Stepper stepperY(STEPSREV, COIL_1Y, COIL_2Y, COIL_3Y, COIL_4Y);

int potValX,potValY;           // potentiometers analog readings
int Xpos,Ypos;                 // Actual steppers positions(0-4096)->(0-360°)
int newXpos, newYpos;          // New steppers positions
unsigned long stampX, stampY;  // last move time stamped.

//============== functions ====================================================

//Read the potentiometers and map the reading to mach 360 degrees.
void readPots(){
  potValX = analogRead(POT_X);          // read POT_X value (0-1023).
  potValY = analogRead(POT_Y);          // read POT_Y value (0-1023).
  newXpos= map(potValX,0,1023,0,2047);  // Map pot X range to one stepper turn.
  newYpos= map(potValY,0,1023,0,2047);  // Map pot Y range to the stepper turn.
}
 
//-----------------------------------------------------------------------------
// Aproach stepperX to the newX position.
void aproachX(int newX){
  int Xdir = Xpos<newX ? 1 : -1;
  stepperX.step(Xdir);        // move one step in the Xdir direction.
  Xpos += Xdir;               // update Xpos.
  stampX = millis();          // stamp actual time.
  }

//-----------------------------------------------------------------------------
// Aproach stepperY to the newY position.
void aproachY(int newY){
  int Ydir = Ypos<newY ? 1 : -1;
  stepperY.step(Ydir);        // move one step in the Ydir direction.
  Ypos += Ydir;               // update Ypos.
  stampY = millis();          // stamp actual time.
  }

//-----------------------------------------------------------------------------
//Check for inactivity and turn off the steppers coils to save battery.
void CheckTimeout(){
  if((millis() - stampX) > TIMEOUT){   //Turn Off StepperX coils.
    digitalWrite(COIL_1X, LOW);
    digitalWrite(COIL_2X, LOW);
    digitalWrite(COIL_3X, LOW);
    digitalWrite(COIL_4X, LOW);
  }
  if((millis() - stampY) > TIMEOUT){   //Turn Off StepperY coils.
    digitalWrite(COIL_1Y, LOW);
    digitalWrite(COIL_2Y, LOW);
    digitalWrite(COIL_3Y, LOW);
    digitalWrite(COIL_4Y, LOW);
  }    
}


//=================== setup ===================================================
void setup(){
  stepperX.setSpeed(SPEED);  // set the X motor speed.
  stepperY.setSpeed(SPEED);  // set the Y motor speed.
  readPots();
  Xpos = newXpos;
  Ypos = newYpos;
}

//================= main loop =================================================
void loop(){
  readPots();
//if diference is greater than NOISE move steppers.
  if(abs(newXpos - Xpos)> NOISE) aproachX(newXpos);
  if(abs(newYpos - Ypos)> NOISE) aproachY(newYpos);

  CheckTimeout();   //check for inactivity.

}

 

—————-

 

 

 

 

 


Interrupts with the TRINKET analog comparator

$
0
0

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

Trinket_ISR

 

/*Trinket_comp_ISR.ino  Arduining.com 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 ----------------------------
ISR(ANA_COMP_vect){  
  triggered = true;
}
  
//-----------------------------------------------------------------------------
void setup(){
 pinMode(LED,OUTPUT);
  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.
  delay(100);
  //Put the LED status as the analog comparator output (inverted)
  if(ACSR & (1<<ACO))digitalWrite(LED, LOW);
  else digitalWrite(LED, HIGH);
}

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



NodeMCU Breathing LED with Arduino IDE

$
0
0

Breathing_LED

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
-etc.

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”.

NOTE:
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 Arduining.com  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
    i--;
    delay(0);                        //to prevent watchdog firing.
  }
  delay(REST);                       //take a rest...
}


Traffic Light States Machine with Arduino

$
0
0

Traffic_Light_Intersection2

This exercise with the Arduino is inspired by the course:

Embedded Systems – Shape The World

Chapter : Finite States Machines

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

http://users.ece.utexas.edu/~valvano/Volume1/E-Book/C10_FiniteStateMachines.htm

-The C code was adjusted to the Arduino and checked with a simulator.

-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.

Definition of Inputs and Output:

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

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

Traffic_Input_Output5

Every state is described in the following form:

Traffic_Machine_State

The complete States Diagram:

Traffic_States_Diagram

The wiring diagram with the Arduino UNO:

Traffic_Light_Schematics3

An this is the Sketch running in the simulator:

/*Traffic_Light.ino        17 SEP 2015   Arduining.com
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 SwitchPin 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:http://users.ece.utexas.edu/~valvano/Volume1/E-Book/
*/
#define SENSORS  PINB      // define the ATmega328 Port to read the switches
#define LIGHTS   PORTD     // define the ATmeha 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
    delay(FSM[State].Time);
    Input = SENSORS & B00000011;     // read sensors
    State = FSM[State].Next[Input];  
}

Traffic_Simulation4

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


ESP-201 an ESP8266 breadboard friend

$
0
0

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.

 

ESP-201_presenter

 

A quick pinout reference to start the wiring:

ESP-201_pinout

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:

ESP-201_A0

 

Experimenting with different antennas:

ESP-201_Antenna_tests

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

ESP-201_A0_ThingSpeak

 

 

Experimenting with Deep Sleep:

In progress….SEP-201_DS_Wiring

Boot Modes


Wiring TFT Display to Arduino NANO

$
0
0
 Wiring Diagram:

TFT_SD_NANO_DIM_wiring

A clean approach to attach the Display to Arduino NANO:

TFT_SD_NANO_DIM_jumpers

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

TFT_SD_NANO_DIM_assembled

Reading the analog input A0:

Test_001

Plotting the analog channel A0 using vertical lines:

Test_002

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

 

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

MicroLib_03_text

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

MicroLib_03_Rect_test

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

MicroLib_A0_test_img

 

 

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

 


Simple Graph With Arduino NANO and TFT Library

$
0
0

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

simple_graph_01_4

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.

tft_sd_nano_dim_wiring

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

tft_sd_nano_dim_jumpers

 

tft_sd_nano_dim_assembled


 

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.setRotation(0);
TFTscreen.background(0,128,0);    // dark green background
TFTscreen.stroke(255,255,255);    // white stroke
analogWrite(BKLIGHT,BRIGHTNESS);  //Set brightness.
TFTscreen.setTextSize(1);
TFTscreen.text(“Arduining.com”,50,151);
drawFrame();
clearGraph();
}

void drawFrame(){
TFTscreen.stroke(255,255,255);      // white stroke
TFTscreen.fill( 255, 255, 255 );    // White fill
TFTscreen.rect(0, 0, WIDTH, 21);
TFTscreen.setTextSize(1);
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.
x_pos++;
if(x_pos > WIDTH){
x_pos=0;
delay(PERSIST);
clearGraph();
}
}

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 );
delay(10);
}

 


Thanks for visiting…



Arduino Sketch upload via Bluetooth

$
0
0

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.

blue_remoteprogramming


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

bluetooth_hc-05_status

 

Test made with an Arduino NANO clone:

wireless_sketch_upload

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

BT_RemoteProg.jpg


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.

                           __,-----,__
                          |[]|_____|[]|<===LED
   [----- (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)

/*------------------------------------------------------------------------------
  setup()
------------------------------------------------------------------------------*/
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);
    pinMode(STATPIN, INPUT_PULLUP);
    digitalWrite(RESETPIN, HIGH);  // Set RESET to High.  
}

/*------------------------------------------------------------------------------
  loop()
------------------------------------------------------------------------------*/
void loop(){
  delay(1);

	if(flag){
    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.
    delay(1);
    digitalWrite(RESETPIN, HIGH);  // Return to High.
    
    while(!flag){
      digitalWrite(LEDPIN,LOW);
      delay(500);
      digitalWrite(LEDPIN,HIGH);
      delay(500);          
      }                            // Hold until next Binding.
	}

}

/*------------------------------------------------------------------------------
  Pin Change Interrupt of pin 2 (PB2).
------------------------------------------------------------------------------*/
ISR(PCINT0_vect){
    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:

arduino3v3_remoteprogr

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.


Using Bipolar Stepper Motors With Arduino and Easy Driver

$
0
0

Controlling the NEMA 17 MERCURY SM-42BYG011-25

UNO_EasyDriver_Wiring_02

Arduino Sketch highlighted using  http://hilite.me/ :

/*EasyDriver_Test.ino  Arduining.com  6 MAY 2012

Sketch used to test the EasyDriver board from Sparkfun.com
Used in the YouTube video (Jul 15, 2012): "Arduino EasyDriver and Stepper Motor "

During the test a movement of 360 degrees (full turn) was implemented.
The stepper turns right and left alternatively.

Hardware:
-EasyDriver v4.4
  MS1 and MS2 connected to ground to select Full-Step mode.

-Stepper Motor SM-42BYG011-25 features:
  • Step Angle (degrees) :1.8
  • 2 Phase
  • Rated Voltage : 12V
  • Rated Current : 0.33A
  
*/

#define DIR   2
#define STEP  3

void advance(int steps)
{
  if(steps>0)digitalWrite(DIR, LOW); // Set clockwise direction.
  else{
    digitalWrite(DIR, HIGH);         // Set counter-clockwise direction.
    steps=abs(steps);
  }
  for (int i = 0; i<steps; i++){     // Rotate n steps.
    digitalWrite(STEP, HIGH);
    delayMicroseconds(20);           // Minimum STEP Pulse Width 1.0uS
    digitalWrite(STEP, LOW);         // Step pulse (rising edge).
    delay(10);                       // Delay between steps
  }
} 

void setup()
{
  pinMode(DIR, OUTPUT);
  pinMode(STEP, OUTPUT);
}

void loop()
{
  delay(250);
  advance(200);
  delay(250);
  advance(-200);
}


Controlling the DOWONSOL-9181 Stepper

EasyDriver_Pot_01


Arduino Sketch highlighted using  http://hilite.me/ :

/*------------------------------------------------------
EasyDriver_Pot_01.ino  Arduining 31 MAY 2015

Stepper motors following a potentiometer on analog input 0.
A software low-pass filter is used to reduce the noise in the analog reading.

The ENABLE signal is used to shut-down the current and keep the motor cold.

Hardware:
-Arduino UNO
-EasyDriver v4.4
  MS1 and MS2 connected to GND. (single stepping)
-Stepper Motor DOWONSOL:
  Model: 9181
  Voltage: 12V
  Coils impedance: 70 Ohms. (measured)
  Motor Step angle: 18 degrees
  GearBox reduction: 36:1
  Output angle/step: 0.5 degree  (720 pulses/revolution)
-Stepper Motor MERCURY:
  Model: ST-PM35-15-11C
  Voltage: 12V
  Motor Step angle: 48 degrees
  Output angle/step: 7.5 degree  (48 pulses/revolution)

 -----------------------------------------------------*/
#define MS1   12
#define MS2   11
#define STEP  10
#define DIR   9
#define EN    8

#define POT   0
#define TURN  720      //number of steps per revolution (DOWONSOL)
//#define TURN  48      //number of steps per revolution (MERCURY)
int potVal,targetPos;
int lastPot=0;
int actualPos=0;

void pulse(){
    digitalWrite(STEP, HIGH);
    delayMicroseconds(20);         // Minimum STEP Pulse Width 1.0uS
    digitalWrite(STEP, LOW);       // Step pulse (rising edge).
} 

void setup()
{
  pinMode(DIR, OUTPUT);
  pinMode(STEP, OUTPUT);
  pinMode(MS1, OUTPUT);
  pinMode(MS2, OUTPUT);
  pinMode(EN, OUTPUT);
  
  digitalWrite(MS1, LOW);          // Full step selected
  digitalWrite(MS2, LOW);          // Full step selected
  digitalWrite(EN, HIGH);          // Disable the A3967 IC.
}

void loop()
{
  potVal = analogRead(POT);       // Potentiometer value range 0-1023
  potVal= potVal * 0.1 + lastPot * 0.9 ;  // Filtering to reduce noise.
  lastPot= potVal;
  targetPos= map(potVal,0,1023,0,TURN);   // Map pot range in the stepper range.
  if(abs(targetPos - actualPos)> 1){      //if diference is greater than 1 step.
      digitalWrite(EN, LOW);              // Enable the A3967 IC.
      if((targetPos - actualPos)> 0){
          digitalWrite(DIR, LOW);         // Set counter-clockwise direction.
          pulse();                        // move one step to the right.
          actualPos++;
          }
      else{
          digitalWrite(DIR, HIGH);        // Set counter-clockwise direction.
          pulse();                        // move one step to the right.
          actualPos--;
      }
  }
  delay(5);
  digitalWrite(EN, HIGH);                 // Disable the A3967 IC.
}

Youtube video:

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




Viewing all 10 articles
Browse latest View live