Skip to content

Instantly share code, notes, and snippets.

@PierreAuge
Last active June 4, 2017 18:56
Show Gist options
  • Save PierreAuge/79c03b8b5e85f0df4993ff28212f97fb to your computer and use it in GitHub Desktop.
Save PierreAuge/79c03b8b5e85f0df4993ff28212f97fb to your computer and use it in GitHub Desktop.
/* This one is not using any PinChangeInterrupt library */
/*
This program uses an Arduino for a closed-loop control of a DC-motor.
Motor motion is detected by a quadrature encoder.
Two inputs named STEP and DIR allow changing the target position.
Serial port prints current position and target position every second.
Serial input can be used to feed a new location for the servo (no CR LF).
Pins used:
Digital inputs 8 & 9 are connected to the two encoder signals (AB).
Digital input 3 is the STEP input.
Analog input 0 is the DIR input.
Digital outputs 5 & 6 control the PWM outputs for the motor (I am using an IBT-2 43amp peak DC motor driver).
Digital outputs 4 and 7 are enable pins for dual-H-bridge
Please note PID gains kp, ki, kd need to be tuned to each different setup.
*/
#include <EEPROM.h>
#include <PID_v1.h>
#define encoder0PinA 2 // PD2;
#define encoder0PinB 8 // PC0;
#define M1 5
#define M2 6 // motor's PWM outputs
#define ENABLE_1 4
#define ENABLE_2 7
byte pos[1000]; int p=0;
double kp=3,ki=0,kd=0.0;
double input=0, output=0, setpoint=0;
PID myPID(&input, &output, &setpoint,kp,ki,kd, DIRECT);
volatile long encoder0Pos = 0;
boolean auto1=false, auto2=false,counting=false;
long previousMillis = 0; // will store last time LED was updated
long target1=0; // destination location at any moment
//for motor control ramps 1.4
bool newStep = false;
bool oldStep = false;
bool dir = false;
byte skip=0;
// Install Pin change interrupt for a pin, can be called multiple times
void pciSetup(byte pin)
{
*digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin)); // enable pin
PCIFR |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
PCICR |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the group
}
void setup() {
pinMode(encoder0PinA, INPUT);
pinMode(encoder0PinB, INPUT);
pinMode(ENABLE_1, OUTPUT);
pinMode(ENABLE_2, OUTPUT);
digitalWrite(ENABLE_1, 1);
digitalWrite(ENABLE_2, 1);
pciSetup(encoder0PinB);
attachInterrupt(0, encoderInt, CHANGE); // encoder pin on interrupt 0 - pin 2
attachInterrupt(1, countStep , RISING); // step input on interrupt 1 - pin 3
TCCR1B = TCCR1B & 0b11111000 | 1; // set 31Kh PWM
Serial.begin (115200);
help();
recoverPIDfromEEPROM();
//Setup the pid
myPID.SetMode(AUTOMATIC);
myPID.SetSampleTime(1);
myPID.SetOutputLimits(-255,255);
}
void loop(){
input = encoder0Pos;
setpoint=target1;
while(!myPID.Compute()); // wait till PID is actually computed
if(Serial.available()) process_line(); // it may induce a glitch to move motion, so use it sparingly
pwmOut(output);
if(auto1) if(millis() % 3000 == 0) target1=random(2000); // that was for self test with no input from main controller
if(auto2) if(millis() % 1000 == 0) printPos();
//if(counting && abs(input-target1)<15) counting=false;
if(counting && (skip++ % 5)==0 ) {pos[p]=encoder0Pos; if(p<999) p++; else counting=false;}
}
void pwmOut(int out) {
if(out<0) { analogWrite(M1,0); analogWrite(M2,abs(out)); }
else { analogWrite(M2,0); analogWrite(M1,abs(out)); }
}
const int QEM [16] = {0,-1,1,2,1,0,2,-1,-1,2,0,1,2,1,-1,0}; // Quadrature Encoder Matrix
static unsigned char New, Old;
ISR (PCINT0_vect) { // handle pin change interrupt for D8
Old = New;
New = (PINB & 1 )+ ((PIND & 4) >> 1); //
encoder0Pos+= QEM [Old * 4 + New];
}
void encoderInt() { // handle pin change interrupt for D2
Old = New;
New = (PINB & 1 )+ ((PIND & 4) >> 1); //
encoder0Pos+= QEM [Old * 4 + New];
}
void countStep(){ if (PINC&B0000001) target1--;else target1++; } // pin A0 represents direction
void process_line() {
char cmd = Serial.read();
if(cmd>'Z') cmd-=32;
switch(cmd) {
case 'P': kp=Serial.parseFloat(); myPID.SetTunings(kp,ki,kd); break;
case 'D': kd=Serial.parseFloat(); myPID.SetTunings(kp,ki,kd); break;
case 'I': ki=Serial.parseFloat(); myPID.SetTunings(kp,ki,kd); break;
case '?': printPos(); break;
case 'X': target1=Serial.parseInt(); p=0; counting=true; for(int i=0; i<300; i++) pos[i]=0; break;
case 'T': auto1 = !auto1; break;
case 'A': auto2 = !auto2; break;
case 'Q': Serial.print("P="); Serial.print(kp); Serial.print(" I="); Serial.print(ki); Serial.print(" D="); Serial.println(kd); break;
case 'H': help(); break;
case 'W': writetoEEPROM(); break;
case 'K': eedump(); break;
case 'R': recoverPIDfromEEPROM() ; break;
case 'S': for(int i=0; i<p; i++) Serial.println(pos[i]); break;
}
while(Serial.read()!=10); // dump extra characters till LF is seen (you can use CRLF or just LF)
}
void printPos() {
Serial.print(F("Position=")); Serial.print(encoder0Pos); Serial.print(F(" PID_output=")); Serial.print(output); Serial.print(F(" Target=")); Serial.println(setpoint);
}
void help() {
Serial.println(F("\nPID DC motor controller and stepper interface emulator"));
Serial.println(F("by misan"));
Serial.println(F("Available serial commands: (lines end with CRLF or LF)"));
Serial.println(F("P123.34 sets proportional term to 123.34"));
Serial.println(F("I123.34 sets integral term to 123.34"));
Serial.println(F("D123.34 sets derivative term to 123.34"));
Serial.println(F("? prints out current encoder, output and setpoint values"));
Serial.println(F("X123 sets the target destination for the motor to 123 encoder pulses"));
Serial.println(F("T will start a sequence of random destinations (between 0 and 2000) every 3 seconds. T again will disable that"));
Serial.println(F("Q will print out the current values of P, I and D parameters"));
Serial.println(F("W will store current values of P, I and D parameters into EEPROM"));
Serial.println(F("H will print this help message again"));
Serial.println(F("A will toggle on/off showing regulator status every second\n"));
}
void writetoEEPROM() { // keep PID set values in EEPROM so they are kept when arduino goes off
eeput(kp,0);
eeput(ki,4);
eeput(kd,8);
double cks=0;
for(int i=0; i<12; i++) cks+=EEPROM.read(i);
eeput(cks,12);
Serial.println("\nPID values stored to EEPROM");
//Serial.println(cks);
}
void recoverPIDfromEEPROM() {
double cks=0;
double cksEE;
for(int i=0; i<12; i++) cks+=EEPROM.read(i);
cksEE=eeget(12);
//Serial.println(cks);
if(cks==cksEE) {
Serial.println(F("*** Found PID values on EEPROM"));
kp=eeget(0);
ki=eeget(4);
kd=eeget(8);
myPID.SetTunings(kp,ki,kd);
}
else Serial.println(F("*** Bad checksum"));
}
void eeput(double value, int dir) { // Snow Leopard keeps me grounded to 1.0.6 Arduino, so I have to do this :-(
char * addr = (char * ) &value;
for(int i=dir; i<dir+4; i++) EEPROM.write(i,addr[i-dir]);
}
double eeget(int dir) { // Snow Leopard keeps me grounded to 1.0.6 Arduino, so I have to do this :-(
double value;
char * addr = (char * ) &value;
for(int i=dir; i<dir+4; i++) addr[i-dir]=EEPROM.read(i);
return value;
}
void eedump() {
for(int i=0; i<16; i++) { Serial.print(EEPROM.read(i),HEX); Serial.print(" "); }Serial.println();
}
# Your init script
#
# Atom will evaluate this file each time a new window is opened. It is run
# after packages are loaded/activated and after the previous editor state
# has been restored.
#
# An example hack to log to the console when each text editor is saved.
#
# atom.workspace.observeTextEditors (editor) ->
# editor.onDidSave ->
# console.log "Saved! #{editor.getPath()}"
# Your keymap
#
# Atom keymaps work similarly to style sheets. Just as style sheets use
# selectors to apply styles to elements, Atom keymaps use selectors to associate
# keystrokes with events in specific contexts. Unlike style sheets however,
# each selector can only be declared once.
#
# You can create a new keybinding in this file by typing "key" and then hitting
# tab.
#
# Here's an example taken from Atom's built-in keymap:
#
# 'atom-text-editor':
# 'enter': 'editor:newline'
#
# 'atom-workspace':
# 'ctrl-shift-p': 'core:move-up'
# 'ctrl-p': 'core:move-down'
#
# You can find more information about keymaps in these guides:
# * http://flight-manual.atom.io/using-atom/sections/basic-customization/#_customizing_keybindings
# * http://flight-manual.atom.io/behind-atom/sections/keymaps-in-depth/
#
# If you're having trouble with your keybindings not working, try the
# Keybinding Resolver: `Cmd+.` on macOS and `Ctrl+.` on other platforms. See the
# Debugging Guide for more information:
# * http://flight-manual.atom.io/hacking-atom/sections/debugging/#check-the-keybindings
#
# This file uses CoffeeScript Object Notation (CSON).
# If you are unfamiliar with CSON, you can read more about it in the
# Atom Flight Manual:
# http://flight-manual.atom.io/using-atom/sections/basic-customization/#_cson
[
{
"name": "about",
"version": "1.7.6"
},
{
"name": "archive-view",
"version": "0.63.2"
},
{
"name": "atom-dark-syntax",
"version": "0.28.0",
"theme": "syntax"
},
{
"name": "atom-dark-ui",
"version": "0.53.0",
"theme": "ui"
},
{
"name": "atom-light-syntax",
"version": "0.29.0",
"theme": "syntax"
},
{
"name": "atom-light-ui",
"version": "0.46.0",
"theme": "ui"
},
{
"name": "autocomplete-atom-api",
"version": "0.10.1"
},
{
"name": "autocomplete-clang",
"version": "0.11.3"
},
{
"name": "autocomplete-css",
"version": "0.16.1"
},
{
"name": "autocomplete-html",
"version": "0.7.3"
},
{
"name": "autocomplete-plus",
"version": "2.35.3"
},
{
"name": "autocomplete-snippets",
"version": "1.11.0"
},
{
"name": "autoflow",
"version": "0.29.0"
},
{
"name": "autosave",
"version": "0.24.2"
},
{
"name": "background-tips",
"version": "0.27.0"
},
{
"name": "base16-tomorrow-dark-theme",
"version": "1.5.0",
"theme": "syntax"
},
{
"name": "base16-tomorrow-light-theme",
"version": "1.5.0",
"theme": "syntax"
},
{
"name": "bookmarks",
"version": "0.44.3"
},
{
"name": "bracket-matcher",
"version": "0.85.5"
},
{
"name": "build",
"version": "0.68.0"
},
{
"name": "busy",
"version": "0.7.0"
},
{
"name": "command-palette",
"version": "0.40.4"
},
{
"name": "dalek",
"version": "0.2.1"
},
{
"name": "deprecation-cop",
"version": "0.56.7"
},
{
"name": "dev-live-reload",
"version": "0.47.1"
},
{
"name": "encoding-selector",
"version": "0.23.3"
},
{
"name": "exception-reporting",
"version": "0.41.4"
},
{
"name": "file-icons",
"version": "2.1.7"
},
{
"name": "find-and-replace",
"version": "0.208.3"
},
{
"name": "fuzzy-finder",
"version": "1.5.8"
},
{
"name": "git-diff",
"version": "1.3.5"
},
{
"name": "git-projects",
"version": "1.17.0"
},
{
"name": "go-to-line",
"version": "0.32.0"
},
{
"name": "grammar-selector",
"version": "0.49.4"
},
{
"name": "image-view",
"version": "0.61.2"
},
{
"name": "incompatible-packages",
"version": "0.27.3"
},
{
"name": "intentions",
"version": "1.1.2"
},
{
"name": "keybinding-resolver",
"version": "0.38.0"
},
{
"name": "language-c",
"version": "0.57.0"
},
{
"name": "language-clojure",
"version": "0.22.2"
},
{
"name": "language-coffee-script",
"version": "0.48.6"
},
{
"name": "language-csharp",
"version": "0.14.2"
},
{
"name": "language-css",
"version": "0.42.2"
},
{
"name": "language-gfm",
"version": "0.88.1"
},
{
"name": "language-git",
"version": "0.19.0"
},
{
"name": "language-go",
"version": "0.43.1"
},
{
"name": "language-html",
"version": "0.47.2"
},
{
"name": "language-hyperlink",
"version": "0.16.1"
},
{
"name": "language-ini",
"version": "1.19.0"
},
{
"name": "language-java",
"version": "0.27.0"
},
{
"name": "language-javascript",
"version": "0.126.1"
},
{
"name": "language-json",
"version": "0.19.0"
},
{
"name": "language-less",
"version": "0.32.0"
},
{
"name": "language-make",
"version": "0.22.3"
},
{
"name": "language-mustache",
"version": "0.13.1"
},
{
"name": "language-objective-c",
"version": "0.15.1"
},
{
"name": "language-openscad",
"version": "0.4.3"
},
{
"name": "language-perl",
"version": "0.37.0"
},
{
"name": "language-php",
"version": "0.38.0"
},
{
"name": "language-property-list",
"version": "0.9.1"
},
{
"name": "language-python",
"version": "0.45.2"
},
{
"name": "language-ruby",
"version": "0.71.0"
},
{
"name": "language-ruby-on-rails",
"version": "0.25.2"
},
{
"name": "language-sass",
"version": "0.59.0"
},
{
"name": "language-shellscript",
"version": "0.25.0"
},
{
"name": "language-source",
"version": "0.9.0"
},
{
"name": "language-sql",
"version": "0.25.4"
},
{
"name": "language-text",
"version": "0.7.2"
},
{
"name": "language-todo",
"version": "0.29.1"
},
{
"name": "language-toml",
"version": "0.18.1"
},
{
"name": "language-xml",
"version": "0.35.0"
},
{
"name": "language-yaml",
"version": "0.29.0"
},
{
"name": "line-ending-selector",
"version": "0.6.3"
},
{
"name": "link",
"version": "0.31.3"
},
{
"name": "linter",
"version": "2.1.4"
},
{
"name": "linter-gcc",
"version": "0.7.1"
},
{
"name": "linter-ui-default",
"version": "1.6.0"
},
{
"name": "markdown-preview",
"version": "0.159.12"
},
{
"name": "metrics",
"version": "1.2.5"
},
{
"name": "minimap",
"version": "4.28.2"
},
{
"name": "notifications",
"version": "0.67.2"
},
{
"name": "one-dark-syntax",
"version": "1.7.1",
"theme": "syntax"
},
{
"name": "one-dark-ui",
"version": "1.10.3",
"theme": "ui"
},
{
"name": "one-light-syntax",
"version": "1.7.1",
"theme": "syntax"
},
{
"name": "one-light-ui",
"version": "1.10.3",
"theme": "ui"
},
{
"name": "open-on-github",
"version": "1.2.1"
},
{
"name": "package-generator",
"version": "1.1.1"
},
{
"name": "platformio-ide",
"version": "2.0.0-beta.6"
},
{
"name": "platformio-ide-debugger",
"version": "1.2.2"
},
{
"name": "platformio-ide-terminal",
"version": "2.5.1"
},
{
"name": "settings-view",
"version": "0.249.4"
},
{
"name": "snippets",
"version": "1.1.4"
},
{
"name": "solarized-dark-syntax",
"version": "1.1.2",
"theme": "syntax"
},
{
"name": "solarized-light-syntax",
"version": "1.1.2",
"theme": "syntax"
},
{
"name": "spell-check",
"version": "0.71.4"
},
{
"name": "status-bar",
"version": "1.8.7"
},
{
"name": "styleguide",
"version": "0.49.6"
},
{
"name": "symbols-view",
"version": "0.115.5"
},
{
"name": "sync-settings",
"version": "0.8.1"
},
{
"name": "tabs",
"version": "0.106.0"
},
{
"name": "timecop",
"version": "0.36.0"
},
{
"name": "tool-bar",
"version": "1.1.0"
},
{
"name": "tree-view",
"version": "0.217.1"
},
{
"name": "update-package-dependencies",
"version": "0.12.0"
},
{
"name": "welcome",
"version": "0.36.3"
},
{
"name": "whitespace",
"version": "0.36.2"
},
{
"name": "wrap-guide",
"version": "0.40.1"
}
]
{
"core": {
"ignoredNames": [
".git",
".hg",
".svn",
".DS_Store",
"._*",
"Thumbs.db",
"desktop.ini",
".pioenvs",
".piolibdeps",
".clang_complete",
".gcc-flags.json"
],
"telemetryConsent": "limited"
},
"exception-reporting": {
"userId": "0e26c4e2-be88-4917-b67a-1086cff56038"
},
"file-icons": {
"coloured": false
},
"linter-ui-default": {
"panelHeight": 69,
"useBusySignal": false
},
"sync-settings": {
"quietUpdateCheck": true
},
"tool-bar": {
"position": "Left"
},
"tree-view": {
"hideIgnoredNames": true
}
}
# Your snippets
#
# Atom snippets allow you to enter a simple prefix in the editor and hit tab to
# expand the prefix into a larger code block with templated values.
#
# You can create a new snippet in this file by typing "snip" and then hitting
# tab.
#
# An example CoffeeScript snippet to expand log to console.log:
#
# '.source.coffee':
# 'Console log':
# 'prefix': 'log'
# 'body': 'console.log $1'
#
# Each scope (e.g. '.source.coffee' above) can only be declared once.
#
# This file uses CoffeeScript Object Notation (CSON).
# If you are unfamiliar with CSON, you can read more about it in the
# Atom Flight Manual:
# http://flight-manual.atom.io/using-atom/sections/basic-customization/#_cson
/*
* Your Stylesheet
*
* This stylesheet is loaded when Atom starts up and is reloaded automatically
* when it is changed and saved.
*
* Add your own CSS or Less to fully customize Atom.
* If you are unfamiliar with Less, you can read more about it here:
* http://lesscss.org
*/
/*
* Examples
* (To see them, uncomment and save)
*/
// style the background color of the tree view
.tree-view {
// background-color: whitesmoke;
}
// style the background and foreground colors on the atom-text-editor-element itself
atom-text-editor {
// color: white;
// background-color: hsl(180, 24%, 12%);
}
// style UI elements inside atom-text-editor
atom-text-editor .cursor {
// border-color: red;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment