Arduino templates
================Run_An_Arduino_Program=============================
<— Open
This Program
Get An Open Window to load in the code.
===============Board_Code===========
int ledPin = 13; // LED connected to digital pin 13
void setup()
{ pinMode(ledPin, OUTPUT); // initialize the digital pin as an output:
}
void loop()
{ digitalWrite(ledPin, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(ledPin, LOW); // set the LED off
delay(1000); // wait for a second
}
=================Cut_Paste_And_Compile======================
=====================UpLoad_To_Board=====================
====================To_Stop_The_Board=======================
The Code will begin to run after uploaded.
The menu provides a way to stop the Board.
================Print_to_Serial====================================
void setup()
{ Serial.begin( 9600); // set baud
Serial.println( "ASCII Table ~ Character Map"); // prints title with ending line break
} // setup() end
int thisByte = 33; // alternative int thisByte = '!';
void loop()
{ Serial.print( thisByte, BYTE); // print ASCII, so 33, will show up as '!'
Serial.print( ", dec: ");
Serial.print( thisByte); // Decimal is default format for Serial.print()
Serial.print( ", hex: ");
Serial.print( thisByte, HEX); // prints value as hexadecimal
Serial.print( ", oct: ");
Serial.print( thisByte, OCT); // prints value as string in octal
Serial.print( ", bin: ");
Serial.println( thisByte, BIN); // prints value as binary
if (thisByte == 126)
{ while( true) { continue; } // stop at thisByte == 126
} thisByte++;
} // loop() end
This example shows how to print to the serial port.
Set the serial monitor on to view output.
================H_Key_Enables_Print_to_Serial=============================
int incomingByte; // a variable to read incoming serial data into
void setup()
{ Serial.begin( 9600); // set baud
Serial.println( "ASCII Table ~ Character Map"); // prints title with ending line break
} // setup() end
int thisByte = 33; // alternative int thisByte = '!';
void loop()
{ if (Serial.available() > 0) // see if incoming serial data:
{ incomingByte = Serial.read(); // read oldest byte in serial buffer:
if (incomingByte == 'H') // if H (ASCII 72), printoutput
{ Serial.print( thisByte, BYTE); // print ASCII, so 33, will show up as '!'
Serial.print( ", dec: ");
Serial.print( thisByte); // Decimal is default format for Serial.print()
Serial.print( ", hex: ");
Serial.print( thisByte, HEX); // prints value as hexadecimal
Serial.print( ", oct: ");
Serial.print( thisByte, OCT); // prints value as string in octal
Serial.print( ", bin: ");
Serial.println( thisByte, BIN); // prints value as binary
if (thisByte == 126)
{ while( true) { continue; } // stop at thisByte == 126
} thisByte++;
} // if (incomingByte == 'H') end
} // if (Serial.available() > 0) end
} // loop() end
This example shows how to send a serial control to the serial port.
Set the serial monitor on to view output.
Need to type a "H" to get output.
==============Send_Analog_to_Serial============================
void setup()
{ Serial.begin( 9600); // initialize the serial communication:
}
void loop()
{ Serial.println( analogRead(0)); // send the value of analog input 0:
delay( 10); // to stabilize adc:
}
==============To_Monitor_Serial=============================
Can Monitor Serial
Using Analog0
This example shows how to send ADC data from Analog0 to the serial port.
Set the serial monitor on to view output.
================Using_Processing_To_Read_Serial==================
Open This Program
Get An Open Window.
================Arduino_Code_To_Read/Display_Serial===========
void setup()
{ Serial.begin( 9600); // initialize the serial communication:
}
void loop()
{ Serial.println( analogRead(0)); // send the value of analog input 0:
delay( 10); // to stabilize adc:
}
================Processing_Code_To_Read/Display_Serial==============
import processing.serial.*;
Serial myPort; // The serial port
int xPos = 1; // horizontal position of the graph
void setup ()
{ size( 400, 300); // set the window size:
println( Serial.list()); // List all the available serial ports
myPort = new Serial(this, Serial.list()[0], 9600 ); // initialize to 9600 baud
myPort.bufferUntil('\n'); // no serialEvent() unless newline character:
background(0); // set inital background:
} // end setup
void draw () { } // everything happens in the serialEvent()
void serialEvent (Serial myPort)
{ String inString = myPort.readStringUntil('\n'); // get the ASCII string:
if (inString != null)
{ inString = trim(inString); // trim off any whitespace:
println( inString);
float inByte = float(inString);
inByte = map(inByte, 0, 1023, 0, height); // convert to int at screen height:
stroke( 127,34,255); // set color used to draw
line( xPos, height, xPos, height - inByte); // draw the line:
if (xPos >= width)
{ xPos = 0; // if edge screen, go back beginning:
background( 0); // or like background(#FFCC00)
} else
{ xPos= xPos+1; // increment the horizontal position:
} // end if (xPos >= width)
} // end if (inString != null)
} // end serialEvent
================CUT_PASTE_Run_Processing_Code==========================
=============Analog0_Open_Input_Displayed==========================
This example shows serial data can be displayed like a scope.
The Processing application can read the serial data and display it.
Notice that there is separate code for the Arduino board and
the Processing application.
Notice the 60Hz which results from having an Open Input.
===============Read/Display_Analog_At_Max_Baud===========
===============Arduino_Code======================================
void setup()
{ Serial.begin( 115200); // initialize to max baud
}
void loop()
{ Serial.println( analogRead(0)); // send the value of analog input 0:
}
===============Processing_Code===================================
import processing.serial.*;
Serial myPort; // The serial port
int xPos = 1; // horizontal position of the graph
void setup ()
{ size( 400, 300); // set the window size:
println( Serial.list()); // List all the available serial ports
myPort = new Serial(this, Serial.list()[0], 115200); // initialize to max baud
myPort.bufferUntil('\n'); // no serialEvent() unless newline character:
background(0); // set inital background:
} // end setup
void draw () { } // everything happens in the serialEvent()
void serialEvent (Serial myPort)
{ String inString = myPort.readStringUntil('\n'); // get the ASCII string:
if (inString != null)
{ inString = trim(inString); // trim off any whitespace:
println( inString);
float inByte = float(inString);
inByte = map(inByte, 0, 1023, 0, height); // convert to int at screen height:
stroke( 127,34,255); // set color used to draw
line( xPos, height, xPos, height - inByte); // draw the line:
if (xPos >= width)
{ xPos = 0; // if edge screen, go back beginning:
background( 0); // or like background(#FFCC00)
} else
{ xPos= xPos+10; // increment the horizontal position:
} // end if (xPos >= width)
} // end if (inString != null)
} // end serialEvent
===============Processing_Display======================================
The ADC is 10Bit @100us. That is a 10KHz rate. But the data is being
shipped serially at 115200 baud. Using 60Hz as a reference, looks like
about 20 data points are being displayed over a 60Hz cycle. That is
about a 1200Hz data rate. The overall Sample rate appears to be set by
the serial data rate.
=================Save_Analog_Data_To_A_File===========================
=================Arduino_Code======================================
void setup()
{ Serial.begin( 9600); // initialize the serial communication:
}
void loop()
{ Serial.println( analogRead(0)); // send the value of analog input 0:
delay( 10); // to stabilize adc:
}
=================Processing_Code===================================
import processing.serial.*; // Inport library
Serial myPort; // create serial port
String fstr = " "; // create global string
void setup()
{ println( Serial.list()); // List all the available serial ports
myPort = new Serial(this, Serial.list()[0], 9600); // Open port Arduino case #0)
myPort.bufferUntil( '\n'); // no serialEvent unless newline
} // end setup()
void draw () { } // everything happens in serialEvent()
void serialEvent (Serial myPort)
{ String inString = myPort.readStringUntil('\n'); // get the ASCII string:
if (inString != null) // received a value
{ inString = trim(inString); // trim off any whitespace:
if (key == 'w' ) // s key writes data
{ println( inString); // view inString data
fstr = fstr +inString +" "; // append with a space between
println( fstr); // view fstr data
} // end if (key == 'w' )
if (key == 's' ) // s key saves data
{ String[] list = split(fstr, " "); // create a list
saveStrings( "data.txt", list); ; // write list to a file
} // end if (key == 's' )
} // end if (inString != null)
} // end serialEvent()
=================Processing_Display===================================
To control the sampling, put the mouse in grey square for keys to work.
Type "w" to start writing data to a string.
Type "s" to save string at "data.txt".
=================View_Data===================================
The data will be stored at a strange location.
Use the menu to find Sketch folder.
Modify the processing code as desired format for spreadsheets etc...
==============Using_A_Function_in_Arduino================
void setup() // setup is always run first
{ Serial.begin( 9600); // initialize serial port
} // end of setup()
void loop() // where all code happens
{ int i = 2;
int j = 3;
int k;
k = myMultiplyFunction(i, j); // call function such that k = 6
Serial.println( k); // print k on serial port
delay( 500); // delay 500msec
} // end of loop
int myMultiplyFunction(int x, int y) // declare function with int output
{ int result;
result = x * y;
return result; // Terminates function and return a value
buggy code // this code will never be executed
} // end of myMultiplyFunction
Arduino runs only setup() and loop(). But functions can be called.
================Mouse_Over_Control_Using_Serial_Port=============================
================Arduino_Code======================================
const int ledPin = 13; // the pin that the LED is attached to
int incomingByte; // a variable to read incoming serial data into
void setup()
{ Serial.begin( 9600); // initialize serial communication:
pinMode( ledPin, OUTPUT); // initialize the LED pin as an output:
}
void loop()
{ if (Serial.available() > 0) // see if there's incoming serial data:
{ incomingByte = Serial.read(); // read the oldest byte in the serial buffer:
if (incomingByte == 'H') // if it's a capital H (ASCII 72), turn on the LED:
{ digitalWrite( ledPin, HIGH);
}
if (incomingByte == 'L') // if it's an L (ASCII 76) turn off the LED:
{ digitalWrite( ledPin, LOW);
}
}
}
=================Processing_Code===================================
import processing.serial.*;
float boxX;
float boxY;
int boxSize = 20;
boolean mouseOverBox = false;
Serial port;
void setup()
{ size( 200, 200);
boxX = width/2.0;
boxY = height/2.0;
rectMode( RADIUS);
println( Serial.list()); // List all the available serial ports
port = new Serial(this, Serial.list()[0], 9600); // Open port Arduino case #0)
}
void draw()
{ background( 0);
if (mouseX > boxX-boxSize &&
mouseX < boxX+boxSize &&
mouseY > boxY-boxSize &&
mouseY < boxY+boxSize)
{ mouseOverBox = true; // Test if the cursor is over the box
stroke( 255); // draw a line around the box and change its color:
fill( 153);
port.write( 'H'); // send an 'H' to indicate mouse is over square:
} else
{ stroke( 153); // return the box to it's inactive state:
fill( 153);
port.write( 'L'); // send an 'L' to turn the LED off:
mouseOverBox = false;
} rect( boxX, boxY, boxSize, boxSize); // Draw the box
}
=================Processing_Display===================================
>MouseOver>
As you mouse over the center square,
the LED on pin 13 should turn on and off.
===============Read_Write_Analog=============================
int ledPin = 13; // LED connected to digital pin 13
int analogPin = 0; // potentiometer connected to analog pin 0
int val = 0; // variable to store the read value
void setup()
{ pinMode( ledPin, OUTPUT); // sets the pin as output
}
void loop()
{ val = analogRead(analogPin); // analogRead 0->1023 @100us
analogWrite( ledPin, val / 4); // analogWrite 0->255 @490 Hz
}
The Arduino can do a 10bit ADC @10Khz, but its analog output is really
a digital pin running at 490Hz 8Bits PWM.
===============Read_Write_Serial_decimal=============================
int incomingByte = 0; // for incoming serial data
void setup()
{ Serial.begin( 9600); // opens serial port, sets data rate to 9600 bps
}
void loop()
{ if (Serial.available() > 0) // send data only when you receive data:
{ incomingByte = Serial.read(); // read the incoming byte:
Serial.print( "I received: "); // prints without line feed
Serial.println( incomingByte, DEC); // prints ascii code numeber
}
}
The Arduino has several ways to transmit the data.
===============Read_Write_Serial_Char=============================
void setup()
{ Serial.begin( 9600);
}
void loop()
{ if (Serial.available()) // bytes_in_buffer=Serial.available()
{ int inByte = Serial.read();
Serial.print( inByte, BYTE); // print char with ascii code
}
}
A string can be printed without line feeds.
===============Read_Pulse_Width=============================
int pin = 7;
unsigned long duration_us = 0; // pulse_time_us to be measured
unsigned long timeout_us = 1000000; // maximun time_us to look is 1sec
void setup()
{ pinMode( pin, INPUT); // threehold Low <2V->3V< High
Serial.begin( 9600);
}
void loop()
{ duration_us = pulseIn(pin, HIGH, timeout_us); //start@high , meas@Low (10us->3min) 0 if timeout
Serial.println( duration_us);
}
An Open Input and a finger can trigger the timming.
===============Send_Serial_Out=============================
// ____________
// __| \/ |__
// Q1 |__| |__|VCC 1 Q1 parallel data output
// __| |__ 2 Q2 parallel data output
// Q2 |__| |__|Q0 3 Q3 parallel data output
// __| |__ 4 Q4 parallel data output
// Q3 |__| |__|DS 5 Q5 parallel data output
// __| |__ 6 Q6 parallel data output
// Q4 |__| 595 |__|/OE 7 Q7 parallel data output
// __| |__ 8 GND ground (0V)
// Q5 |__| |__|ST_CP 9 Q7' serial data output
// __| |__ 10 MR master reset (active LOW)
// Q6 |__| |__|SH_CP 11 SH_CP shift register clock input
// __| |__ 12 ST_CP storage register clock input
// Q7 |__| |__|/MR 13 OE output enable (active LOW
// __| |__ 14 DS serial data input
// GND|__| |__|Q7' 15 Q0 parallel data output
// |____________| 16 VCC positive supply voltage
int latchPin = 8; //Pin connected to ST_CP of 74HC595
int clockPin = 12; //Pin connected to SH_CP of 74HC595
int dataPin = 11; //Pin connected to DS of 74HC595
void setup()
{ pinMode( latchPin, OUTPUT); // Outputs are not short circuit proof
pinMode( clockPin, OUTPUT); // Outputs are +/-40mA
pinMode( dataPin, OUTPUT);
}
void loop()
{ for (int j = 0; j < 256; j++) // count up routine
{ digitalWrite( latchPin, LOW); // ground latchPin when transmitting
shiftOut( dataPin, clockPin, LSBFIRST, j); // write j (one Byte) to output LSBFIRST
digitalWrite( latchPin, HIGH); // latchPin high when done
delay( 1000);
}
}
Up until now, translating between serial and parallel was not as easy.
===============Sending_Two_Bytes_Serial_Out=============================
int data; // integers holds two bytes (16bits)
data = 500; // Instead do this for MSBFIRST serial
shiftOut( data, clock, MSBFIRST, (data >> 8)); // " >> " bitshift moves (high byte) into low byte
shiftOut( data, clock, MSBFIRST, data); // shift out lowbyte
data = 500; // And do this for LSBFIRST serial
shiftOut( data, clock, LSBFIRST, data); // shift out lowbyte
shiftOut( data, clock, LSBFIRST, (data >> 8)); // shift out highbyte
And then there is the question of "which byte comes first"?
===============16Bit_Dac_Serial_Example=============================
// AD420 Serial Input 16bit DAC ^ VCC
// /_\
// _____ _______|
// _|_ _|_ | | |
// /// ___ ___________ _|_ _|_ |
// | | | ___ ___ |
// |_[2] ADC420 [20]__| | |
// | | | | |
// ___ |_[5] [21]______| |
// _|_ | | | |
// /// |____[4] [23]__________|
// | | ___
// CLEAR____[6] [18]_______________|OUT|
// | | | |___|
// LATCH____[7] [11]_______/\ __|
// | | | \/
// CLOCK____[8] [15]__ |
// | | | _|_
// DATA ____[9] [14]__| ///
// |___________|
//
#define CLOCK 8
#define DATA 9
#define HALF_CLOCK_PERIOD 1 // 2 uS of clock period (sample rate = 30.3 KHz)
uint16_t j= 0; // Notice the special format
void setup()
{ pinMode( DATA, OUTPUT);
pinMode( CLOCK,OUTPUT);
pinMode( LATCH,OUTPUT);
digitalWrite( DATA, LOW);
digitalWrite( CLOCK,LOW);
digitalWrite( LATCH,LOW);
}
void writeValue(uint16_t value)
{ digitalWrite( LATCH,LOW); // start of sequence
digitalWrite( CLOCK,LOW);
for (int i=15;i>=0;i--) // sending 16 bit sample data
{ digitalWrite( DATA,((value&(1<<i)))>>i);
delayMicroseconds(HALF_CLOCK_PERIOD);
digitalWrite( CLOCK,HIGH);
delayMicroseconds(HALF_CLOCK_PERIOD);
digitalWrite( CLOCK,LOW);
} // end sending 16 bit sample data
digitalWrite( DATA,LOW);
digitalWrite( CLOCK,LOW);
digitalWrite( LATCH,HIGH);
delayMicroseconds(HALF_CLOCK_PERIOD);
digitalWrite( LATCH,LOW);
} // end writeValue
void loop()
{ for (j=0;j<65535;j+=5) // 0 to 5V triangular waveform
{ writeValue( j);
} // end ramp up
for (j=0;j<65535;j+=5)
{ writeValue( 65535-j);
} // end ramp down
}
This is a good template on how to do a serial interface with any mixed
signal IC.
===============An_8Bit_ADC_Serial_Application=============================
Sampling Mixed signal ICs is a little different than sampling
an Op Amp. While a mixed signal like the ADCV0831 requires very few
external components, the assumption is that a customer has a way to
look at the serial output.
This particular serial interface has been called "Microwire" by
National Semiconductor. It is a standard way for a "COPS" chip
to talk to external chips. For customers that did not have this
resource, a demo board was built to allow some customers access
to the serial output data.
The board generates a free running Chip Select and Clock. When a customer
connects scope probes up to those two nodes together with the Data
Output node, applying an analog input will reveal the proper serial
output in the format shown above.
The demo board was made to handle both a plastic dip package as well
as a SOT package (which mounted on the back having a mirror pinout).
If the Arduino system had been available, this demo board would have
been unnecessary. A customer would have only needed the ADCV0831
in a standard dip package, an Arduino board, maybe a capacitor or two,
some hook up wire, and a very small amount of code to connect the ADC's
digital output directly to a laptop for display.
A website on how to connect a LTC2400 to an Arduino system is shown here.
Tiny packages are a bit hard to handle. If a part must be shipped in a
SOT package, the customer will be needing it to be mounted on a PC board.
The alternative is to ship the part in a plastic dip (taking care to
realize the pinout will be a mirror image).
So the question is, can the Arduino board make sampling mixed signal
ICs almost as easy as sampling Op Amp ICs?
===============Digital_Write=============================
int ledPin = 13; // LED connected to digital pin 13
void setup()
{ pinMode( ledPin, OUTPUT); // sets the digital pin as output
}
void loop()
{ digitalWrite( ledPin, HIGH); // sets the LED on
delay( 1000); // waits for a second
digitalWrite( ledPin, LOW); // sets the LED off
delay( 1000); // waits for a second
}
There are a few terms shown in black which have special meaning.
===============Digital_Read=============================
int ledPin = 13; // LED connected to digital pin 13
int inPin = 7; // pushbutton connected to digital pin 7
int val = 0; // variable to store the read value
void setup()
{ pinMode( ledPin, OUTPUT); // digital pin 13 as output +/-40 mA
pinMode( inPin, INPUT); // digital pin 7 as input 2V->3V
}
void loop()
{ val = digitalRead(inPin); // read the input pin
digitalWrite( ledPin, val); // sets the LED to the button's value
}
The digital output pins may not be short circuit proof?
The digital input pins should see 2V as low and 3V as high.
===============Read_Time=============================
long time_ms;
void setup()
{ Serial.begin( 9600);
}
void loop()
{ Serial.print( "Time: ");
time_ms = millis();
Serial.println( time_ms); // prints time since program started
delay( 1000); // delay one sec
}
The Timing looks like it shows how long it takes for code to run.
=================Read_Time=============================
/* Frequency Test
* Paul Badger 2007
* Program to empirically determine the time delay to generate the
* proper frequency for a an Infrared (IR) Remote Control Receiver module
* These modules typically require 36 - 52 khz communication frequency
* depending on specific device.
*/
int tdelay;
unsigned long i, hz;
unsigned long time;
int outPin = 11;
void setup()
{ pinMode( outPin, OUTPUT);
Serial.begin( 9600);
}
void loop()
{ for (tdelay = 1; tdelay < 12; tdelay++) // scan across range time delays find frequency
{ time = millis(); // get start time of inner loop
for (i = 0; i < 100000; i++) // time 100,000 cycles through the loop
{ digitalWrite( outPin, HIGH);
delayMicroseconds( tdelay);
digitalWrite( outPin, LOW);
delayMicroseconds( tdelay);
}
time = millis() - time; // compute time through inner loop in milliseconds
hz = (1 /((float)time / 100000000.0)); // divide by 100KHz and 1000 milliseconds per second
Serial.print( tdelay, DEC);
Serial.print( " ");
Serial.println( hz, DEC);
}
}
This and the following are just examples included for reference.
=================Save_Strings_To_File_Using_Processor_Code===================
String[] name = new String[3];
name[0] = "Alfred";
name[1] = "E";
name[2] = "Newman";
saveStrings( "nouns.txt", name); // write strings to file, each on a separate line
Use menu to find Sketch folder
=================Save_String_to_File_Using_Processor_Code=============
Use menu to find Sketch folder
String words = "apple bear cat dog";
String[] list = split(words, ' ');
saveStrings( "nouns.txt", list); // write strings to file on separate lines
=================Read_from_File_Using_Processor_Code===================
String lines[] = loadStrings("nouns.txt");
println( "there are " + lines.length + " lines");
for (int i=0; i < lines.length; i++)
{ println( lines[i]);
}
=================MISC_Arduino================
Arduino program run in two parts:
void setup()
void loop()
anytype val = constrain(sensVal, 10, 150); // limits range sensVal to between 10 and 150
int val = map(val, 0, 1023, 0, 255); // map a val 0->1023 to 0->255
anytype val = min(x, y)
float base = 3
float exponent = 2
double val = pow(base, exponent)
float rad = 3.14
double val = sin(rad)
double val = cos(rad)
double val = tan(rad)
randomSeed( seed)
long val = random(max)
long val = random(min, max)
unsigned long val = millis()
delay( ms)
delayMicroseconds( us)
Serial.flush()
false defined as 0 (zero)
true Any integer which is non-zero
HIGH 3 volts or more input/ 5 volts output .
LOW 2 volts or less input pin is at 0 volts.
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
&& and
|| or
! not
Pins configured as OUTPUT with pinMode() in a low-impedance state.
Pins configured outputs can be damaged or destroyed if short circuited
break break is used to exit from a do, for, or while loop,
bypassing the normal loop condition. It is also used to exit from a
switch statement.
for (x = 0; x < 255; x ++)
{ digitalWrite( PWMpin, x);
sens = analogRead(sensorPin);
if (sens > threshold) // bail out on sensor detect
{ x = 0;
break;
} delay( 50);
}