mirror of
https://github.com/arduino/Arduino.git
synced 2025-02-19 13:54:23 +01:00
Merge branch 'ide-1.5.x' into dev-ide-1.5.x-discovery
Conflicts: app/src/processing/app/Preferences.java app/src/processing/app/debug/Uploader.java
This commit is contained in:
commit
ea8c14421a
@ -31,6 +31,7 @@ import processing.app.Preferences;
|
||||
import processing.app.debug.MessageConsumer;
|
||||
import processing.app.debug.MessageSiphon;
|
||||
import processing.app.debug.RunnerException;
|
||||
import processing.app.helpers.ProcessUtils;
|
||||
import processing.app.helpers.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
@ -98,7 +99,7 @@ public abstract class Uploader implements MessageConsumer {
|
||||
System.out.print(c + " ");
|
||||
System.out.println();
|
||||
}
|
||||
Process process = Runtime.getRuntime().exec(command);
|
||||
Process process = ProcessUtils.exec(command);
|
||||
new MessageSiphon(process.getInputStream(), this);
|
||||
new MessageSiphon(process.getErrorStream(), this);
|
||||
|
||||
|
@ -33,7 +33,6 @@ import processing.app.*;
|
||||
import processing.app.debug.RunnerException;
|
||||
import processing.app.debug.TargetPlatform;
|
||||
import processing.app.helpers.PreferencesMap;
|
||||
import processing.app.helpers.PreferencesMapException;
|
||||
import processing.app.helpers.StringReplacer;
|
||||
|
||||
import java.io.File;
|
||||
|
@ -145,7 +145,7 @@ public class Base {
|
||||
File versionFile = getContentFile("lib/version.txt");
|
||||
if (versionFile.exists()) {
|
||||
String version = PApplet.loadStrings(versionFile)[0];
|
||||
if (!version.equals(VERSION_NAME)) {
|
||||
if (!version.equals(VERSION_NAME) && !version.equals("${version}")) {
|
||||
VERSION_NAME = version;
|
||||
RELEASE = true;
|
||||
}
|
||||
@ -154,6 +154,10 @@ public class Base {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
// help 3rd party installers find the correct hardware path
|
||||
Preferences.set("last.ide." + VERSION_NAME + ".hardwarepath", getHardwarePath());
|
||||
Preferences.set("last.ide." + VERSION_NAME + ".daterun", "" + (new Date()).getTime() / 1000);
|
||||
|
||||
// if (System.getProperty("mrj.version") != null) {
|
||||
// //String jv = System.getProperty("java.version");
|
||||
// String ov = System.getProperty("os.version");
|
||||
|
@ -650,6 +650,7 @@ public class Editor extends JFrame implements RunnerListener {
|
||||
|
||||
if (importMenu == null) {
|
||||
importMenu = new JMenu(_("Import Library..."));
|
||||
MenuScroller.setScrollerFor(importMenu);
|
||||
base.rebuildImportMenu(importMenu, this);
|
||||
}
|
||||
sketchMenu.add(importMenu);
|
||||
|
@ -452,25 +452,21 @@ public class EditorStatus extends JPanel /*implements ActionListener*/ {
|
||||
add(progressBar);
|
||||
progressBar.setVisible(false);
|
||||
|
||||
copyErrorButton = new JButton(
|
||||
"<html>" + _("Copy error") + "<br>" + _("to clipboard") + "</html>");
|
||||
Font font = copyErrorButton.getFont();
|
||||
font = new Font(font.getName(), font.getStyle(), (int) (font.getSize()*0.7));
|
||||
copyErrorButton.setFont(font);
|
||||
copyErrorButton.setHorizontalAlignment(JLabel.CENTER);
|
||||
copyErrorButton = new JButton(_("Copy error"));
|
||||
add(copyErrorButton);
|
||||
copyErrorButton.setVisible(false);
|
||||
copyErrorButton.addActionListener(new ActionListener() {
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
String message="";
|
||||
String message = "";
|
||||
message += _("Arduino: ") + Base.VERSION_NAME + " (" + System.getProperty("os.name") + "), ";
|
||||
message += _("Board: ") + "\"" + Base.getBoardPreferences().get("name") + "\"\n\n";
|
||||
message += editor.console.consoleTextPane.getText().trim();
|
||||
if ((Preferences.getBoolean("build.verbose")) == false) {
|
||||
message = " " + _("This report would have more information with") + "\n";
|
||||
message += "\n\n";
|
||||
message += " " + _("This report would have more information with") + "\n";
|
||||
message += " \"" + _("Show verbose output during compilation") + "\"\n";
|
||||
message += " " + _("enabled in File > Preferences.") + "\n";
|
||||
}
|
||||
message += _("Arduino: ") + Base.VERSION_NAME + " (" + System.getProperty("os.name") + "), ";
|
||||
message += _("Board: ") + "\"" + Base.getBoardPreferences().get("name") + "\"\n";
|
||||
message += editor.console.consoleTextPane.getText().trim();
|
||||
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
|
||||
StringSelection data = new StringSelection(message);
|
||||
clipboard.setContents(data, null);
|
||||
|
@ -218,7 +218,7 @@ public class Preferences {
|
||||
// data model
|
||||
|
||||
static Hashtable defaults;
|
||||
static Hashtable table = new Hashtable();
|
||||
static Hashtable<String, String> table = new Hashtable<String, String>();
|
||||
static File preferencesFile;
|
||||
|
||||
|
||||
@ -242,9 +242,8 @@ public class Preferences {
|
||||
// check for platform-specific properties in the defaults
|
||||
String platformExt = "." + Base.platform.getName();
|
||||
int platformExtLength = platformExt.length();
|
||||
Enumeration e = table.keys();
|
||||
while (e.hasMoreElements()) {
|
||||
String key = (String) e.nextElement();
|
||||
Set<String> keySet = new HashSet<String>(table.keySet());
|
||||
for (String key : keySet) {
|
||||
if (key.endsWith(platformExt)) {
|
||||
// this is a key specific to a particular platform
|
||||
String actualKey = key.substring(0, key.length() - platformExtLength);
|
||||
@ -791,12 +790,12 @@ public class Preferences {
|
||||
// Fix for 0163 to properly use Unicode when writing preferences.txt
|
||||
PrintWriter writer = PApplet.createWriter(preferencesFile);
|
||||
|
||||
String[] keys = (String[])table.keySet().toArray(new String[0]);
|
||||
String[] keys = table.keySet().toArray(new String[0]);
|
||||
Arrays.sort(keys);
|
||||
for (String key: keys) {
|
||||
if (key.startsWith("runtime."))
|
||||
continue;
|
||||
writer.println(key + "=" + ((String) table.get(key)));
|
||||
writer.println(key + "=" + table.get(key));
|
||||
}
|
||||
|
||||
writer.flush();
|
||||
@ -818,7 +817,7 @@ public class Preferences {
|
||||
//}
|
||||
|
||||
static public String get(String attribute /*, String defaultValue */) {
|
||||
return (String) table.get(attribute);
|
||||
return table.get(attribute);
|
||||
/*
|
||||
//String value = (properties != null) ?
|
||||
//properties.getProperty(attribute) : applet.getParameter(attribute);
|
||||
|
@ -39,6 +39,7 @@ import processing.app.Preferences;
|
||||
import processing.app.Sketch;
|
||||
import processing.app.SketchCode;
|
||||
import processing.app.helpers.PreferencesMap;
|
||||
import processing.app.helpers.ProcessUtils;
|
||||
import processing.app.helpers.StringReplacer;
|
||||
import processing.app.helpers.filefilters.OnlyDirs;
|
||||
import processing.app.packages.Library;
|
||||
@ -343,9 +344,8 @@ public class Compiler implements MessageConsumer {
|
||||
secondErrorFound = false;
|
||||
|
||||
Process process;
|
||||
|
||||
try {
|
||||
process = Runtime.getRuntime().exec(command);
|
||||
process = ProcessUtils.exec(command);
|
||||
} catch (IOException e) {
|
||||
RunnerException re = new RunnerException(e.getMessage());
|
||||
re.hideStackTrace();
|
||||
|
@ -30,6 +30,7 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import processing.app.helpers.PreferencesMap;
|
||||
import processing.app.helpers.ProcessUtils;
|
||||
import processing.app.helpers.StringReplacer;
|
||||
|
||||
public class Sizer implements MessageConsumer {
|
||||
@ -67,7 +68,7 @@ public class Sizer implements MessageConsumer {
|
||||
textSize = -1;
|
||||
dataSize = -1;
|
||||
eepromSize = -1;
|
||||
Process process = Runtime.getRuntime().exec(cmd);
|
||||
Process process = ProcessUtils.exec(cmd);
|
||||
MessageSiphon in = new MessageSiphon(process.getInputStream(), this);
|
||||
MessageSiphon err = new MessageSiphon(process.getErrorStream(), this);
|
||||
|
||||
|
25
app/src/processing/app/helpers/ProcessUtils.java
Normal file
25
app/src/processing/app/helpers/ProcessUtils.java
Normal file
@ -0,0 +1,25 @@
|
||||
package processing.app.helpers;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import processing.app.Base;
|
||||
|
||||
public class ProcessUtils {
|
||||
|
||||
public static Process exec(String[] command) throws IOException {
|
||||
// No problems on linux and mac
|
||||
if (!Base.isWindows()) {
|
||||
return Runtime.getRuntime().exec(command);
|
||||
}
|
||||
|
||||
// Brutal hack to workaround windows command line parsing.
|
||||
// http://stackoverflow.com/questions/5969724/java-runtime-exec-fails-to-escape-characters-properly
|
||||
// http://msdn.microsoft.com/en-us/library/a1y7w461.aspx
|
||||
// http://bugs.sun.com/view_bug.do?bug_id=6468220
|
||||
// http://bugs.sun.com/view_bug.do?bug_id=6518827
|
||||
String[] cmdLine = new String[command.length];
|
||||
for (int i = 0; i < command.length; i++)
|
||||
cmdLine[i] = command[i].replace("\"", "\\\"");
|
||||
return Runtime.getRuntime().exec(cmdLine);
|
||||
}
|
||||
}
|
@ -108,9 +108,9 @@ public class Platform extends processing.app.Platform {
|
||||
|
||||
public void openFolder(File file) throws Exception {
|
||||
if (openFolderAvailable()) {
|
||||
String lunch = Preferences.get("launcher");
|
||||
String launcher = Preferences.get("launcher");
|
||||
try {
|
||||
String[] params = new String[] { lunch, file.getAbsolutePath() };
|
||||
String[] params = new String[] { launcher, file.getAbsolutePath() };
|
||||
//processing.core.PApplet.println(params);
|
||||
/*Process p =*/ Runtime.getRuntime().exec(params);
|
||||
/*int result =*/ //p.waitFor();
|
||||
|
@ -3,12 +3,16 @@
|
||||
*/
|
||||
package processing.app.tools;
|
||||
|
||||
import java.awt.BorderLayout;
|
||||
import java.awt.Color;
|
||||
import java.awt.Component;
|
||||
import java.awt.Dimension;
|
||||
import java.awt.Graphics;
|
||||
import java.awt.event.ActionEvent;
|
||||
import java.awt.event.ActionListener;
|
||||
import java.awt.event.MouseWheelEvent;
|
||||
import java.awt.event.MouseWheelListener;
|
||||
|
||||
import javax.swing.Icon;
|
||||
import javax.swing.JComponent;
|
||||
import javax.swing.JMenu;
|
||||
@ -20,7 +24,7 @@ import javax.swing.event.ChangeEvent;
|
||||
import javax.swing.event.ChangeListener;
|
||||
import javax.swing.event.PopupMenuEvent;
|
||||
import javax.swing.event.PopupMenuListener;
|
||||
import javax.swing.plaf.*;
|
||||
import javax.swing.plaf.ButtonUI;
|
||||
|
||||
/**
|
||||
* A class that provides scrolling capabilities to a long menu dropdown or
|
||||
@ -42,6 +46,7 @@ public class MenuScroller {
|
||||
private MenuScrollItem upItem;
|
||||
private MenuScrollItem downItem;
|
||||
private final MenuScrollListener menuListener = new MenuScrollListener();
|
||||
private final MouseScrollListener mouseWheelListener = new MouseScrollListener();
|
||||
private int scrollCount;
|
||||
private int interval;
|
||||
private int topFixedCount;
|
||||
@ -320,6 +325,7 @@ public class MenuScroller {
|
||||
|
||||
this.menu = menu;
|
||||
menu.addPopupMenuListener(menuListener);
|
||||
menu.addMouseWheelListener(mouseWheelListener);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -446,6 +452,7 @@ public class MenuScroller {
|
||||
public void dispose() {
|
||||
if (menu != null) {
|
||||
menu.removePopupMenuListener(menuListener);
|
||||
menu.removeMouseWheelListener(mouseWheelListener);
|
||||
menu = null;
|
||||
}
|
||||
}
|
||||
@ -497,6 +504,14 @@ public class MenuScroller {
|
||||
}
|
||||
}
|
||||
|
||||
private class MouseScrollListener implements MouseWheelListener {
|
||||
public void mouseWheelMoved(MouseWheelEvent mwe) {
|
||||
firstIndex += mwe.getWheelRotation();
|
||||
refreshMenu();
|
||||
mwe.consume();
|
||||
}
|
||||
}
|
||||
|
||||
private class MenuScrollListener implements PopupMenuListener {
|
||||
|
||||
@Override
|
||||
@ -555,6 +570,7 @@ public class MenuScroller {
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
private class MenuScrollTimer extends Timer {
|
||||
|
||||
public MenuScrollTimer(final int increment, int interval) {
|
||||
@ -569,6 +585,7 @@ public class MenuScroller {
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
private class MenuScrollItem extends JMenuItem
|
||||
implements ChangeListener {
|
||||
|
||||
|
202
build/build.xml
202
build/build.xml
@ -5,20 +5,34 @@
|
||||
<!--echo message="os.version = ${os.version}" /-->
|
||||
|
||||
<!-- Sets properties for macosx/windows/linux depending on current system -->
|
||||
<condition property="macosx"><os family="mac" /></condition>
|
||||
<condition property="windows"><os family="windows" /></condition>
|
||||
<condition property="linux"><os family="unix" /></condition>
|
||||
<condition property="linux32"><os family="unix" arch="i386" /></condition>
|
||||
<condition property="linux64"><os family="unix" arch="amd64" /></condition>
|
||||
<condition property="platform" value="macosx"><os family="mac" /></condition>
|
||||
<condition property="platform" value="windows"><os family="windows" /></condition>
|
||||
<condition property="platform" value="linux32"><os family="unix" arch="i386" /></condition>
|
||||
<condition property="platform" value="linux64"><os family="unix" arch="amd64" /></condition>
|
||||
|
||||
<condition property="platform"
|
||||
value="macosx"><os family="mac" /></condition>
|
||||
<condition property="platform"
|
||||
value="windows"><os family="windows" /></condition>
|
||||
<condition property="platform"
|
||||
value="linux32"><os family="unix" arch="i386" /></condition>
|
||||
<condition property="platform"
|
||||
value="linux64"><os family="unix" arch="amd64" /></condition>
|
||||
<condition property="macosx"><equals arg1="${platform}" arg2="macosx" /></condition>
|
||||
<condition property="windows"><equals arg1="${platform}" arg2="windows" /></condition>
|
||||
<condition property="linux32"><equals arg1="${platform}" arg2="linux32" /></condition>
|
||||
<condition property="linux64"><equals arg1="${platform}" arg2="linux64" /></condition>
|
||||
<condition property="linux"><equals arg1="${platform}" arg2="linux32" /></condition>
|
||||
<condition property="linux"><equals arg1="${platform}" arg2="linux64" /></condition>
|
||||
|
||||
<condition property="staging_folder" value="macosx"><equals arg1="${platform}" arg2="macosx" /></condition>
|
||||
<condition property="staging_folder" value="windows"><equals arg1="${platform}" arg2="windows" /></condition>
|
||||
<condition property="staging_folder" value="linux"><equals arg1="${platform}" arg2="linux32" /></condition>
|
||||
<condition property="staging_folder" value="linux"><equals arg1="${platform}" arg2="linux64" /></condition>
|
||||
|
||||
<condition property="staging_hardware_folder" value="Arduino.app/Contents/Resources/Java/hardware"><equals arg1="${platform}" arg2="macosx" /></condition>
|
||||
<condition property="staging_hardware_folder" value="hardware"><equals arg1="${platform}" arg2="windows" /></condition>
|
||||
<condition property="staging_hardware_folder" value="hardware"><equals arg1="${platform}" arg2="linux32" /></condition>
|
||||
<condition property="staging_hardware_folder" value="hardware"><equals arg1="${platform}" arg2="linux64" /></condition>
|
||||
|
||||
<condition property="arch-bits" value="32">
|
||||
<equals arg1="${platform}" arg2="linux32"/>
|
||||
</condition>
|
||||
<condition property="arch-bits" value="64">
|
||||
<equals arg1="${platform}" arg2="linux64"/>
|
||||
</condition>
|
||||
|
||||
<!-- Libraries required for running arduino -->
|
||||
<fileset dir=".." id="runtime.jars">
|
||||
@ -184,7 +198,7 @@
|
||||
<fail message="wrong platform (${os.name})" />
|
||||
</target>
|
||||
|
||||
<target name="macosx-build" if="macosx" depends="revision-check, macosx-checkos, subprojects-build, macosx-check-arm-toolchain" description="Build Mac OS X version">
|
||||
<target name="macosx-build" if="macosx" depends="revision-check, macosx-checkos, subprojects-build" description="Build Mac OS X version">
|
||||
<mkdir dir="macosx/work" />
|
||||
|
||||
<!-- assemble the pde -->
|
||||
@ -233,7 +247,11 @@
|
||||
<param name="target.path" value="macosx/work/Arduino.app/Contents/Resources/Java" />
|
||||
</antcall>
|
||||
|
||||
<antcall target="macosx-unzip-arm-toolchain" />
|
||||
<antcall target="unzip-arm-toolchain">
|
||||
<param name="dist_file" value="gcc-arm-none-eabi-4.7.4-2013q2-mac.tar.gz" />
|
||||
<param name="dist_url" value="http://arduino.googlecode.com/files/gcc-arm-none-eabi-4.7.4-2013q2-mac.tar.gz" />
|
||||
<param name="dist_check_file" value="gcc-arm-none-eabi-4.7.4-2013q2" />
|
||||
</antcall>
|
||||
|
||||
<delete includeEmptyDirs="true" quiet="true">
|
||||
<fileset dir="macosx/work/Arduino.app/Contents/Resources/Java/hardware/tools" includes="**/3.4.6/**/*"/>
|
||||
@ -251,42 +269,6 @@
|
||||
<exec executable="macosx/work/Arduino.app/Contents/MacOS/JavaApplicationStub" spawn="false"/>
|
||||
</target>
|
||||
|
||||
<target name="macosx-check-arm-toolchain-distfile">
|
||||
<available file="macosx/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-macos.tar.gz" property="arm_distfile_available" />
|
||||
</target>
|
||||
|
||||
<target name="macosx-get-arm-toolchain" depends="macosx-check-arm-toolchain-distfile" unless="arm_distfile_available">
|
||||
<!-- Retrieve ARM toolchain -->
|
||||
<get
|
||||
src="http://arduino.googlecode.com/files/gcc-arm-none-eabi-4.4.1-2010q1-188-macos.tar.gz"
|
||||
dest="macosx/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-macos.tar.gz" verbose="true" />
|
||||
</target>
|
||||
|
||||
<target name="macosx-check-arm-toolchain">
|
||||
<available file="macosx/work/Arduino.app/Contents/Resources/Java/hardware/tools/g++_arm_none_eabi"
|
||||
property="arm_available" />
|
||||
</target>
|
||||
|
||||
<target name="macosx-unzip-arm-toolchain" depends="macosx-get-arm-toolchain, macosx-check-arm-toolchain" unless="arm_available">
|
||||
<checksum file="macosx/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-macos.tar.gz" algorithm="sha"
|
||||
fileext=".sha" verifyproperty="checksum.matches"/>
|
||||
<condition property="checksum.matches.fail">
|
||||
<equals arg1="${checksum.matches}" arg2="false"/>
|
||||
</condition>
|
||||
<fail if="checksum.matches.fail">Checksum failed.
|
||||
|
||||
File gcc-arm-none-eabi-4.4.1-2010q1-188-macos.tar.gz failed checksum.
|
||||
Please remove "macosx/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-macos.tar.gz" to download it again.
|
||||
</fail>
|
||||
|
||||
<!-- ...and unzip on the destination folder -->
|
||||
<exec executable="tar" output="/dev/null">
|
||||
<arg value="xfz"/>
|
||||
<arg value="macosx/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-macos.tar.gz"/>
|
||||
<arg value="--directory=macosx/work/Arduino.app/Contents/Resources/Java/hardware/tools/"/>
|
||||
</exec>
|
||||
</target>
|
||||
|
||||
<!-- - - - - - - - - - - - - - - - -->
|
||||
<!-- Sign application for MacOSX. -->
|
||||
<!-- - - - - - - - - - - - - - - - -->
|
||||
@ -446,7 +428,7 @@
|
||||
<fail message="wrong platform (${os.name})" />
|
||||
</target>
|
||||
|
||||
<target name="linux-build" depends="revision-check, linux-checkos, subprojects-build, linux-check-arm-toolchain" description="Build linux version">
|
||||
<target name="linux-build" depends="revision-check, linux-checkos, subprojects-build" description="Build linux version">
|
||||
<mkdir dir="linux/work" />
|
||||
|
||||
<copy todir="linux/work">
|
||||
@ -469,23 +451,30 @@
|
||||
<copy todir="linux/work" file="linux/dist/arduino" />
|
||||
<chmod perm="755" file="linux/work/arduino" />
|
||||
|
||||
<copy todir="linux/work/hardware">
|
||||
<fileset dir="linux/dist" includes="tools/**" />
|
||||
</copy>
|
||||
<mkdir dir="linux/work/hardware/tools" />
|
||||
<copy file="linux/dist/tools/adk2install" todir="linux/work/hardware/tools" />
|
||||
<copy file="linux/dist/tools/adk2tool" todir="linux/work/hardware/tools" />
|
||||
<copy file="linux/dist/tools/avrdude${arch-bits}" tofile="linux/work/hardware/tools/avrdude" />
|
||||
<copy file="linux/dist/tools/avrdude.conf" todir="linux/work/hardware/tools" />
|
||||
<copy file="linux/dist/tools/bossac${arch-bits}" tofile="linux/work/hardware/tools/bossac" />
|
||||
|
||||
<chmod perm="755" file="linux/work/hardware/tools/avrdude" />
|
||||
<chmod perm="755" file="linux/work/hardware/tools/bossac" />
|
||||
<chmod perm="755" file="linux/work/hardware/tools/bossac64" />
|
||||
<chmod perm="755" file="linux/work/hardware/tools/adk2tool" />
|
||||
<chmod perm="755" file="linux/work/hardware/tools/adk2install" />
|
||||
|
||||
<copy todir="linux/work" file="linux/dist/arduino" />
|
||||
<chmod perm="755" file="linux/work/arduino" />
|
||||
|
||||
<antcall target="linux-unzip-arm-toolchain" />
|
||||
</target>
|
||||
|
||||
<target name="linux32-build" depends="linux-build" description="Build linux (32-bit) version">
|
||||
<!-- Unzip ARM tools -->
|
||||
<antcall target="unzip-arm-toolchain">
|
||||
<param name="dist_file" value="gcc-arm-none-eabi-4.7.4-2013q2-linux32.tar.gz" />
|
||||
<param name="dist_url" value="http://arduino.googlecode.com/files/gcc-arm-none-eabi-4.7.4-2013q2-linux32.tar.gz" />
|
||||
<param name="dist_check_file" value="gcc-arm-none-eabi-4.7.4-2013q2" />
|
||||
</antcall>
|
||||
|
||||
<!-- Unzip AVR tools -->
|
||||
<exec executable="tar" dir="linux/work/hardware">
|
||||
<arg value="-xjf"/>
|
||||
@ -499,6 +488,13 @@
|
||||
|
||||
<chmod perm="755" file="linux/work/hardware/tools/avrdude" />
|
||||
|
||||
<!-- Unzip ARM tools -->
|
||||
<antcall target="unzip-arm-toolchain">
|
||||
<param name="dist_file" value="gcc-arm-none-eabi-4.7.4-2013q2-linux64.tar.gz" />
|
||||
<param name="dist_url" value="http://arduino.googlecode.com/files/gcc-arm-none-eabi-4.7.4-2013q2-linux64.tar.gz" />
|
||||
<param name="dist_check_file" value="gcc-arm-none-eabi-4.7.4-2013q2" />
|
||||
</antcall>
|
||||
|
||||
<!-- Unzip AVR tools -->
|
||||
<exec executable="tar" dir="linux/work/hardware">
|
||||
<arg value="-xjf"/>
|
||||
@ -506,60 +502,47 @@
|
||||
</exec>
|
||||
</target>
|
||||
|
||||
<target name="linux32-run" depends="linux32-build"
|
||||
description="Run Linux (32-bit) version">
|
||||
<target name="linux32-run" depends="linux32-build" description="Run Linux (32-bit) version">
|
||||
<exec executable="./linux/work/arduino" spawn="false"/>
|
||||
</target>
|
||||
|
||||
<target name="linux64-run" depends="linux64-build"
|
||||
description="Run Linux (64-bit) version">
|
||||
<target name="linux64-run" depends="linux64-build" description="Run Linux (64-bit) version">
|
||||
<exec executable="./linux/work/arduino" spawn="false"/>
|
||||
</target>
|
||||
|
||||
<target name="linux-check-arm-toolchain-distfile">
|
||||
<available file="linux/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-linux32.tar.gz" property="arm_distfile_available" />
|
||||
<!-- Set 'arm_disfile_available' property if ARM toolchain dist_file is downloaded -->
|
||||
<!-- Set 'arm_toolchain_installed' property if ARM toolchain is installed in working directory -->
|
||||
<target name="check-arm-toolchain">
|
||||
<available file="${staging_folder}/dist/${dist_file}" property="arm_distfile_available" />
|
||||
<available file="${staging_folder}/work/hardware/tools/${dist_check_file}" property="arm_toolchain_installed" />
|
||||
</target>
|
||||
|
||||
<target name="linux-get-arm-toolchain" depends="linux-check-arm-toolchain-distfile" unless="arm_distfile_available">
|
||||
<!-- Retrieve ARM toolchain -->
|
||||
<get
|
||||
src="http://arduino.googlecode.com/files/gcc-arm-none-eabi-4.4.1-2010q1-188-linux32.tar.gz"
|
||||
dest="linux/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-linux32.tar.gz"
|
||||
verbose="true" />
|
||||
<!-- Retrieve ARM toolchain -->
|
||||
<target name="get-arm-toolchain" depends="check-arm-toolchain" unless="arm_distfile_available">
|
||||
<get src="${dist_url}" dest="${staging_folder}/dist/${dist_file}" verbose="true" />
|
||||
</target>
|
||||
|
||||
<target name="linux-check-arm-toolchain">
|
||||
<available file="linux/work/hardware/tools/g++_arm_none_eabi" property="arm_available" />
|
||||
</target>
|
||||
|
||||
<target name="linux-unzip-arm-toolchain" depends="linux-get-arm-toolchain, linux-check-arm-toolchain" unless="arm_available">
|
||||
<checksum file="linux/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-linux32.tar.gz" algorithm="sha"
|
||||
<target name="unzip-arm-toolchain" depends="get-arm-toolchain, check-arm-toolchain"
|
||||
unless="arm_toolchain_installed">
|
||||
<checksum file="${staging_folder}/dist/${dist_file}" algorithm="sha"
|
||||
fileext=".sha" verifyproperty="checksum.matches"/>
|
||||
<condition property="checksum.matches.fail">
|
||||
<equals arg1="${checksum.matches}" arg2="false"/>
|
||||
</condition>
|
||||
<fail if="checksum.matches.fail">Checksum failed.
|
||||
|
||||
File gcc-arm-none-eabi-4.4.1-2010q1-188-linux32.tar.gz failed checksum.
|
||||
Please remove "linux/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-linux32.tar.gz" to download it again.
|
||||
File ${dist_file} failed checksum.
|
||||
Please remove "${staging_folder}/dist/${dist_file}" to download it again.
|
||||
</fail>
|
||||
|
||||
<!-- Unzip toolchain to the destination folder -->
|
||||
<exec executable="tar" output="/dev/null" os="Linux">
|
||||
<arg value="xfz"/>
|
||||
<arg value="linux/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-linux32.tar.gz"/>
|
||||
<arg value="--directory=linux/work/hardware/tools"/>
|
||||
<arg value="${staging_folder}/dist/${dist_file}"/>
|
||||
<arg value="--directory=${staging_folder}/work/${staging_hardware_folder}/tools/"/>
|
||||
</exec>
|
||||
</target>
|
||||
|
||||
<target name="linux64-get-arm-toolchain" depends="linux-check-arm-toolchain-distfile" unless="arm_distfile_available">
|
||||
<antcall target="linux-get-arm-toolchain" />
|
||||
</target>
|
||||
|
||||
<target name="linux64-unzip-arm-toolchain" depends="linux-get-arm-toolchain" unless="arm_available">
|
||||
<antcall target="linux-unzip-arm-toolchain" />
|
||||
</target>
|
||||
|
||||
<target name="linux-dist" depends="build"
|
||||
description="Build .tar.gz of linux version">
|
||||
|
||||
@ -703,7 +686,12 @@
|
||||
<fileset dir="windows/work" includes="**/*.html, **/*.dll, **/*.exe" />
|
||||
</chmod>
|
||||
|
||||
<antcall target="windows-unzip-arm-toolchain" />
|
||||
<!-- Unzip ARM toolchain -->
|
||||
<antcall target="unzip-arm-toolchain">
|
||||
<param name="dist_file" value="gcc-arm-none-eabi-4.7.4-2013q2-windows.tar.gz" />
|
||||
<param name="dist_url" value="http://arduino.googlecode.com/files/gcc-arm-none-eabi-4.7.4-2013q2-windows.tar.gz" />
|
||||
<param name="dist_check_file" value="gcc-arm-none-eabi-4.7.4-2013q2" />
|
||||
</antcall>
|
||||
|
||||
<delete includeEmptyDirs="true" quiet="true">
|
||||
<fileset dir="windows/work/hardware/tools/avr/doc" />
|
||||
@ -716,42 +704,6 @@
|
||||
dir="windows/work" spawn="true"/>
|
||||
</target>
|
||||
|
||||
<target name="windows-check-arm-toolchain-distfile">
|
||||
<available file="windows/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-win32.tar.gz" property="arm_distfile_available" />
|
||||
</target>
|
||||
|
||||
<target name="windows-get-arm-toolchain" depends="windows-check-arm-toolchain-distfile" unless="arm_distfile_available">
|
||||
<!-- Retrieve ARM toolchain -->
|
||||
<get
|
||||
src="http://arduino.googlecode.com/files/gcc-arm-none-eabi-4.4.1-2010q1-188-win32.tar.gz"
|
||||
dest="windows/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-win32.tar.gz"
|
||||
verbose="true" />
|
||||
</target>
|
||||
|
||||
<target name="windows-check-arm-toolchain">
|
||||
<available file="windows/work/hardware/tools/g++_arm_none_eabi" property="arm_available" />
|
||||
</target>
|
||||
|
||||
<target name="windows-unzip-arm-toolchain" depends="windows-get-arm-toolchain, windows-check-arm-toolchain" unless="arm_available">
|
||||
<checksum file="windows/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-win32.tar.gz" algorithm="sha"
|
||||
fileext=".sha" verifyproperty="checksum.matches"/>
|
||||
<condition property="checksum.matches.fail">
|
||||
<equals arg1="${checksum.matches}" arg2="false"/>
|
||||
</condition>
|
||||
<fail if="checksum.matches.fail">Checksum failed.
|
||||
|
||||
File gcc-arm-none-eabi-4.4.1-2010q1-188-win32.tar.gz failed checksum.
|
||||
Please remove "windows/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-win32.tar.gz" to download it again.
|
||||
</fail>
|
||||
|
||||
<!-- Unzip toolchain to the destination folder -->
|
||||
<exec executable="tar">
|
||||
<arg value="xfz"/>
|
||||
<arg value="windows/dist/gcc-arm-none-eabi-4.4.1-2010q1-188-win32.tar.gz"/>
|
||||
<arg value="--directory=windows/work/hardware/tools"/>
|
||||
</exec>
|
||||
</target>
|
||||
|
||||
<target name="windows-dist" depends="windows-build"
|
||||
description="Create .zip files of windows version">
|
||||
|
||||
|
@ -1 +0,0 @@
|
||||
46a93ceec28772ac19c76ffc9b285a1eac4288a3
|
1
build/linux/dist/gcc-arm-none-eabi-4.7.4-2013q2-linux32.tar.gz.sha
vendored
Normal file
1
build/linux/dist/gcc-arm-none-eabi-4.7.4-2013q2-linux32.tar.gz.sha
vendored
Normal file
@ -0,0 +1 @@
|
||||
b35a6b9b1066977509ad5dcf51936b7a6bb18c18
|
1
build/linux/dist/gcc-arm-none-eabi-4.7.4-2013q2-linux64.tar.gz.sha
vendored
Normal file
1
build/linux/dist/gcc-arm-none-eabi-4.7.4-2013q2-linux64.tar.gz.sha
vendored
Normal file
@ -0,0 +1 @@
|
||||
14afebbb1a26b799237080ec32b300a409ff99cb
|
BIN
build/linux/dist/tools/bossac64
vendored
BIN
build/linux/dist/tools/bossac64
vendored
Binary file not shown.
@ -1 +0,0 @@
|
||||
14c554bb9aa9f0d0262a593e7452d33f4babc60d
|
1
build/macosx/dist/gcc-arm-none-eabi-4.7.4-2013q2-mac.tar.gz.sha
vendored
Normal file
1
build/macosx/dist/gcc-arm-none-eabi-4.7.4-2013q2-mac.tar.gz.sha
vendored
Normal file
@ -0,0 +1 @@
|
||||
a1326c6258f91d9b318570bc619ca8a3b799d8bc
|
@ -7,6 +7,10 @@ ARDUINO 1.5.3 BETA
|
||||
* Added support for new 1.5 Library format (https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification)
|
||||
* Pass board type from boards.txt (https://github.com/arduino/Arduino/issues/308)
|
||||
* Display estimated RAM usage after compile (Loren M. Lang)
|
||||
* Updated arm gcc to 4.7.4 and simplified build.xml
|
||||
* ARM gcc doesn't require ia32-libs anymore on 64 bits linux systems
|
||||
* Import library menu is now scrollable
|
||||
* Scrollable menus can now be scrolled with the mouse wheel
|
||||
|
||||
[arduino core]
|
||||
* sam: Fixed delayMicrosecond() when interrupts are disabled
|
||||
@ -18,11 +22,16 @@ ARDUINO 1.5.3 BETA
|
||||
* Added support for floating point numbers in String class (Tevin Zhang, SebiTimeWaster)
|
||||
* sam: Fixed String buffer overflows (Paul Stoffregen)
|
||||
* avr: Added recipe for assembly files (C. A. Church)
|
||||
* avr: Use analogPinToChannel if it's defined (Kristian Sloth Lauszus)
|
||||
* avr: Optimized HardwareSerial buffer (Matthijs Kooijman)
|
||||
* removed unused flags from String (free 1 byte of SRAM)
|
||||
|
||||
[libraries]
|
||||
* sam: Added CAN library (still in early stage of development) (Palliser)
|
||||
* sam: Bugfix SPI library: begin() after end() now works (stimmer)
|
||||
* sam: Bugfix SPI library: incorrent pin configuration in non-extended mode.
|
||||
* Ported all libraries to new 1.5 format
|
||||
* Updated Firmata to version 2.3.6 (Jeff Hoefs)
|
||||
|
||||
[firmwares]
|
||||
* Arduino Due: fixed USB2Serial garbage at startup (https://github.com/arduino/Arduino/pull/1267)
|
||||
|
@ -1 +0,0 @@
|
||||
f288affa058bfdd44f8b93800fc4cb01b2ebf1e5
|
1
build/windows/dist/gcc-arm-none-eabi-4.7.4-2013q2-windows.tar.gz.sha
vendored
Normal file
1
build/windows/dist/gcc-arm-none-eabi-4.7.4-2013q2-windows.tar.gz.sha
vendored
Normal file
@ -0,0 +1 @@
|
||||
c41fa509205b9ced43fc221b6a0cae4223a0842d
|
@ -663,10 +663,11 @@ robotControl.build.mcu=atmega32u4
|
||||
robotControl.build.f_cpu=16000000L
|
||||
robotControl.build.vid=0x2341
|
||||
robotControl.build.pid=0x8038
|
||||
robotControl.build.usb_product="Robot Control"
|
||||
robotControl.build.board=AVR_ROBOT_CONTROL
|
||||
robotControl.build.core=robot
|
||||
robotControl.build.core=arduino
|
||||
robotControl.build.variant=robot_control
|
||||
robotControl.build.extra_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid}
|
||||
robotControl.build.extra_flags={build.usb_flags}
|
||||
|
||||
##############################################################
|
||||
|
||||
@ -692,8 +693,9 @@ robotMotor.build.mcu=atmega32u4
|
||||
robotMotor.build.f_cpu=16000000L
|
||||
robotMotor.build.vid=0x2341
|
||||
robotMotor.build.pid=0x8039
|
||||
robotMotor.build.usb_product="Robot Motor"
|
||||
robotMotor.build.board=AVR_ROBOT_MOTOR
|
||||
robotMotor.build.core=robot
|
||||
robotMotor.build.core=arduino
|
||||
robotMotor.build.variant=robot_motor
|
||||
robotMotor.build.extra_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid}
|
||||
robotMotor.build.extra_flags={build.usb_flags}
|
||||
|
||||
|
@ -134,7 +134,6 @@ inline void String::init(void)
|
||||
buffer = NULL;
|
||||
capacity = 0;
|
||||
len = 0;
|
||||
flags = 0;
|
||||
}
|
||||
|
||||
void String::invalidate(void)
|
||||
|
@ -191,7 +191,6 @@ protected:
|
||||
char *buffer; // the actual char array
|
||||
unsigned int capacity; // the array length minus one (for the '\0')
|
||||
unsigned int len; // the String length (not counting the '\0')
|
||||
unsigned char flags; // unused, for future features
|
||||
protected:
|
||||
void init(void);
|
||||
void invalidate(void);
|
||||
|
@ -41,22 +41,22 @@ int analogRead(uint8_t pin)
|
||||
{
|
||||
uint8_t low, high;
|
||||
|
||||
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
|
||||
#if defined(analogPinToChannel)
|
||||
#if defined(__AVR_ATmega32U4__)
|
||||
if (pin >= 18) pin -= 18; // allow for channel or pin numbers
|
||||
#endif
|
||||
pin = analogPinToChannel(pin);
|
||||
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
|
||||
if (pin >= 54) pin -= 54; // allow for channel or pin numbers
|
||||
#elif defined(__AVR_ATmega32U4__)
|
||||
if (pin >= 18) pin -= 18; // allow for channel or pin numbers
|
||||
#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__)
|
||||
if (pin >= 24) pin -= 24; // allow for channel or pin numbers
|
||||
#elif defined(analogPinToChannel) && (defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__))
|
||||
pin = analogPinToChannel(pin);
|
||||
#else
|
||||
if (pin >= 14) pin -= 14; // allow for channel or pin numbers
|
||||
#endif
|
||||
|
||||
#if defined(__AVR_ATmega32U4__)
|
||||
pin = analogPinToChannel(pin);
|
||||
ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5);
|
||||
#elif defined(ADCSRB) && defined(MUX5)
|
||||
|
||||
#if defined(ADCSRB) && defined(MUX5)
|
||||
// the MUX5 bit of ADCSRB selects whether we're reading from channels
|
||||
// 0 to 7 (MUX5 low) or 8 to 15 (MUX5 high).
|
||||
ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5);
|
||||
|
@ -1,215 +0,0 @@
|
||||
#ifndef Arduino_h
|
||||
#define Arduino_h
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
#include <avr/pgmspace.h>
|
||||
#include <avr/io.h>
|
||||
#include <avr/interrupt.h>
|
||||
|
||||
#include "binary.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"{
|
||||
#endif
|
||||
|
||||
#define HIGH 0x1
|
||||
#define LOW 0x0
|
||||
|
||||
#define INPUT 0x0
|
||||
#define OUTPUT 0x1
|
||||
#define INPUT_PULLUP 0x2
|
||||
|
||||
#define true 0x1
|
||||
#define false 0x0
|
||||
|
||||
#define PI 3.1415926535897932384626433832795
|
||||
#define HALF_PI 1.5707963267948966192313216916398
|
||||
#define TWO_PI 6.283185307179586476925286766559
|
||||
#define DEG_TO_RAD 0.017453292519943295769236907684886
|
||||
#define RAD_TO_DEG 57.295779513082320876798154814105
|
||||
|
||||
#define SERIAL 0x0
|
||||
#define DISPLAY 0x1
|
||||
|
||||
#define LSBFIRST 0
|
||||
#define MSBFIRST 1
|
||||
|
||||
#define CHANGE 1
|
||||
#define FALLING 2
|
||||
#define RISING 3
|
||||
|
||||
#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
|
||||
#define DEFAULT 0
|
||||
#define EXTERNAL 1
|
||||
#define INTERNAL 2
|
||||
#else
|
||||
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__)
|
||||
#define INTERNAL1V1 2
|
||||
#define INTERNAL2V56 3
|
||||
#else
|
||||
#define INTERNAL 3
|
||||
#endif
|
||||
#define DEFAULT 1
|
||||
#define EXTERNAL 0
|
||||
#endif
|
||||
|
||||
// undefine stdlib's abs if encountered
|
||||
#ifdef abs
|
||||
#undef abs
|
||||
#endif
|
||||
|
||||
#define min(a,b) ((a)<(b)?(a):(b))
|
||||
#define max(a,b) ((a)>(b)?(a):(b))
|
||||
#define abs(x) ((x)>0?(x):-(x))
|
||||
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
|
||||
#define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
|
||||
#define radians(deg) ((deg)*DEG_TO_RAD)
|
||||
#define degrees(rad) ((rad)*RAD_TO_DEG)
|
||||
#define sq(x) ((x)*(x))
|
||||
|
||||
#define interrupts() sei()
|
||||
#define noInterrupts() cli()
|
||||
|
||||
#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
|
||||
#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )
|
||||
#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() )
|
||||
|
||||
#define lowByte(w) ((uint8_t) ((w) & 0xff))
|
||||
#define highByte(w) ((uint8_t) ((w) >> 8))
|
||||
|
||||
#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
|
||||
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
|
||||
#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
|
||||
#define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))
|
||||
|
||||
|
||||
typedef unsigned int word;
|
||||
|
||||
#define bit(b) (1UL << (b))
|
||||
|
||||
typedef uint8_t boolean;
|
||||
typedef uint8_t byte;
|
||||
|
||||
void init(void);
|
||||
|
||||
void pinMode(uint8_t, uint8_t);
|
||||
void digitalWrite(uint8_t, uint8_t);
|
||||
int digitalRead(uint8_t);
|
||||
int analogRead(uint8_t);
|
||||
void analogReference(uint8_t mode);
|
||||
void analogWrite(uint8_t, int);
|
||||
|
||||
unsigned long millis(void);
|
||||
unsigned long micros(void);
|
||||
void delay(unsigned long);
|
||||
void delayMicroseconds(unsigned int us);
|
||||
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);
|
||||
|
||||
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val);
|
||||
uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder);
|
||||
|
||||
void attachInterrupt(uint8_t, void (*)(void), int mode);
|
||||
void detachInterrupt(uint8_t);
|
||||
|
||||
void setup(void);
|
||||
void loop(void);
|
||||
|
||||
// Get the bit location within the hardware port of the given virtual pin.
|
||||
// This comes from the pins_*.c file for the active board configuration.
|
||||
|
||||
#define analogInPinToBit(P) (P)
|
||||
|
||||
// On the ATmega1280, the addresses of some of the port registers are
|
||||
// greater than 255, so we can't store them in uint8_t's.
|
||||
extern const uint16_t PROGMEM port_to_mode_PGM[];
|
||||
extern const uint16_t PROGMEM port_to_input_PGM[];
|
||||
extern const uint16_t PROGMEM port_to_output_PGM[];
|
||||
|
||||
extern const uint8_t PROGMEM digital_pin_to_port_PGM[];
|
||||
// extern const uint8_t PROGMEM digital_pin_to_bit_PGM[];
|
||||
extern const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[];
|
||||
extern const uint8_t PROGMEM digital_pin_to_timer_PGM[];
|
||||
|
||||
// Get the bit location within the hardware port of the given virtual pin.
|
||||
// This comes from the pins_*.c file for the active board configuration.
|
||||
//
|
||||
// These perform slightly better as macros compared to inline functions
|
||||
//
|
||||
#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )
|
||||
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )
|
||||
#define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )
|
||||
#define analogInPinToBit(P) (P)
|
||||
#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )
|
||||
#define portInputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_input_PGM + (P))) )
|
||||
#define portModeRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_mode_PGM + (P))) )
|
||||
|
||||
#define NOT_A_PIN 0
|
||||
#define NOT_A_PORT 0
|
||||
|
||||
#ifdef ARDUINO_MAIN
|
||||
#define PA 1
|
||||
#define PB 2
|
||||
#define PC 3
|
||||
#define PD 4
|
||||
#define PE 5
|
||||
#define PF 6
|
||||
#define PG 7
|
||||
#define PH 8
|
||||
#define PJ 10
|
||||
#define PK 11
|
||||
#define PL 12
|
||||
#endif
|
||||
|
||||
#define NOT_ON_TIMER 0
|
||||
#define TIMER0A 1
|
||||
#define TIMER0B 2
|
||||
#define TIMER1A 3
|
||||
#define TIMER1B 4
|
||||
#define TIMER2 5
|
||||
#define TIMER2A 6
|
||||
#define TIMER2B 7
|
||||
|
||||
#define TIMER3A 8
|
||||
#define TIMER3B 9
|
||||
#define TIMER3C 10
|
||||
#define TIMER4A 11
|
||||
#define TIMER4B 12
|
||||
#define TIMER4C 13
|
||||
#define TIMER4D 14
|
||||
#define TIMER5A 15
|
||||
#define TIMER5B 16
|
||||
#define TIMER5C 17
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include "WCharacter.h"
|
||||
#include "WString.h"
|
||||
#include "HardwareSerial.h"
|
||||
|
||||
uint16_t makeWord(uint16_t w);
|
||||
uint16_t makeWord(byte h, byte l);
|
||||
|
||||
#define word(...) makeWord(__VA_ARGS__)
|
||||
|
||||
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);
|
||||
|
||||
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0);
|
||||
void noTone(uint8_t _pin);
|
||||
|
||||
// WMath prototypes
|
||||
long random(long);
|
||||
long random(long, long);
|
||||
void randomSeed(unsigned int);
|
||||
long map(long, long, long, long, long);
|
||||
|
||||
#endif
|
||||
|
||||
#include "pins_arduino.h"
|
||||
|
||||
#endif
|
@ -1,220 +0,0 @@
|
||||
|
||||
|
||||
/* Copyright (c) 2011, Peter Barrett
|
||||
**
|
||||
** Permission to use, copy, modify, and/or distribute this software for
|
||||
** any purpose with or without fee is hereby granted, provided that the
|
||||
** above copyright notice and this permission notice appear in all copies.
|
||||
**
|
||||
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
|
||||
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
|
||||
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
|
||||
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
|
||||
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
||||
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
|
||||
** SOFTWARE.
|
||||
*/
|
||||
|
||||
#include "Platform.h"
|
||||
#include "USBAPI.h"
|
||||
#include <avr/wdt.h>
|
||||
|
||||
#if defined(USBCON)
|
||||
#ifdef CDC_ENABLED
|
||||
|
||||
typedef struct
|
||||
{
|
||||
u32 dwDTERate;
|
||||
u8 bCharFormat;
|
||||
u8 bParityType;
|
||||
u8 bDataBits;
|
||||
u8 lineState;
|
||||
} LineInfo;
|
||||
|
||||
static volatile LineInfo _usbLineInfo = { 57600, 0x00, 0x00, 0x00, 0x00 };
|
||||
|
||||
#define WEAK __attribute__ ((weak))
|
||||
|
||||
extern const CDCDescriptor _cdcInterface PROGMEM;
|
||||
const CDCDescriptor _cdcInterface =
|
||||
{
|
||||
D_IAD(0,2,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,1),
|
||||
|
||||
// CDC communication interface
|
||||
D_INTERFACE(CDC_ACM_INTERFACE,1,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0),
|
||||
D_CDCCS(CDC_HEADER,0x10,0x01), // Header (1.10 bcd)
|
||||
D_CDCCS(CDC_CALL_MANAGEMENT,1,1), // Device handles call management (not)
|
||||
D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT,6), // SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported
|
||||
D_CDCCS(CDC_UNION,CDC_ACM_INTERFACE,CDC_DATA_INTERFACE), // Communication interface is master, data interface is slave 0
|
||||
D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_ACM),USB_ENDPOINT_TYPE_INTERRUPT,0x10,0x40),
|
||||
|
||||
// CDC data interface
|
||||
D_INTERFACE(CDC_DATA_INTERFACE,2,CDC_DATA_INTERFACE_CLASS,0,0),
|
||||
D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT),USB_ENDPOINT_TYPE_BULK,0x40,0),
|
||||
D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ),USB_ENDPOINT_TYPE_BULK,0x40,0)
|
||||
};
|
||||
|
||||
int WEAK CDC_GetInterface(u8* interfaceNum)
|
||||
{
|
||||
interfaceNum[0] += 2; // uses 2
|
||||
return USB_SendControl(TRANSFER_PGM,&_cdcInterface,sizeof(_cdcInterface));
|
||||
}
|
||||
|
||||
bool WEAK CDC_Setup(Setup& setup)
|
||||
{
|
||||
u8 r = setup.bRequest;
|
||||
u8 requestType = setup.bmRequestType;
|
||||
|
||||
if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType)
|
||||
{
|
||||
if (CDC_GET_LINE_CODING == r)
|
||||
{
|
||||
USB_SendControl(0,(void*)&_usbLineInfo,7);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType)
|
||||
{
|
||||
if (CDC_SET_LINE_CODING == r)
|
||||
{
|
||||
USB_RecvControl((void*)&_usbLineInfo,7);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (CDC_SET_CONTROL_LINE_STATE == r)
|
||||
{
|
||||
_usbLineInfo.lineState = setup.wValueL;
|
||||
|
||||
// auto-reset into the bootloader is triggered when the port, already
|
||||
// open at 1200 bps, is closed. this is the signal to start the watchdog
|
||||
// with a relatively long period so it can finish housekeeping tasks
|
||||
// like servicing endpoints before the sketch ends
|
||||
if (1200 == _usbLineInfo.dwDTERate) {
|
||||
// We check DTR state to determine if host port is open (bit 0 of lineState).
|
||||
if ((_usbLineInfo.lineState & 0x01) == 0) {
|
||||
*(uint16_t *)0x0800 = 0x7777;
|
||||
wdt_enable(WDTO_120MS);
|
||||
} else {
|
||||
// Most OSs do some intermediate steps when configuring ports and DTR can
|
||||
// twiggle more than once before stabilizing.
|
||||
// To avoid spurious resets we set the watchdog to 250ms and eventually
|
||||
// cancel if DTR goes back high.
|
||||
|
||||
wdt_disable();
|
||||
wdt_reset();
|
||||
*(uint16_t *)0x0800 = 0x0;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
int _serialPeek = -1;
|
||||
void Serial_::begin(uint16_t baud_count)
|
||||
{
|
||||
}
|
||||
|
||||
void Serial_::end(void)
|
||||
{
|
||||
}
|
||||
|
||||
void Serial_::accept(void)
|
||||
{
|
||||
int i = (unsigned int)(_rx_buffer_head+1) % SERIAL_BUFFER_SIZE;
|
||||
|
||||
// if we should be storing the received character into the location
|
||||
// just before the tail (meaning that the head would advance to the
|
||||
// current location of the tail), we're about to overflow the buffer
|
||||
// and so we don't write the character or advance the head.
|
||||
|
||||
// while we have room to store a byte
|
||||
while (i != _rx_buffer_tail) {
|
||||
int c = USB_Recv(CDC_RX);
|
||||
if (c == -1)
|
||||
break; // no more data
|
||||
_rx_buffer[_rx_buffer_head] = c;
|
||||
_rx_buffer_head = i;
|
||||
|
||||
i = (unsigned int)(_rx_buffer_head+1) % SERIAL_BUFFER_SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
int Serial_::available(void)
|
||||
{
|
||||
return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer_head - _rx_buffer_tail) % SERIAL_BUFFER_SIZE;
|
||||
}
|
||||
|
||||
int Serial_::peek(void)
|
||||
{
|
||||
if (_rx_buffer_head == _rx_buffer_tail) {
|
||||
return -1;
|
||||
} else {
|
||||
return _rx_buffer[_rx_buffer_tail];
|
||||
}
|
||||
}
|
||||
|
||||
int Serial_::read(void)
|
||||
{
|
||||
// if the head isn't ahead of the tail, we don't have any characters
|
||||
if (_rx_buffer_head == _rx_buffer_tail) {
|
||||
return -1;
|
||||
} else {
|
||||
unsigned char c = _rx_buffer[_rx_buffer_tail];
|
||||
_rx_buffer_tail = (unsigned int)(_rx_buffer_tail + 1) % SERIAL_BUFFER_SIZE;
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
void Serial_::flush(void)
|
||||
{
|
||||
USB_Flush(CDC_TX);
|
||||
}
|
||||
|
||||
size_t Serial_::write(uint8_t c)
|
||||
{
|
||||
/* only try to send bytes if the high-level CDC connection itself
|
||||
is open (not just the pipe) - the OS should set lineState when the port
|
||||
is opened and clear lineState when the port is closed.
|
||||
bytes sent before the user opens the connection or after
|
||||
the connection is closed are lost - just like with a UART. */
|
||||
|
||||
// TODO - ZE - check behavior on different OSes and test what happens if an
|
||||
// open connection isn't broken cleanly (cable is yanked out, host dies
|
||||
// or locks up, or host virtual serial port hangs)
|
||||
if (_usbLineInfo.lineState > 0) {
|
||||
int r = USB_Send(CDC_TX,&c,1);
|
||||
if (r > 0) {
|
||||
return r;
|
||||
} else {
|
||||
setWriteError();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
setWriteError();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// This operator is a convenient way for a sketch to check whether the
|
||||
// port has actually been configured and opened by the host (as opposed
|
||||
// to just being connected to the host). It can be used, for example, in
|
||||
// setup() before printing to ensure that an application on the host is
|
||||
// actually ready to receive and display the data.
|
||||
// We add a short delay before returning to fix a bug observed by Federico
|
||||
// where the port is configured (lineState != 0) but not quite opened.
|
||||
Serial_::operator bool() {
|
||||
bool result = false;
|
||||
if (_usbLineInfo.lineState > 0)
|
||||
result = true;
|
||||
delay(10);
|
||||
return result;
|
||||
}
|
||||
|
||||
Serial_ Serial;
|
||||
|
||||
#endif
|
||||
#endif /* if defined(USBCON) */
|
@ -1,26 +0,0 @@
|
||||
#ifndef client_h
|
||||
#define client_h
|
||||
#include "Print.h"
|
||||
#include "Stream.h"
|
||||
#include "IPAddress.h"
|
||||
|
||||
class Client : public Stream {
|
||||
|
||||
public:
|
||||
virtual int connect(IPAddress ip, uint16_t port) =0;
|
||||
virtual int connect(const char *host, uint16_t port) =0;
|
||||
virtual size_t write(uint8_t) =0;
|
||||
virtual size_t write(const uint8_t *buf, size_t size) =0;
|
||||
virtual int available() = 0;
|
||||
virtual int read() = 0;
|
||||
virtual int read(uint8_t *buf, size_t size) = 0;
|
||||
virtual int peek() = 0;
|
||||
virtual void flush() = 0;
|
||||
virtual void stop() = 0;
|
||||
virtual uint8_t connected() = 0;
|
||||
virtual operator bool() = 0;
|
||||
protected:
|
||||
uint8_t* rawIPAddress(IPAddress& addr) { return addr.raw_address(); };
|
||||
};
|
||||
|
||||
#endif
|
@ -1,520 +0,0 @@
|
||||
|
||||
|
||||
/* Copyright (c) 2011, Peter Barrett
|
||||
**
|
||||
** Permission to use, copy, modify, and/or distribute this software for
|
||||
** any purpose with or without fee is hereby granted, provided that the
|
||||
** above copyright notice and this permission notice appear in all copies.
|
||||
**
|
||||
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
|
||||
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
|
||||
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
|
||||
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
|
||||
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
||||
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
|
||||
** SOFTWARE.
|
||||
*/
|
||||
|
||||
#include "Platform.h"
|
||||
#include "USBAPI.h"
|
||||
#include "USBDesc.h"
|
||||
|
||||
#if defined(USBCON)
|
||||
#ifdef HID_ENABLED
|
||||
|
||||
//#define RAWHID_ENABLED
|
||||
|
||||
// Singletons for mouse and keyboard
|
||||
|
||||
Mouse_ Mouse;
|
||||
Keyboard_ Keyboard;
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
|
||||
// HID report descriptor
|
||||
|
||||
#define LSB(_x) ((_x) & 0xFF)
|
||||
#define MSB(_x) ((_x) >> 8)
|
||||
|
||||
#define RAWHID_USAGE_PAGE 0xFFC0
|
||||
#define RAWHID_USAGE 0x0C00
|
||||
#define RAWHID_TX_SIZE 64
|
||||
#define RAWHID_RX_SIZE 64
|
||||
|
||||
extern const u8 _hidReportDescriptor[] PROGMEM;
|
||||
const u8 _hidReportDescriptor[] = {
|
||||
|
||||
// Mouse
|
||||
0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 54
|
||||
0x09, 0x02, // USAGE (Mouse)
|
||||
0xa1, 0x01, // COLLECTION (Application)
|
||||
0x09, 0x01, // USAGE (Pointer)
|
||||
0xa1, 0x00, // COLLECTION (Physical)
|
||||
0x85, 0x01, // REPORT_ID (1)
|
||||
0x05, 0x09, // USAGE_PAGE (Button)
|
||||
0x19, 0x01, // USAGE_MINIMUM (Button 1)
|
||||
0x29, 0x03, // USAGE_MAXIMUM (Button 3)
|
||||
0x15, 0x00, // LOGICAL_MINIMUM (0)
|
||||
0x25, 0x01, // LOGICAL_MAXIMUM (1)
|
||||
0x95, 0x03, // REPORT_COUNT (3)
|
||||
0x75, 0x01, // REPORT_SIZE (1)
|
||||
0x81, 0x02, // INPUT (Data,Var,Abs)
|
||||
0x95, 0x01, // REPORT_COUNT (1)
|
||||
0x75, 0x05, // REPORT_SIZE (5)
|
||||
0x81, 0x03, // INPUT (Cnst,Var,Abs)
|
||||
0x05, 0x01, // USAGE_PAGE (Generic Desktop)
|
||||
0x09, 0x30, // USAGE (X)
|
||||
0x09, 0x31, // USAGE (Y)
|
||||
0x09, 0x38, // USAGE (Wheel)
|
||||
0x15, 0x81, // LOGICAL_MINIMUM (-127)
|
||||
0x25, 0x7f, // LOGICAL_MAXIMUM (127)
|
||||
0x75, 0x08, // REPORT_SIZE (8)
|
||||
0x95, 0x03, // REPORT_COUNT (3)
|
||||
0x81, 0x06, // INPUT (Data,Var,Rel)
|
||||
0xc0, // END_COLLECTION
|
||||
0xc0, // END_COLLECTION
|
||||
|
||||
// Keyboard
|
||||
0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 47
|
||||
0x09, 0x06, // USAGE (Keyboard)
|
||||
0xa1, 0x01, // COLLECTION (Application)
|
||||
0x85, 0x02, // REPORT_ID (2)
|
||||
0x05, 0x07, // USAGE_PAGE (Keyboard)
|
||||
|
||||
0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl)
|
||||
0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI)
|
||||
0x15, 0x00, // LOGICAL_MINIMUM (0)
|
||||
0x25, 0x01, // LOGICAL_MAXIMUM (1)
|
||||
0x75, 0x01, // REPORT_SIZE (1)
|
||||
|
||||
0x95, 0x08, // REPORT_COUNT (8)
|
||||
0x81, 0x02, // INPUT (Data,Var,Abs)
|
||||
0x95, 0x01, // REPORT_COUNT (1)
|
||||
0x75, 0x08, // REPORT_SIZE (8)
|
||||
0x81, 0x03, // INPUT (Cnst,Var,Abs)
|
||||
|
||||
0x95, 0x06, // REPORT_COUNT (6)
|
||||
0x75, 0x08, // REPORT_SIZE (8)
|
||||
0x15, 0x00, // LOGICAL_MINIMUM (0)
|
||||
0x25, 0x65, // LOGICAL_MAXIMUM (101)
|
||||
0x05, 0x07, // USAGE_PAGE (Keyboard)
|
||||
|
||||
0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated))
|
||||
0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application)
|
||||
0x81, 0x00, // INPUT (Data,Ary,Abs)
|
||||
0xc0, // END_COLLECTION
|
||||
|
||||
#if RAWHID_ENABLED
|
||||
// RAW HID
|
||||
0x06, LSB(RAWHID_USAGE_PAGE), MSB(RAWHID_USAGE_PAGE), // 30
|
||||
0x0A, LSB(RAWHID_USAGE), MSB(RAWHID_USAGE),
|
||||
|
||||
0xA1, 0x01, // Collection 0x01
|
||||
0x85, 0x03, // REPORT_ID (3)
|
||||
0x75, 0x08, // report size = 8 bits
|
||||
0x15, 0x00, // logical minimum = 0
|
||||
0x26, 0xFF, 0x00, // logical maximum = 255
|
||||
|
||||
0x95, 64, // report count TX
|
||||
0x09, 0x01, // usage
|
||||
0x81, 0x02, // Input (array)
|
||||
|
||||
0x95, 64, // report count RX
|
||||
0x09, 0x02, // usage
|
||||
0x91, 0x02, // Output (array)
|
||||
0xC0 // end collection
|
||||
#endif
|
||||
};
|
||||
|
||||
extern const HIDDescriptor _hidInterface PROGMEM;
|
||||
const HIDDescriptor _hidInterface =
|
||||
{
|
||||
D_INTERFACE(HID_INTERFACE,1,3,0,0),
|
||||
D_HIDREPORT(sizeof(_hidReportDescriptor)),
|
||||
D_ENDPOINT(USB_ENDPOINT_IN (HID_ENDPOINT_INT),USB_ENDPOINT_TYPE_INTERRUPT,0x40,0x01)
|
||||
};
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
// Driver
|
||||
|
||||
u8 _hid_protocol = 1;
|
||||
u8 _hid_idle = 1;
|
||||
|
||||
#define WEAK __attribute__ ((weak))
|
||||
|
||||
int WEAK HID_GetInterface(u8* interfaceNum)
|
||||
{
|
||||
interfaceNum[0] += 1; // uses 1
|
||||
return USB_SendControl(TRANSFER_PGM,&_hidInterface,sizeof(_hidInterface));
|
||||
}
|
||||
|
||||
int WEAK HID_GetDescriptor(int i)
|
||||
{
|
||||
return USB_SendControl(TRANSFER_PGM,_hidReportDescriptor,sizeof(_hidReportDescriptor));
|
||||
}
|
||||
|
||||
void WEAK HID_SendReport(u8 id, const void* data, int len)
|
||||
{
|
||||
USB_Send(HID_TX, &id, 1);
|
||||
USB_Send(HID_TX | TRANSFER_RELEASE,data,len);
|
||||
}
|
||||
|
||||
bool WEAK HID_Setup(Setup& setup)
|
||||
{
|
||||
u8 r = setup.bRequest;
|
||||
u8 requestType = setup.bmRequestType;
|
||||
if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType)
|
||||
{
|
||||
if (HID_GET_REPORT == r)
|
||||
{
|
||||
//HID_GetReport();
|
||||
return true;
|
||||
}
|
||||
if (HID_GET_PROTOCOL == r)
|
||||
{
|
||||
//Send8(_hid_protocol); // TODO
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType)
|
||||
{
|
||||
if (HID_SET_PROTOCOL == r)
|
||||
{
|
||||
_hid_protocol = setup.wValueL;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (HID_SET_IDLE == r)
|
||||
{
|
||||
_hid_idle = setup.wValueL;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
// Mouse
|
||||
|
||||
Mouse_::Mouse_(void) : _buttons(0)
|
||||
{
|
||||
}
|
||||
|
||||
void Mouse_::begin(void)
|
||||
{
|
||||
}
|
||||
|
||||
void Mouse_::end(void)
|
||||
{
|
||||
}
|
||||
|
||||
void Mouse_::click(uint8_t b)
|
||||
{
|
||||
_buttons = b;
|
||||
move(0,0,0);
|
||||
_buttons = 0;
|
||||
move(0,0,0);
|
||||
}
|
||||
|
||||
void Mouse_::move(signed char x, signed char y, signed char wheel)
|
||||
{
|
||||
u8 m[4];
|
||||
m[0] = _buttons;
|
||||
m[1] = x;
|
||||
m[2] = y;
|
||||
m[3] = wheel;
|
||||
HID_SendReport(1,m,4);
|
||||
}
|
||||
|
||||
void Mouse_::buttons(uint8_t b)
|
||||
{
|
||||
if (b != _buttons)
|
||||
{
|
||||
_buttons = b;
|
||||
move(0,0,0);
|
||||
}
|
||||
}
|
||||
|
||||
void Mouse_::press(uint8_t b)
|
||||
{
|
||||
buttons(_buttons | b);
|
||||
}
|
||||
|
||||
void Mouse_::release(uint8_t b)
|
||||
{
|
||||
buttons(_buttons & ~b);
|
||||
}
|
||||
|
||||
bool Mouse_::isPressed(uint8_t b)
|
||||
{
|
||||
if ((b & _buttons) > 0)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
// Keyboard
|
||||
|
||||
Keyboard_::Keyboard_(void)
|
||||
{
|
||||
}
|
||||
|
||||
void Keyboard_::begin(void)
|
||||
{
|
||||
}
|
||||
|
||||
void Keyboard_::end(void)
|
||||
{
|
||||
}
|
||||
|
||||
void Keyboard_::sendReport(KeyReport* keys)
|
||||
{
|
||||
HID_SendReport(2,keys,sizeof(KeyReport));
|
||||
}
|
||||
|
||||
extern
|
||||
const uint8_t _asciimap[128] PROGMEM;
|
||||
|
||||
#define SHIFT 0x80
|
||||
const uint8_t _asciimap[128] =
|
||||
{
|
||||
0x00, // NUL
|
||||
0x00, // SOH
|
||||
0x00, // STX
|
||||
0x00, // ETX
|
||||
0x00, // EOT
|
||||
0x00, // ENQ
|
||||
0x00, // ACK
|
||||
0x00, // BEL
|
||||
0x2a, // BS Backspace
|
||||
0x2b, // TAB Tab
|
||||
0x28, // LF Enter
|
||||
0x00, // VT
|
||||
0x00, // FF
|
||||
0x00, // CR
|
||||
0x00, // SO
|
||||
0x00, // SI
|
||||
0x00, // DEL
|
||||
0x00, // DC1
|
||||
0x00, // DC2
|
||||
0x00, // DC3
|
||||
0x00, // DC4
|
||||
0x00, // NAK
|
||||
0x00, // SYN
|
||||
0x00, // ETB
|
||||
0x00, // CAN
|
||||
0x00, // EM
|
||||
0x00, // SUB
|
||||
0x00, // ESC
|
||||
0x00, // FS
|
||||
0x00, // GS
|
||||
0x00, // RS
|
||||
0x00, // US
|
||||
|
||||
0x2c, // ' '
|
||||
0x1e|SHIFT, // !
|
||||
0x34|SHIFT, // "
|
||||
0x20|SHIFT, // #
|
||||
0x21|SHIFT, // $
|
||||
0x22|SHIFT, // %
|
||||
0x24|SHIFT, // &
|
||||
0x34, // '
|
||||
0x26|SHIFT, // (
|
||||
0x27|SHIFT, // )
|
||||
0x25|SHIFT, // *
|
||||
0x2e|SHIFT, // +
|
||||
0x36, // ,
|
||||
0x2d, // -
|
||||
0x37, // .
|
||||
0x38, // /
|
||||
0x27, // 0
|
||||
0x1e, // 1
|
||||
0x1f, // 2
|
||||
0x20, // 3
|
||||
0x21, // 4
|
||||
0x22, // 5
|
||||
0x23, // 6
|
||||
0x24, // 7
|
||||
0x25, // 8
|
||||
0x26, // 9
|
||||
0x33|SHIFT, // :
|
||||
0x33, // ;
|
||||
0x36|SHIFT, // <
|
||||
0x2e, // =
|
||||
0x37|SHIFT, // >
|
||||
0x38|SHIFT, // ?
|
||||
0x1f|SHIFT, // @
|
||||
0x04|SHIFT, // A
|
||||
0x05|SHIFT, // B
|
||||
0x06|SHIFT, // C
|
||||
0x07|SHIFT, // D
|
||||
0x08|SHIFT, // E
|
||||
0x09|SHIFT, // F
|
||||
0x0a|SHIFT, // G
|
||||
0x0b|SHIFT, // H
|
||||
0x0c|SHIFT, // I
|
||||
0x0d|SHIFT, // J
|
||||
0x0e|SHIFT, // K
|
||||
0x0f|SHIFT, // L
|
||||
0x10|SHIFT, // M
|
||||
0x11|SHIFT, // N
|
||||
0x12|SHIFT, // O
|
||||
0x13|SHIFT, // P
|
||||
0x14|SHIFT, // Q
|
||||
0x15|SHIFT, // R
|
||||
0x16|SHIFT, // S
|
||||
0x17|SHIFT, // T
|
||||
0x18|SHIFT, // U
|
||||
0x19|SHIFT, // V
|
||||
0x1a|SHIFT, // W
|
||||
0x1b|SHIFT, // X
|
||||
0x1c|SHIFT, // Y
|
||||
0x1d|SHIFT, // Z
|
||||
0x2f, // [
|
||||
0x31, // bslash
|
||||
0x30, // ]
|
||||
0x23|SHIFT, // ^
|
||||
0x2d|SHIFT, // _
|
||||
0x35, // `
|
||||
0x04, // a
|
||||
0x05, // b
|
||||
0x06, // c
|
||||
0x07, // d
|
||||
0x08, // e
|
||||
0x09, // f
|
||||
0x0a, // g
|
||||
0x0b, // h
|
||||
0x0c, // i
|
||||
0x0d, // j
|
||||
0x0e, // k
|
||||
0x0f, // l
|
||||
0x10, // m
|
||||
0x11, // n
|
||||
0x12, // o
|
||||
0x13, // p
|
||||
0x14, // q
|
||||
0x15, // r
|
||||
0x16, // s
|
||||
0x17, // t
|
||||
0x18, // u
|
||||
0x19, // v
|
||||
0x1a, // w
|
||||
0x1b, // x
|
||||
0x1c, // y
|
||||
0x1d, // z
|
||||
0x2f|SHIFT, //
|
||||
0x31|SHIFT, // |
|
||||
0x30|SHIFT, // }
|
||||
0x35|SHIFT, // ~
|
||||
0 // DEL
|
||||
};
|
||||
|
||||
uint8_t USBPutChar(uint8_t c);
|
||||
|
||||
// press() adds the specified key (printing, non-printing, or modifier)
|
||||
// to the persistent key report and sends the report. Because of the way
|
||||
// USB HID works, the host acts like the key remains pressed until we
|
||||
// call release(), releaseAll(), or otherwise clear the report and resend.
|
||||
size_t Keyboard_::press(uint8_t k)
|
||||
{
|
||||
uint8_t i;
|
||||
if (k >= 136) { // it's a non-printing key (not a modifier)
|
||||
k = k - 136;
|
||||
} else if (k >= 128) { // it's a modifier key
|
||||
_keyReport.modifiers |= (1<<(k-128));
|
||||
k = 0;
|
||||
} else { // it's a printing key
|
||||
k = pgm_read_byte(_asciimap + k);
|
||||
if (!k) {
|
||||
setWriteError();
|
||||
return 0;
|
||||
}
|
||||
if (k & 0x80) { // it's a capital letter or other character reached with shift
|
||||
_keyReport.modifiers |= 0x02; // the left shift modifier
|
||||
k &= 0x7F;
|
||||
}
|
||||
}
|
||||
|
||||
// Add k to the key report only if it's not already present
|
||||
// and if there is an empty slot.
|
||||
if (_keyReport.keys[0] != k && _keyReport.keys[1] != k &&
|
||||
_keyReport.keys[2] != k && _keyReport.keys[3] != k &&
|
||||
_keyReport.keys[4] != k && _keyReport.keys[5] != k) {
|
||||
|
||||
for (i=0; i<6; i++) {
|
||||
if (_keyReport.keys[i] == 0x00) {
|
||||
_keyReport.keys[i] = k;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (i == 6) {
|
||||
setWriteError();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
sendReport(&_keyReport);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// release() takes the specified key out of the persistent key report and
|
||||
// sends the report. This tells the OS the key is no longer pressed and that
|
||||
// it shouldn't be repeated any more.
|
||||
size_t Keyboard_::release(uint8_t k)
|
||||
{
|
||||
uint8_t i;
|
||||
if (k >= 136) { // it's a non-printing key (not a modifier)
|
||||
k = k - 136;
|
||||
} else if (k >= 128) { // it's a modifier key
|
||||
_keyReport.modifiers &= ~(1<<(k-128));
|
||||
k = 0;
|
||||
} else { // it's a printing key
|
||||
k = pgm_read_byte(_asciimap + k);
|
||||
if (!k) {
|
||||
return 0;
|
||||
}
|
||||
if (k & 0x80) { // it's a capital letter or other character reached with shift
|
||||
_keyReport.modifiers &= ~(0x02); // the left shift modifier
|
||||
k &= 0x7F;
|
||||
}
|
||||
}
|
||||
|
||||
// Test the key report to see if k is present. Clear it if it exists.
|
||||
// Check all positions in case the key is present more than once (which it shouldn't be)
|
||||
for (i=0; i<6; i++) {
|
||||
if (0 != k && _keyReport.keys[i] == k) {
|
||||
_keyReport.keys[i] = 0x00;
|
||||
}
|
||||
}
|
||||
|
||||
sendReport(&_keyReport);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void Keyboard_::releaseAll(void)
|
||||
{
|
||||
_keyReport.keys[0] = 0;
|
||||
_keyReport.keys[1] = 0;
|
||||
_keyReport.keys[2] = 0;
|
||||
_keyReport.keys[3] = 0;
|
||||
_keyReport.keys[4] = 0;
|
||||
_keyReport.keys[5] = 0;
|
||||
_keyReport.modifiers = 0;
|
||||
sendReport(&_keyReport);
|
||||
}
|
||||
|
||||
size_t Keyboard_::write(uint8_t c)
|
||||
{
|
||||
uint8_t p = press(c); // Keydown
|
||||
uint8_t r = release(c); // Keyup
|
||||
return (p); // just return the result of press() since release() almost always returns 1
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#endif /* if defined(USBCON) */
|
@ -1,469 +0,0 @@
|
||||
/*
|
||||
HardwareSerial.cpp - Hardware serial library for Wiring
|
||||
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
Modified 23 November 2006 by David A. Mellis
|
||||
Modified 28 September 2010 by Mark Sproul
|
||||
Modified 14 August 2012 by Alarus
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <inttypes.h>
|
||||
#include "Arduino.h"
|
||||
#include "wiring_private.h"
|
||||
|
||||
// this next line disables the entire HardwareSerial.cpp,
|
||||
// this is so I can support Attiny series and any other chip without a uart
|
||||
#if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H)
|
||||
|
||||
#include "HardwareSerial.h"
|
||||
|
||||
/*
|
||||
* on ATmega8, the uart and its bits are not numbered, so there is no "TXC0"
|
||||
* definition.
|
||||
*/
|
||||
#if !defined(TXC0)
|
||||
#if defined(TXC)
|
||||
#define TXC0 TXC
|
||||
#elif defined(TXC1)
|
||||
// Some devices have uart1 but no uart0
|
||||
#define TXC0 TXC1
|
||||
#else
|
||||
#error TXC0 not definable in HardwareSerial.h
|
||||
#endif
|
||||
#endif
|
||||
|
||||
inline void store_char(unsigned char c, HardwareSerial *s)
|
||||
{
|
||||
int i = (unsigned int)(s->_rx_buffer_head + 1) % SERIAL_BUFFER_SIZE;
|
||||
|
||||
// if we should be storing the received character into the location
|
||||
// just before the tail (meaning that the head would advance to the
|
||||
// current location of the tail), we're about to overflow the buffer
|
||||
// and so we don't write the character or advance the head.
|
||||
if (i != s->_rx_buffer_tail) {
|
||||
s->_rx_buffer[s->_rx_buffer_head] = c;
|
||||
s->_rx_buffer_head = i;
|
||||
}
|
||||
}
|
||||
|
||||
#if !defined(USART0_RX_vect) && defined(USART1_RX_vect)
|
||||
// do nothing - on the 32u4 the first USART is USART1
|
||||
#else
|
||||
#if !defined(USART_RX_vect) && !defined(USART0_RX_vect) && \
|
||||
!defined(USART_RXC_vect)
|
||||
#error "Don't know what the Data Received vector is called for the first UART"
|
||||
#else
|
||||
void serialEvent() __attribute__((weak));
|
||||
void serialEvent() {}
|
||||
#define serialEvent_implemented
|
||||
#if defined(USART_RX_vect)
|
||||
ISR(USART_RX_vect)
|
||||
#elif defined(USART0_RX_vect)
|
||||
ISR(USART0_RX_vect)
|
||||
#elif defined(USART_RXC_vect)
|
||||
ISR(USART_RXC_vect) // ATmega8
|
||||
#endif
|
||||
{
|
||||
#if defined(UDR0)
|
||||
if (bit_is_clear(UCSR0A, UPE0)) {
|
||||
unsigned char c = UDR0;
|
||||
store_char(c, &Serial);
|
||||
} else {
|
||||
unsigned char c = UDR0;
|
||||
};
|
||||
#elif defined(UDR)
|
||||
if (bit_is_clear(UCSRA, PE)) {
|
||||
unsigned char c = UDR;
|
||||
store_char(c, &rx_buffer);
|
||||
} else {
|
||||
unsigned char c = UDR;
|
||||
};
|
||||
#else
|
||||
#error UDR not defined
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(USART1_RX_vect)
|
||||
void serialEvent1() __attribute__((weak));
|
||||
void serialEvent1() {}
|
||||
#define serialEvent1_implemented
|
||||
ISR(USART1_RX_vect)
|
||||
{
|
||||
if (bit_is_clear(UCSR1A, UPE1)) {
|
||||
unsigned char c = UDR1;
|
||||
store_char(c, &Serial1);
|
||||
} else {
|
||||
unsigned char c = UDR1;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(USART2_RX_vect) && defined(UDR2)
|
||||
void serialEvent2() __attribute__((weak));
|
||||
void serialEvent2() {}
|
||||
#define serialEvent2_implemented
|
||||
ISR(USART2_RX_vect)
|
||||
{
|
||||
if (bit_is_clear(UCSR2A, UPE2)) {
|
||||
unsigned char c = UDR2;
|
||||
store_char(c, &Serial2);
|
||||
} else {
|
||||
unsigned char c = UDR2;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(USART3_RX_vect) && defined(UDR3)
|
||||
void serialEvent3() __attribute__((weak));
|
||||
void serialEvent3() {}
|
||||
#define serialEvent3_implemented
|
||||
ISR(USART3_RX_vect)
|
||||
{
|
||||
if (bit_is_clear(UCSR3A, UPE3)) {
|
||||
unsigned char c = UDR3;
|
||||
store_char(c, &Serial3);
|
||||
} else {
|
||||
unsigned char c = UDR3;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
|
||||
void serialEventRun(void)
|
||||
{
|
||||
#ifdef serialEvent_implemented
|
||||
if (Serial.available()) serialEvent();
|
||||
#endif
|
||||
#ifdef serialEvent1_implemented
|
||||
if (Serial1.available()) serialEvent1();
|
||||
#endif
|
||||
#ifdef serialEvent2_implemented
|
||||
if (Serial2.available()) serialEvent2();
|
||||
#endif
|
||||
#ifdef serialEvent3_implemented
|
||||
if (Serial3.available()) serialEvent3();
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
#if !defined(USART0_UDRE_vect) && defined(USART1_UDRE_vect)
|
||||
// do nothing - on the 32u4 the first USART is USART1
|
||||
#else
|
||||
#if !defined(UART0_UDRE_vect) && !defined(UART_UDRE_vect) && !defined(USART0_UDRE_vect) && !defined(USART_UDRE_vect)
|
||||
#error "Don't know what the Data Register Empty vector is called for the first UART"
|
||||
#else
|
||||
#if defined(UART0_UDRE_vect)
|
||||
ISR(UART0_UDRE_vect)
|
||||
#elif defined(UART_UDRE_vect)
|
||||
ISR(UART_UDRE_vect)
|
||||
#elif defined(USART0_UDRE_vect)
|
||||
ISR(USART0_UDRE_vect)
|
||||
#elif defined(USART_UDRE_vect)
|
||||
ISR(USART_UDRE_vect)
|
||||
#endif
|
||||
{
|
||||
if (Serial._tx_buffer_head == Serial._tx_buffer_tail) {
|
||||
// Buffer empty, so disable interrupts
|
||||
#if defined(UCSR0B)
|
||||
cbi(UCSR0B, UDRIE0);
|
||||
#else
|
||||
cbi(UCSRB, UDRIE);
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
// There is more data in the output buffer. Send the next byte
|
||||
unsigned char c = Serial._tx_buffer[Serial._tx_buffer_tail];
|
||||
Serial._tx_buffer_tail = (Serial._tx_buffer_tail + 1) % SERIAL_BUFFER_SIZE;
|
||||
|
||||
#if defined(UDR0)
|
||||
UDR0 = c;
|
||||
#elif defined(UDR)
|
||||
UDR = c;
|
||||
#else
|
||||
#error UDR not defined
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef USART1_UDRE_vect
|
||||
ISR(USART1_UDRE_vect)
|
||||
{
|
||||
if (Serial1._tx_buffer_head == Serial1._tx_buffer_tail) {
|
||||
// Buffer empty, so disable interrupts
|
||||
cbi(UCSR1B, UDRIE1);
|
||||
}
|
||||
else {
|
||||
// There is more data in the output buffer. Send the next byte
|
||||
unsigned char c = Serial1._tx_buffer[Serial1._tx_buffer_tail];
|
||||
Serial1._tx_buffer_tail = (Serial1._tx_buffer_tail + 1) % SERIAL_BUFFER_SIZE;
|
||||
|
||||
UDR1 = c;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USART2_UDRE_vect
|
||||
ISR(USART2_UDRE_vect)
|
||||
{
|
||||
if (Serial2._tx_buffer_head == Serial2._tx_buffer_tail) {
|
||||
// Buffer empty, so disable interrupts
|
||||
cbi(UCSR2B, UDRIE2);
|
||||
}
|
||||
else {
|
||||
// There is more data in the output buffer. Send the next byte
|
||||
unsigned char c = Serial2._tx_buffer[Serial2._tx_buffer_tail];
|
||||
Serial2._tx_buffer_tail = (Serial2._tx_buffer_tail + 1) % SERIAL_BUFFER_SIZE;
|
||||
|
||||
UDR2 = c;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USART3_UDRE_vect
|
||||
ISR(USART3_UDRE_vect)
|
||||
{
|
||||
if (Serial3._tx_buffer_head == Serial3._tx_buffer_tail) {
|
||||
// Buffer empty, so disable interrupts
|
||||
cbi(UCSR3B, UDRIE3);
|
||||
}
|
||||
else {
|
||||
// There is more data in the output buffer. Send the next byte
|
||||
unsigned char c = Serial3._tx_buffer[Serial3._tx_buffer_tail];
|
||||
Serial3._tx_buffer_tail = (Serial3._tx_buffer_tail + 1) % SERIAL_BUFFER_SIZE;
|
||||
|
||||
UDR3 = c;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// Constructors ////////////////////////////////////////////////////////////////
|
||||
|
||||
HardwareSerial::HardwareSerial(
|
||||
volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
|
||||
volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
|
||||
volatile uint8_t *ucsrc, volatile uint8_t *udr,
|
||||
uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x)
|
||||
{
|
||||
_tx_buffer_head = _tx_buffer_tail = 0;
|
||||
_rx_buffer_head = _rx_buffer_tail = 0;
|
||||
_ubrrh = ubrrh;
|
||||
_ubrrl = ubrrl;
|
||||
_ucsra = ucsra;
|
||||
_ucsrb = ucsrb;
|
||||
_ucsrc = ucsrc;
|
||||
_udr = udr;
|
||||
_rxen = rxen;
|
||||
_txen = txen;
|
||||
_rxcie = rxcie;
|
||||
_udrie = udrie;
|
||||
_u2x = u2x;
|
||||
}
|
||||
|
||||
// Public Methods //////////////////////////////////////////////////////////////
|
||||
|
||||
void HardwareSerial::begin(unsigned long baud)
|
||||
{
|
||||
uint16_t baud_setting;
|
||||
bool use_u2x = true;
|
||||
|
||||
#if F_CPU == 16000000UL
|
||||
// hardcoded exception for compatibility with the bootloader shipped
|
||||
// with the Duemilanove and previous boards and the firmware on the 8U2
|
||||
// on the Uno and Mega 2560.
|
||||
if (baud == 57600) {
|
||||
use_u2x = false;
|
||||
}
|
||||
#endif
|
||||
|
||||
try_again:
|
||||
|
||||
if (use_u2x) {
|
||||
*_ucsra = 1 << _u2x;
|
||||
baud_setting = (F_CPU / 4 / baud - 1) / 2;
|
||||
} else {
|
||||
*_ucsra = 0;
|
||||
baud_setting = (F_CPU / 8 / baud - 1) / 2;
|
||||
}
|
||||
|
||||
if ((baud_setting > 4095) && use_u2x)
|
||||
{
|
||||
use_u2x = false;
|
||||
goto try_again;
|
||||
}
|
||||
|
||||
// assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)
|
||||
*_ubrrh = baud_setting >> 8;
|
||||
*_ubrrl = baud_setting;
|
||||
|
||||
transmitting = false;
|
||||
|
||||
sbi(*_ucsrb, _rxen);
|
||||
sbi(*_ucsrb, _txen);
|
||||
sbi(*_ucsrb, _rxcie);
|
||||
cbi(*_ucsrb, _udrie);
|
||||
}
|
||||
|
||||
void HardwareSerial::begin(unsigned long baud, byte config)
|
||||
{
|
||||
uint16_t baud_setting;
|
||||
uint8_t current_config;
|
||||
bool use_u2x = true;
|
||||
|
||||
#if F_CPU == 16000000UL
|
||||
// hardcoded exception for compatibility with the bootloader shipped
|
||||
// with the Duemilanove and previous boards and the firmware on the 8U2
|
||||
// on the Uno and Mega 2560.
|
||||
if (baud == 57600) {
|
||||
use_u2x = false;
|
||||
}
|
||||
#endif
|
||||
|
||||
try_again:
|
||||
|
||||
if (use_u2x) {
|
||||
*_ucsra = 1 << _u2x;
|
||||
baud_setting = (F_CPU / 4 / baud - 1) / 2;
|
||||
} else {
|
||||
*_ucsra = 0;
|
||||
baud_setting = (F_CPU / 8 / baud - 1) / 2;
|
||||
}
|
||||
|
||||
if ((baud_setting > 4095) && use_u2x)
|
||||
{
|
||||
use_u2x = false;
|
||||
goto try_again;
|
||||
}
|
||||
|
||||
// assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)
|
||||
*_ubrrh = baud_setting >> 8;
|
||||
*_ubrrl = baud_setting;
|
||||
|
||||
//set the data bits, parity, and stop bits
|
||||
#if defined(__AVR_ATmega8__)
|
||||
config |= 0x80; // select UCSRC register (shared with UBRRH)
|
||||
#endif
|
||||
*_ucsrc = config;
|
||||
|
||||
sbi(*_ucsrb, _rxen);
|
||||
sbi(*_ucsrb, _txen);
|
||||
sbi(*_ucsrb, _rxcie);
|
||||
cbi(*_ucsrb, _udrie);
|
||||
}
|
||||
|
||||
void HardwareSerial::end()
|
||||
{
|
||||
// wait for transmission of outgoing data
|
||||
while (_tx_buffer_head != _tx_buffer_tail)
|
||||
;
|
||||
|
||||
cbi(*_ucsrb, _rxen);
|
||||
cbi(*_ucsrb, _txen);
|
||||
cbi(*_ucsrb, _rxcie);
|
||||
cbi(*_ucsrb, _udrie);
|
||||
|
||||
// clear any received data
|
||||
_rx_buffer_head = _rx_buffer_tail;
|
||||
}
|
||||
|
||||
int HardwareSerial::available(void)
|
||||
{
|
||||
return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer_head - _rx_buffer_tail) % SERIAL_BUFFER_SIZE;
|
||||
}
|
||||
|
||||
int HardwareSerial::peek(void)
|
||||
{
|
||||
if (_rx_buffer_head == _rx_buffer_tail) {
|
||||
return -1;
|
||||
} else {
|
||||
return _rx_buffer[_rx_buffer_tail];
|
||||
}
|
||||
}
|
||||
|
||||
int HardwareSerial::read(void)
|
||||
{
|
||||
// if the head isn't ahead of the tail, we don't have any characters
|
||||
if (_rx_buffer_head == _rx_buffer_tail) {
|
||||
return -1;
|
||||
} else {
|
||||
unsigned char c = _rx_buffer[_rx_buffer_tail];
|
||||
_rx_buffer_tail = (unsigned int)(_rx_buffer_tail + 1) % SERIAL_BUFFER_SIZE;
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
void HardwareSerial::flush()
|
||||
{
|
||||
// UDR is kept full while the buffer is not empty, so TXC triggers when EMPTY && SENT
|
||||
while (transmitting && ! (*_ucsra & _BV(TXC0)));
|
||||
transmitting = false;
|
||||
}
|
||||
|
||||
size_t HardwareSerial::write(uint8_t c)
|
||||
{
|
||||
int i = (_tx_buffer_head + 1) % SERIAL_BUFFER_SIZE;
|
||||
|
||||
// If the output buffer is full, there's nothing for it other than to
|
||||
// wait for the interrupt handler to empty it a bit
|
||||
// ???: return 0 here instead?
|
||||
while (i == _tx_buffer_tail)
|
||||
;
|
||||
|
||||
_tx_buffer[_tx_buffer_head] = c;
|
||||
_tx_buffer_head = i;
|
||||
|
||||
sbi(*_ucsrb, _udrie);
|
||||
// clear the TXC bit -- "can be cleared by writing a one to its bit location"
|
||||
transmitting = true;
|
||||
sbi(*_ucsra, TXC0);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
HardwareSerial::operator bool() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Preinstantiate Objects //////////////////////////////////////////////////////
|
||||
|
||||
#if defined(UBRRH) && defined(UBRRL)
|
||||
HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR, RXEN, TXEN, RXCIE, UDRIE, U2X);
|
||||
#elif defined(UBRR0H) && defined(UBRR0L)
|
||||
HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0, RXEN0, TXEN0, RXCIE0, UDRIE0, U2X0);
|
||||
#elif defined(USBCON)
|
||||
// do nothing - Serial object and buffers are initialized in CDC code
|
||||
#else
|
||||
#error no serial port defined (port 0)
|
||||
#endif
|
||||
|
||||
#if defined(UBRR1H)
|
||||
HardwareSerial Serial1(&UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1);
|
||||
#endif
|
||||
#if defined(UBRR2H)
|
||||
HardwareSerial Serial2(&UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UCSR2C, &UDR2, RXEN2, TXEN2, RXCIE2, UDRIE2, U2X2);
|
||||
#endif
|
||||
#if defined(UBRR3H)
|
||||
HardwareSerial Serial3(&UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UCSR3C, &UDR3, RXEN3, TXEN3, RXCIE3, UDRIE3, U2X3);
|
||||
#endif
|
||||
|
||||
#endif // whole file
|
||||
|
@ -1,133 +0,0 @@
|
||||
/*
|
||||
HardwareSerial.h - Hardware serial library for Wiring
|
||||
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
Modified 28 September 2010 by Mark Sproul
|
||||
Modified 14 August 2012 by Alarus
|
||||
*/
|
||||
|
||||
#ifndef HardwareSerial_h
|
||||
#define HardwareSerial_h
|
||||
|
||||
#include <inttypes.h>
|
||||
|
||||
#include "Stream.h"
|
||||
|
||||
// Define constants and variables for buffering incoming serial data. We're
|
||||
// using a ring buffer (I think), in which head is the index of the location
|
||||
// to which to write the next incoming character and tail is the index of the
|
||||
// location from which to read.
|
||||
#if (RAMEND < 1000)
|
||||
#define SERIAL_BUFFER_SIZE 16
|
||||
#else
|
||||
#define SERIAL_BUFFER_SIZE 64
|
||||
#endif
|
||||
|
||||
class HardwareSerial : public Stream
|
||||
{
|
||||
protected:
|
||||
volatile uint8_t *_ubrrh;
|
||||
volatile uint8_t *_ubrrl;
|
||||
volatile uint8_t *_ucsra;
|
||||
volatile uint8_t *_ucsrb;
|
||||
volatile uint8_t *_ucsrc;
|
||||
volatile uint8_t *_udr;
|
||||
uint8_t _rxen;
|
||||
uint8_t _txen;
|
||||
uint8_t _rxcie;
|
||||
uint8_t _udrie;
|
||||
uint8_t _u2x;
|
||||
bool transmitting;
|
||||
|
||||
public:
|
||||
volatile uint8_t _rx_buffer_head;
|
||||
volatile uint8_t _rx_buffer_tail;
|
||||
volatile uint8_t _tx_buffer_head;
|
||||
volatile uint8_t _tx_buffer_tail;
|
||||
|
||||
// Don't put any members after these buffers, since only the first
|
||||
// 32 bytes of this struct can be accessed quickly using the ldd
|
||||
// instruction.
|
||||
unsigned char _rx_buffer[SERIAL_BUFFER_SIZE];
|
||||
unsigned char _tx_buffer[SERIAL_BUFFER_SIZE];
|
||||
|
||||
HardwareSerial(
|
||||
volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
|
||||
volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
|
||||
volatile uint8_t *ucsrc, volatile uint8_t *udr,
|
||||
uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x);
|
||||
void begin(unsigned long);
|
||||
void begin(unsigned long, uint8_t);
|
||||
void end();
|
||||
virtual int available(void);
|
||||
virtual int peek(void);
|
||||
virtual int read(void);
|
||||
virtual void flush(void);
|
||||
virtual size_t write(uint8_t);
|
||||
inline size_t write(unsigned long n) { return write((uint8_t)n); }
|
||||
inline size_t write(long n) { return write((uint8_t)n); }
|
||||
inline size_t write(unsigned int n) { return write((uint8_t)n); }
|
||||
inline size_t write(int n) { return write((uint8_t)n); }
|
||||
using Print::write; // pull in write(str) and write(buf, size) from Print
|
||||
operator bool();
|
||||
};
|
||||
|
||||
// Define config for Serial.begin(baud, config);
|
||||
#define SERIAL_5N1 0x00
|
||||
#define SERIAL_6N1 0x02
|
||||
#define SERIAL_7N1 0x04
|
||||
#define SERIAL_8N1 0x06
|
||||
#define SERIAL_5N2 0x08
|
||||
#define SERIAL_6N2 0x0A
|
||||
#define SERIAL_7N2 0x0C
|
||||
#define SERIAL_8N2 0x0E
|
||||
#define SERIAL_5E1 0x20
|
||||
#define SERIAL_6E1 0x22
|
||||
#define SERIAL_7E1 0x24
|
||||
#define SERIAL_8E1 0x26
|
||||
#define SERIAL_5E2 0x28
|
||||
#define SERIAL_6E2 0x2A
|
||||
#define SERIAL_7E2 0x2C
|
||||
#define SERIAL_8E2 0x2E
|
||||
#define SERIAL_5O1 0x30
|
||||
#define SERIAL_6O1 0x32
|
||||
#define SERIAL_7O1 0x34
|
||||
#define SERIAL_8O1 0x36
|
||||
#define SERIAL_5O2 0x38
|
||||
#define SERIAL_6O2 0x3A
|
||||
#define SERIAL_7O2 0x3C
|
||||
#define SERIAL_8O2 0x3E
|
||||
|
||||
#if defined(UBRRH) || defined(UBRR0H)
|
||||
extern HardwareSerial Serial;
|
||||
#elif defined(USBCON)
|
||||
#include "USBAPI.h"
|
||||
// extern HardwareSerial Serial_;
|
||||
#endif
|
||||
#if defined(UBRR1H)
|
||||
extern HardwareSerial Serial1;
|
||||
#endif
|
||||
#if defined(UBRR2H)
|
||||
extern HardwareSerial Serial2;
|
||||
#endif
|
||||
#if defined(UBRR3H)
|
||||
extern HardwareSerial Serial3;
|
||||
#endif
|
||||
|
||||
extern void serialEventRun(void) __attribute__((weak));
|
||||
|
||||
#endif
|
@ -1,56 +0,0 @@
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <IPAddress.h>
|
||||
|
||||
IPAddress::IPAddress()
|
||||
{
|
||||
memset(_address, 0, sizeof(_address));
|
||||
}
|
||||
|
||||
IPAddress::IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet)
|
||||
{
|
||||
_address[0] = first_octet;
|
||||
_address[1] = second_octet;
|
||||
_address[2] = third_octet;
|
||||
_address[3] = fourth_octet;
|
||||
}
|
||||
|
||||
IPAddress::IPAddress(uint32_t address)
|
||||
{
|
||||
memcpy(_address, &address, sizeof(_address));
|
||||
}
|
||||
|
||||
IPAddress::IPAddress(const uint8_t *address)
|
||||
{
|
||||
memcpy(_address, address, sizeof(_address));
|
||||
}
|
||||
|
||||
IPAddress& IPAddress::operator=(const uint8_t *address)
|
||||
{
|
||||
memcpy(_address, address, sizeof(_address));
|
||||
return *this;
|
||||
}
|
||||
|
||||
IPAddress& IPAddress::operator=(uint32_t address)
|
||||
{
|
||||
memcpy(_address, (const uint8_t *)&address, sizeof(_address));
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool IPAddress::operator==(const uint8_t* addr)
|
||||
{
|
||||
return memcmp(addr, _address, sizeof(_address)) == 0;
|
||||
}
|
||||
|
||||
size_t IPAddress::printTo(Print& p) const
|
||||
{
|
||||
size_t n = 0;
|
||||
for (int i =0; i < 3; i++)
|
||||
{
|
||||
n += p.print(_address[i], DEC);
|
||||
n += p.print('.');
|
||||
}
|
||||
n += p.print(_address[3], DEC);
|
||||
return n;
|
||||
}
|
||||
|
@ -1,76 +0,0 @@
|
||||
/*
|
||||
*
|
||||
* MIT License:
|
||||
* Copyright (c) 2011 Adrian McEwen
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
* adrianm@mcqn.com 1/1/2011
|
||||
*/
|
||||
|
||||
#ifndef IPAddress_h
|
||||
#define IPAddress_h
|
||||
|
||||
#include <Printable.h>
|
||||
|
||||
// A class to make it easier to handle and pass around IP addresses
|
||||
|
||||
class IPAddress : public Printable {
|
||||
private:
|
||||
uint8_t _address[4]; // IPv4 address
|
||||
// Access the raw byte array containing the address. Because this returns a pointer
|
||||
// to the internal structure rather than a copy of the address this function should only
|
||||
// be used when you know that the usage of the returned uint8_t* will be transient and not
|
||||
// stored.
|
||||
uint8_t* raw_address() { return _address; };
|
||||
|
||||
public:
|
||||
// Constructors
|
||||
IPAddress();
|
||||
IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet);
|
||||
IPAddress(uint32_t address);
|
||||
IPAddress(const uint8_t *address);
|
||||
|
||||
// Overloaded cast operator to allow IPAddress objects to be used where a pointer
|
||||
// to a four-byte uint8_t array is expected
|
||||
operator uint32_t() { return *((uint32_t*)_address); };
|
||||
bool operator==(const IPAddress& addr) { return (*((uint32_t*)_address)) == (*((uint32_t*)addr._address)); };
|
||||
bool operator==(const uint8_t* addr);
|
||||
|
||||
// Overloaded index operator to allow getting and setting individual octets of the address
|
||||
uint8_t operator[](int index) const { return _address[index]; };
|
||||
uint8_t& operator[](int index) { return _address[index]; };
|
||||
|
||||
// Overloaded copy operators to allow initialisation of IPAddress objects from other types
|
||||
IPAddress& operator=(const uint8_t *address);
|
||||
IPAddress& operator=(uint32_t address);
|
||||
|
||||
virtual size_t printTo(Print& p) const;
|
||||
|
||||
friend class EthernetClass;
|
||||
friend class UDP;
|
||||
friend class Client;
|
||||
friend class Server;
|
||||
friend class DhcpClass;
|
||||
friend class DNSClient;
|
||||
};
|
||||
|
||||
const IPAddress INADDR_NONE(0,0,0,0);
|
||||
|
||||
|
||||
#endif
|
@ -1,23 +0,0 @@
|
||||
|
||||
#ifndef __PLATFORM_H__
|
||||
#define __PLATFORM_H__
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <avr/pgmspace.h>
|
||||
#include <avr/eeprom.h>
|
||||
#include <avr/interrupt.h>
|
||||
#include <util/delay.h>
|
||||
|
||||
typedef unsigned char u8;
|
||||
typedef unsigned short u16;
|
||||
typedef unsigned long u32;
|
||||
|
||||
#include "Arduino.h"
|
||||
|
||||
#if defined(USBCON)
|
||||
#include "USBDesc.h"
|
||||
#include "USBCore.h"
|
||||
#include "USBAPI.h"
|
||||
#endif /* if defined(USBCON) */
|
||||
|
||||
#endif
|
@ -1,268 +0,0 @@
|
||||
/*
|
||||
Print.cpp - Base class that provides print() and println()
|
||||
Copyright (c) 2008 David A. Mellis. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
Modified 23 November 2006 by David A. Mellis
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
#include "Arduino.h"
|
||||
|
||||
#include "Print.h"
|
||||
|
||||
// Public Methods //////////////////////////////////////////////////////////////
|
||||
|
||||
/* default implementation: may be overridden */
|
||||
size_t Print::write(const uint8_t *buffer, size_t size)
|
||||
{
|
||||
size_t n = 0;
|
||||
while (size--) {
|
||||
n += write(*buffer++);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::print(const __FlashStringHelper *ifsh)
|
||||
{
|
||||
const char PROGMEM *p = (const char PROGMEM *)ifsh;
|
||||
size_t n = 0;
|
||||
while (1) {
|
||||
unsigned char c = pgm_read_byte(p++);
|
||||
if (c == 0) break;
|
||||
n += write(c);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::print(const String &s)
|
||||
{
|
||||
size_t n = 0;
|
||||
for (uint16_t i = 0; i < s.length(); i++) {
|
||||
n += write(s[i]);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::print(const char str[])
|
||||
{
|
||||
return write(str);
|
||||
}
|
||||
|
||||
size_t Print::print(char c)
|
||||
{
|
||||
return write(c);
|
||||
}
|
||||
|
||||
size_t Print::print(unsigned char b, int base)
|
||||
{
|
||||
return print((unsigned long) b, base);
|
||||
}
|
||||
|
||||
size_t Print::print(int n, int base)
|
||||
{
|
||||
return print((long) n, base);
|
||||
}
|
||||
|
||||
size_t Print::print(unsigned int n, int base)
|
||||
{
|
||||
return print((unsigned long) n, base);
|
||||
}
|
||||
|
||||
size_t Print::print(long n, int base)
|
||||
{
|
||||
if (base == 0) {
|
||||
return write(n);
|
||||
} else if (base == 10) {
|
||||
if (n < 0) {
|
||||
int t = print('-');
|
||||
n = -n;
|
||||
return printNumber(n, 10) + t;
|
||||
}
|
||||
return printNumber(n, 10);
|
||||
} else {
|
||||
return printNumber(n, base);
|
||||
}
|
||||
}
|
||||
|
||||
size_t Print::print(unsigned long n, int base)
|
||||
{
|
||||
if (base == 0) return write(n);
|
||||
else return printNumber(n, base);
|
||||
}
|
||||
|
||||
size_t Print::print(double n, int digits)
|
||||
{
|
||||
return printFloat(n, digits);
|
||||
}
|
||||
|
||||
size_t Print::println(const __FlashStringHelper *ifsh)
|
||||
{
|
||||
size_t n = print(ifsh);
|
||||
n += println();
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::print(const Printable& x)
|
||||
{
|
||||
return x.printTo(*this);
|
||||
}
|
||||
|
||||
size_t Print::println(void)
|
||||
{
|
||||
size_t n = print('\r');
|
||||
n += print('\n');
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::println(const String &s)
|
||||
{
|
||||
size_t n = print(s);
|
||||
n += println();
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::println(const char c[])
|
||||
{
|
||||
size_t n = print(c);
|
||||
n += println();
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::println(char c)
|
||||
{
|
||||
size_t n = print(c);
|
||||
n += println();
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::println(unsigned char b, int base)
|
||||
{
|
||||
size_t n = print(b, base);
|
||||
n += println();
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::println(int num, int base)
|
||||
{
|
||||
size_t n = print(num, base);
|
||||
n += println();
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::println(unsigned int num, int base)
|
||||
{
|
||||
size_t n = print(num, base);
|
||||
n += println();
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::println(long num, int base)
|
||||
{
|
||||
size_t n = print(num, base);
|
||||
n += println();
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::println(unsigned long num, int base)
|
||||
{
|
||||
size_t n = print(num, base);
|
||||
n += println();
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::println(double num, int digits)
|
||||
{
|
||||
size_t n = print(num, digits);
|
||||
n += println();
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Print::println(const Printable& x)
|
||||
{
|
||||
size_t n = print(x);
|
||||
n += println();
|
||||
return n;
|
||||
}
|
||||
|
||||
// Private Methods /////////////////////////////////////////////////////////////
|
||||
|
||||
size_t Print::printNumber(unsigned long n, uint8_t base) {
|
||||
char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
|
||||
char *str = &buf[sizeof(buf) - 1];
|
||||
|
||||
*str = '\0';
|
||||
|
||||
// prevent crash if called with base == 1
|
||||
if (base < 2) base = 10;
|
||||
|
||||
do {
|
||||
unsigned long m = n;
|
||||
n /= base;
|
||||
char c = m - base * n;
|
||||
*--str = c < 10 ? c + '0' : c + 'A' - 10;
|
||||
} while(n);
|
||||
|
||||
return write(str);
|
||||
}
|
||||
|
||||
size_t Print::printFloat(double number, uint8_t digits)
|
||||
{
|
||||
size_t n = 0;
|
||||
|
||||
if (isnan(number)) return print("nan");
|
||||
if (isinf(number)) return print("inf");
|
||||
if (number > 4294967040.0) return print ("ovf"); // constant determined empirically
|
||||
if (number <-4294967040.0) return print ("ovf"); // constant determined empirically
|
||||
|
||||
// Handle negative numbers
|
||||
if (number < 0.0)
|
||||
{
|
||||
n += print('-');
|
||||
number = -number;
|
||||
}
|
||||
|
||||
// Round correctly so that print(1.999, 2) prints as "2.00"
|
||||
double rounding = 0.5;
|
||||
for (uint8_t i=0; i<digits; ++i)
|
||||
rounding /= 10.0;
|
||||
|
||||
number += rounding;
|
||||
|
||||
// Extract the integer part of the number and print it
|
||||
unsigned long int_part = (unsigned long)number;
|
||||
double remainder = number - (double)int_part;
|
||||
n += print(int_part);
|
||||
|
||||
// Print the decimal point, but only if there are digits beyond
|
||||
if (digits > 0) {
|
||||
n += print(".");
|
||||
}
|
||||
|
||||
// Extract digits from the remainder one at a time
|
||||
while (digits-- > 0)
|
||||
{
|
||||
remainder *= 10.0;
|
||||
int toPrint = int(remainder);
|
||||
n += print(toPrint);
|
||||
remainder -= toPrint;
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
@ -1,81 +0,0 @@
|
||||
/*
|
||||
Print.h - Base class that provides print() and println()
|
||||
Copyright (c) 2008 David A. Mellis. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#ifndef Print_h
|
||||
#define Print_h
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <stdio.h> // for size_t
|
||||
|
||||
#include "WString.h"
|
||||
#include "Printable.h"
|
||||
|
||||
#define DEC 10
|
||||
#define HEX 16
|
||||
#define OCT 8
|
||||
#define BIN 2
|
||||
|
||||
class Print
|
||||
{
|
||||
private:
|
||||
int write_error;
|
||||
size_t printNumber(unsigned long, uint8_t);
|
||||
size_t printFloat(double, uint8_t);
|
||||
protected:
|
||||
void setWriteError(int err = 1) { write_error = err; }
|
||||
public:
|
||||
Print() : write_error(0) {}
|
||||
|
||||
int getWriteError() { return write_error; }
|
||||
void clearWriteError() { setWriteError(0); }
|
||||
|
||||
virtual size_t write(uint8_t) = 0;
|
||||
size_t write(const char *str) {
|
||||
if (str == NULL) return 0;
|
||||
return write((const uint8_t *)str, strlen(str));
|
||||
}
|
||||
virtual size_t write(const uint8_t *buffer, size_t size);
|
||||
|
||||
size_t print(const __FlashStringHelper *);
|
||||
size_t print(const String &);
|
||||
size_t print(const char[]);
|
||||
size_t print(char);
|
||||
size_t print(unsigned char, int = DEC);
|
||||
size_t print(int, int = DEC);
|
||||
size_t print(unsigned int, int = DEC);
|
||||
size_t print(long, int = DEC);
|
||||
size_t print(unsigned long, int = DEC);
|
||||
size_t print(double, int = 2);
|
||||
size_t print(const Printable&);
|
||||
|
||||
size_t println(const __FlashStringHelper *);
|
||||
size_t println(const String &s);
|
||||
size_t println(const char[]);
|
||||
size_t println(char);
|
||||
size_t println(unsigned char, int = DEC);
|
||||
size_t println(int, int = DEC);
|
||||
size_t println(unsigned int, int = DEC);
|
||||
size_t println(long, int = DEC);
|
||||
size_t println(unsigned long, int = DEC);
|
||||
size_t println(double, int = 2);
|
||||
size_t println(const Printable&);
|
||||
size_t println(void);
|
||||
};
|
||||
|
||||
#endif
|
@ -1,40 +0,0 @@
|
||||
/*
|
||||
Printable.h - Interface class that allows printing of complex types
|
||||
Copyright (c) 2011 Adrian McEwen. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#ifndef Printable_h
|
||||
#define Printable_h
|
||||
|
||||
#include <new.h>
|
||||
|
||||
class Print;
|
||||
|
||||
/** The Printable class provides a way for new classes to allow themselves to be printed.
|
||||
By deriving from Printable and implementing the printTo method, it will then be possible
|
||||
for users to print out instances of this class by passing them into the usual
|
||||
Print::print and Print::println methods.
|
||||
*/
|
||||
|
||||
class Printable
|
||||
{
|
||||
public:
|
||||
virtual size_t printTo(Print& p) const = 0;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
@ -1,9 +0,0 @@
|
||||
#ifndef server_h
|
||||
#define server_h
|
||||
|
||||
class Server : public Print {
|
||||
public:
|
||||
virtual void begin() =0;
|
||||
};
|
||||
|
||||
#endif
|
@ -1,270 +0,0 @@
|
||||
/*
|
||||
Stream.cpp - adds parsing methods to Stream class
|
||||
Copyright (c) 2008 David A. Mellis. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
Created July 2011
|
||||
parsing functions based on TextFinder library by Michael Margolis
|
||||
*/
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Stream.h"
|
||||
|
||||
#define PARSE_TIMEOUT 1000 // default number of milli-seconds to wait
|
||||
#define NO_SKIP_CHAR 1 // a magic char not found in a valid ASCII numeric field
|
||||
|
||||
// private method to read stream with timeout
|
||||
int Stream::timedRead()
|
||||
{
|
||||
int c;
|
||||
_startMillis = millis();
|
||||
do {
|
||||
c = read();
|
||||
if (c >= 0) return c;
|
||||
} while(millis() - _startMillis < _timeout);
|
||||
return -1; // -1 indicates timeout
|
||||
}
|
||||
|
||||
// private method to peek stream with timeout
|
||||
int Stream::timedPeek()
|
||||
{
|
||||
int c;
|
||||
_startMillis = millis();
|
||||
do {
|
||||
c = peek();
|
||||
if (c >= 0) return c;
|
||||
} while(millis() - _startMillis < _timeout);
|
||||
return -1; // -1 indicates timeout
|
||||
}
|
||||
|
||||
// returns peek of the next digit in the stream or -1 if timeout
|
||||
// discards non-numeric characters
|
||||
int Stream::peekNextDigit()
|
||||
{
|
||||
int c;
|
||||
while (1) {
|
||||
c = timedPeek();
|
||||
if (c < 0) return c; // timeout
|
||||
if (c == '-') return c;
|
||||
if (c >= '0' && c <= '9') return c;
|
||||
read(); // discard non-numeric
|
||||
}
|
||||
}
|
||||
|
||||
// Public Methods
|
||||
//////////////////////////////////////////////////////////////
|
||||
|
||||
void Stream::setTimeout(unsigned long timeout) // sets the maximum number of milliseconds to wait
|
||||
{
|
||||
_timeout = timeout;
|
||||
}
|
||||
|
||||
// find returns true if the target string is found
|
||||
bool Stream::find(char *target)
|
||||
{
|
||||
return findUntil(target, NULL);
|
||||
}
|
||||
|
||||
// reads data from the stream until the target string of given length is found
|
||||
// returns true if target string is found, false if timed out
|
||||
bool Stream::find(char *target, size_t length)
|
||||
{
|
||||
return findUntil(target, length, NULL, 0);
|
||||
}
|
||||
|
||||
// as find but search ends if the terminator string is found
|
||||
bool Stream::findUntil(char *target, char *terminator)
|
||||
{
|
||||
return findUntil(target, strlen(target), terminator, strlen(terminator));
|
||||
}
|
||||
|
||||
// reads data from the stream until the target string of the given length is found
|
||||
// search terminated if the terminator string is found
|
||||
// returns true if target string is found, false if terminated or timed out
|
||||
bool Stream::findUntil(char *target, size_t targetLen, char *terminator, size_t termLen)
|
||||
{
|
||||
size_t index = 0; // maximum target string length is 64k bytes!
|
||||
size_t termIndex = 0;
|
||||
int c;
|
||||
|
||||
if( *target == 0)
|
||||
return true; // return true if target is a null string
|
||||
while( (c = timedRead()) > 0){
|
||||
|
||||
if(c != target[index])
|
||||
index = 0; // reset index if any char does not match
|
||||
|
||||
if( c == target[index]){
|
||||
//////Serial.print("found "); Serial.write(c); Serial.print("index now"); Serial.println(index+1);
|
||||
if(++index >= targetLen){ // return true if all chars in the target match
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if(termLen > 0 && c == terminator[termIndex]){
|
||||
if(++termIndex >= termLen)
|
||||
return false; // return false if terminate string found before target string
|
||||
}
|
||||
else
|
||||
termIndex = 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// returns the first valid (long) integer value from the current position.
|
||||
// initial characters that are not digits (or the minus sign) are skipped
|
||||
// function is terminated by the first character that is not a digit.
|
||||
long Stream::parseInt()
|
||||
{
|
||||
return parseInt(NO_SKIP_CHAR); // terminate on first non-digit character (or timeout)
|
||||
}
|
||||
|
||||
// as above but a given skipChar is ignored
|
||||
// this allows format characters (typically commas) in values to be ignored
|
||||
long Stream::parseInt(char skipChar)
|
||||
{
|
||||
boolean isNegative = false;
|
||||
long value = 0;
|
||||
int c;
|
||||
|
||||
c = peekNextDigit();
|
||||
// ignore non numeric leading characters
|
||||
if(c < 0)
|
||||
return 0; // zero returned if timeout
|
||||
|
||||
do{
|
||||
if(c == skipChar)
|
||||
; // ignore this charactor
|
||||
else if(c == '-')
|
||||
isNegative = true;
|
||||
else if(c >= '0' && c <= '9') // is c a digit?
|
||||
value = value * 10 + c - '0';
|
||||
read(); // consume the character we got with peek
|
||||
c = timedPeek();
|
||||
}
|
||||
while( (c >= '0' && c <= '9') || c == skipChar );
|
||||
|
||||
if(isNegative)
|
||||
value = -value;
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
// as parseInt but returns a floating point value
|
||||
float Stream::parseFloat()
|
||||
{
|
||||
return parseFloat(NO_SKIP_CHAR);
|
||||
}
|
||||
|
||||
// as above but the given skipChar is ignored
|
||||
// this allows format characters (typically commas) in values to be ignored
|
||||
float Stream::parseFloat(char skipChar){
|
||||
boolean isNegative = false;
|
||||
boolean isFraction = false;
|
||||
long value = 0;
|
||||
char c;
|
||||
float fraction = 1.0;
|
||||
|
||||
c = peekNextDigit();
|
||||
// ignore non numeric leading characters
|
||||
if(c < 0)
|
||||
return 0; // zero returned if timeout
|
||||
|
||||
do{
|
||||
if(c == skipChar)
|
||||
; // ignore
|
||||
else if(c == '-')
|
||||
isNegative = true;
|
||||
else if (c == '.')
|
||||
isFraction = true;
|
||||
else if(c >= '0' && c <= '9') { // is c a digit?
|
||||
value = value * 10 + c - '0';
|
||||
if(isFraction)
|
||||
fraction *= 0.1;
|
||||
}
|
||||
read(); // consume the character we got with peek
|
||||
c = timedPeek();
|
||||
}
|
||||
while( (c >= '0' && c <= '9') || c == '.' || c == skipChar );
|
||||
|
||||
if(isNegative)
|
||||
value = -value;
|
||||
if(isFraction)
|
||||
return value * fraction;
|
||||
else
|
||||
return value;
|
||||
}
|
||||
|
||||
// read characters from stream into buffer
|
||||
// terminates if length characters have been read, or timeout (see setTimeout)
|
||||
// returns the number of characters placed in the buffer
|
||||
// the buffer is NOT null terminated.
|
||||
//
|
||||
size_t Stream::readBytes(char *buffer, size_t length)
|
||||
{
|
||||
size_t count = 0;
|
||||
while (count < length) {
|
||||
int c = timedRead();
|
||||
if (c < 0) break;
|
||||
*buffer++ = (char)c;
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
|
||||
// as readBytes with terminator character
|
||||
// terminates if length characters have been read, timeout, or if the terminator character detected
|
||||
// returns the number of characters placed in the buffer (0 means no valid data found)
|
||||
|
||||
size_t Stream::readBytesUntil(char terminator, char *buffer, size_t length)
|
||||
{
|
||||
if (length < 1) return 0;
|
||||
size_t index = 0;
|
||||
while (index < length) {
|
||||
int c = timedRead();
|
||||
if (c < 0 || c == terminator) break;
|
||||
*buffer++ = (char)c;
|
||||
index++;
|
||||
}
|
||||
return index; // return number of characters, not including null terminator
|
||||
}
|
||||
|
||||
String Stream::readString()
|
||||
{
|
||||
String ret;
|
||||
int c = timedRead();
|
||||
while (c >= 0)
|
||||
{
|
||||
ret += (char)c;
|
||||
c = timedRead();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
String Stream::readStringUntil(char terminator)
|
||||
{
|
||||
String ret;
|
||||
int c = timedRead();
|
||||
while (c >= 0 && c != terminator)
|
||||
{
|
||||
ret += (char)c;
|
||||
c = timedRead();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
@ -1,96 +0,0 @@
|
||||
/*
|
||||
Stream.h - base class for character-based streams.
|
||||
Copyright (c) 2010 David A. Mellis. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
parsing functions based on TextFinder library by Michael Margolis
|
||||
*/
|
||||
|
||||
#ifndef Stream_h
|
||||
#define Stream_h
|
||||
|
||||
#include <inttypes.h>
|
||||
#include "Print.h"
|
||||
|
||||
// compatability macros for testing
|
||||
/*
|
||||
#define getInt() parseInt()
|
||||
#define getInt(skipChar) parseInt(skipchar)
|
||||
#define getFloat() parseFloat()
|
||||
#define getFloat(skipChar) parseFloat(skipChar)
|
||||
#define getString( pre_string, post_string, buffer, length)
|
||||
readBytesBetween( pre_string, terminator, buffer, length)
|
||||
*/
|
||||
|
||||
class Stream : public Print
|
||||
{
|
||||
protected:
|
||||
unsigned long _timeout; // number of milliseconds to wait for the next char before aborting timed read
|
||||
unsigned long _startMillis; // used for timeout measurement
|
||||
int timedRead(); // private method to read stream with timeout
|
||||
int timedPeek(); // private method to peek stream with timeout
|
||||
int peekNextDigit(); // returns the next numeric digit in the stream or -1 if timeout
|
||||
|
||||
public:
|
||||
virtual int available() = 0;
|
||||
virtual int read() = 0;
|
||||
virtual int peek() = 0;
|
||||
virtual void flush() = 0;
|
||||
|
||||
Stream() {_timeout=1000;}
|
||||
|
||||
// parsing methods
|
||||
|
||||
void setTimeout(unsigned long timeout); // sets maximum milliseconds to wait for stream data, default is 1 second
|
||||
|
||||
bool find(char *target); // reads data from the stream until the target string is found
|
||||
// returns true if target string is found, false if timed out (see setTimeout)
|
||||
|
||||
bool find(char *target, size_t length); // reads data from the stream until the target string of given length is found
|
||||
// returns true if target string is found, false if timed out
|
||||
|
||||
bool findUntil(char *target, char *terminator); // as find but search ends if the terminator string is found
|
||||
|
||||
bool findUntil(char *target, size_t targetLen, char *terminate, size_t termLen); // as above but search ends if the terminate string is found
|
||||
|
||||
|
||||
long parseInt(); // returns the first valid (long) integer value from the current position.
|
||||
// initial characters that are not digits (or the minus sign) are skipped
|
||||
// integer is terminated by the first character that is not a digit.
|
||||
|
||||
float parseFloat(); // float version of parseInt
|
||||
|
||||
size_t readBytes( char *buffer, size_t length); // read chars from stream into buffer
|
||||
// terminates if length characters have been read or timeout (see setTimeout)
|
||||
// returns the number of characters placed in the buffer (0 means no valid data found)
|
||||
|
||||
size_t readBytesUntil( char terminator, char *buffer, size_t length); // as readBytes with terminator character
|
||||
// terminates if length characters have been read, timeout, or if the terminator character detected
|
||||
// returns the number of characters placed in the buffer (0 means no valid data found)
|
||||
|
||||
// Arduino String functions to be added here
|
||||
String readString();
|
||||
String readStringUntil(char terminator);
|
||||
|
||||
protected:
|
||||
long parseInt(char skipChar); // as above but the given skipChar is ignored
|
||||
// as above but the given skipChar is ignored
|
||||
// this allows format characters (typically commas) in values to be ignored
|
||||
|
||||
float parseFloat(char skipChar); // as above but the given skipChar is ignored
|
||||
};
|
||||
|
||||
#endif
|
@ -1,616 +0,0 @@
|
||||
/* Tone.cpp
|
||||
|
||||
A Tone Generator Library
|
||||
|
||||
Written by Brett Hagman
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
Version Modified By Date Comments
|
||||
------- ----------- -------- --------
|
||||
0001 B Hagman 09/08/02 Initial coding
|
||||
0002 B Hagman 09/08/18 Multiple pins
|
||||
0003 B Hagman 09/08/18 Moved initialization from constructor to begin()
|
||||
0004 B Hagman 09/09/26 Fixed problems with ATmega8
|
||||
0005 B Hagman 09/11/23 Scanned prescalars for best fit on 8 bit timers
|
||||
09/11/25 Changed pin toggle method to XOR
|
||||
09/11/25 Fixed timer0 from being excluded
|
||||
0006 D Mellis 09/12/29 Replaced objects with functions
|
||||
0007 M Sproul 10/08/29 Changed #ifdefs from cpu to register
|
||||
0008 S Kanemoto 12/06/22 Fixed for Leonardo by @maris_HY
|
||||
*************************************************/
|
||||
|
||||
#include <avr/interrupt.h>
|
||||
#include <avr/pgmspace.h>
|
||||
#include "Arduino.h"
|
||||
#include "pins_arduino.h"
|
||||
|
||||
#if defined(__AVR_ATmega8__) || defined(__AVR_ATmega128__)
|
||||
#define TCCR2A TCCR2
|
||||
#define TCCR2B TCCR2
|
||||
#define COM2A1 COM21
|
||||
#define COM2A0 COM20
|
||||
#define OCR2A OCR2
|
||||
#define TIMSK2 TIMSK
|
||||
#define OCIE2A OCIE2
|
||||
#define TIMER2_COMPA_vect TIMER2_COMP_vect
|
||||
#define TIMSK1 TIMSK
|
||||
#endif
|
||||
|
||||
// timerx_toggle_count:
|
||||
// > 0 - duration specified
|
||||
// = 0 - stopped
|
||||
// < 0 - infinitely (until stop() method called, or new play() called)
|
||||
|
||||
#if !defined(__AVR_ATmega8__)
|
||||
volatile long timer0_toggle_count;
|
||||
volatile uint8_t *timer0_pin_port;
|
||||
volatile uint8_t timer0_pin_mask;
|
||||
#endif
|
||||
|
||||
volatile long timer1_toggle_count;
|
||||
volatile uint8_t *timer1_pin_port;
|
||||
volatile uint8_t timer1_pin_mask;
|
||||
volatile long timer2_toggle_count;
|
||||
volatile uint8_t *timer2_pin_port;
|
||||
volatile uint8_t timer2_pin_mask;
|
||||
|
||||
#if defined(TIMSK3)
|
||||
volatile long timer3_toggle_count;
|
||||
volatile uint8_t *timer3_pin_port;
|
||||
volatile uint8_t timer3_pin_mask;
|
||||
#endif
|
||||
|
||||
#if defined(TIMSK4)
|
||||
volatile long timer4_toggle_count;
|
||||
volatile uint8_t *timer4_pin_port;
|
||||
volatile uint8_t timer4_pin_mask;
|
||||
#endif
|
||||
|
||||
#if defined(TIMSK5)
|
||||
volatile long timer5_toggle_count;
|
||||
volatile uint8_t *timer5_pin_port;
|
||||
volatile uint8_t timer5_pin_mask;
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
|
||||
|
||||
#define AVAILABLE_TONE_PINS 1
|
||||
#define USE_TIMER2
|
||||
|
||||
const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 3, 4, 5, 1, 0 */ };
|
||||
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255, 255, 255, 255 */ };
|
||||
|
||||
#elif defined(__AVR_ATmega8__)
|
||||
|
||||
#define AVAILABLE_TONE_PINS 1
|
||||
#define USE_TIMER2
|
||||
|
||||
const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1 */ };
|
||||
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ };
|
||||
|
||||
#elif defined(__AVR_ATmega32U4__)
|
||||
|
||||
#define AVAILABLE_TONE_PINS 1
|
||||
#define USE_TIMER3
|
||||
|
||||
const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 3 /*, 1 */ };
|
||||
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ };
|
||||
|
||||
#else
|
||||
|
||||
#define AVAILABLE_TONE_PINS 1
|
||||
#define USE_TIMER2
|
||||
|
||||
// Leave timer 0 to last.
|
||||
const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1, 0 */ };
|
||||
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255 */ };
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
static int8_t toneBegin(uint8_t _pin)
|
||||
{
|
||||
int8_t _timer = -1;
|
||||
|
||||
// if we're already using the pin, the timer should be configured.
|
||||
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
|
||||
if (tone_pins[i] == _pin) {
|
||||
return pgm_read_byte(tone_pin_to_timer_PGM + i);
|
||||
}
|
||||
}
|
||||
|
||||
// search for an unused timer.
|
||||
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
|
||||
if (tone_pins[i] == 255) {
|
||||
tone_pins[i] = _pin;
|
||||
_timer = pgm_read_byte(tone_pin_to_timer_PGM + i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (_timer != -1)
|
||||
{
|
||||
// Set timer specific stuff
|
||||
// All timers in CTC mode
|
||||
// 8 bit timers will require changing prescalar values,
|
||||
// whereas 16 bit timers are set to either ck/1 or ck/64 prescalar
|
||||
switch (_timer)
|
||||
{
|
||||
#if defined(TCCR0A) && defined(TCCR0B)
|
||||
case 0:
|
||||
// 8 bit timer
|
||||
TCCR0A = 0;
|
||||
TCCR0B = 0;
|
||||
bitWrite(TCCR0A, WGM01, 1);
|
||||
bitWrite(TCCR0B, CS00, 1);
|
||||
timer0_pin_port = portOutputRegister(digitalPinToPort(_pin));
|
||||
timer0_pin_mask = digitalPinToBitMask(_pin);
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR1A) && defined(TCCR1B) && defined(WGM12)
|
||||
case 1:
|
||||
// 16 bit timer
|
||||
TCCR1A = 0;
|
||||
TCCR1B = 0;
|
||||
bitWrite(TCCR1B, WGM12, 1);
|
||||
bitWrite(TCCR1B, CS10, 1);
|
||||
timer1_pin_port = portOutputRegister(digitalPinToPort(_pin));
|
||||
timer1_pin_mask = digitalPinToBitMask(_pin);
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR2A) && defined(TCCR2B)
|
||||
case 2:
|
||||
// 8 bit timer
|
||||
TCCR2A = 0;
|
||||
TCCR2B = 0;
|
||||
bitWrite(TCCR2A, WGM21, 1);
|
||||
bitWrite(TCCR2B, CS20, 1);
|
||||
timer2_pin_port = portOutputRegister(digitalPinToPort(_pin));
|
||||
timer2_pin_mask = digitalPinToBitMask(_pin);
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR3A) && defined(TCCR3B) && defined(TIMSK3)
|
||||
case 3:
|
||||
// 16 bit timer
|
||||
TCCR3A = 0;
|
||||
TCCR3B = 0;
|
||||
bitWrite(TCCR3B, WGM32, 1);
|
||||
bitWrite(TCCR3B, CS30, 1);
|
||||
timer3_pin_port = portOutputRegister(digitalPinToPort(_pin));
|
||||
timer3_pin_mask = digitalPinToBitMask(_pin);
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR4A) && defined(TCCR4B) && defined(TIMSK4)
|
||||
case 4:
|
||||
// 16 bit timer
|
||||
TCCR4A = 0;
|
||||
TCCR4B = 0;
|
||||
#if defined(WGM42)
|
||||
bitWrite(TCCR4B, WGM42, 1);
|
||||
#elif defined(CS43)
|
||||
#warning this may not be correct
|
||||
// atmega32u4
|
||||
bitWrite(TCCR4B, CS43, 1);
|
||||
#endif
|
||||
bitWrite(TCCR4B, CS40, 1);
|
||||
timer4_pin_port = portOutputRegister(digitalPinToPort(_pin));
|
||||
timer4_pin_mask = digitalPinToBitMask(_pin);
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR5A) && defined(TCCR5B) && defined(TIMSK5)
|
||||
case 5:
|
||||
// 16 bit timer
|
||||
TCCR5A = 0;
|
||||
TCCR5B = 0;
|
||||
bitWrite(TCCR5B, WGM52, 1);
|
||||
bitWrite(TCCR5B, CS50, 1);
|
||||
timer5_pin_port = portOutputRegister(digitalPinToPort(_pin));
|
||||
timer5_pin_mask = digitalPinToBitMask(_pin);
|
||||
break;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
return _timer;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// frequency (in hertz) and duration (in milliseconds).
|
||||
|
||||
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration)
|
||||
{
|
||||
uint8_t prescalarbits = 0b001;
|
||||
long toggle_count = 0;
|
||||
uint32_t ocr = 0;
|
||||
int8_t _timer;
|
||||
|
||||
_timer = toneBegin(_pin);
|
||||
|
||||
if (_timer >= 0)
|
||||
{
|
||||
// Set the pinMode as OUTPUT
|
||||
pinMode(_pin, OUTPUT);
|
||||
|
||||
// if we are using an 8 bit timer, scan through prescalars to find the best fit
|
||||
if (_timer == 0 || _timer == 2)
|
||||
{
|
||||
ocr = F_CPU / frequency / 2 - 1;
|
||||
prescalarbits = 0b001; // ck/1: same for both timers
|
||||
if (ocr > 255)
|
||||
{
|
||||
ocr = F_CPU / frequency / 2 / 8 - 1;
|
||||
prescalarbits = 0b010; // ck/8: same for both timers
|
||||
|
||||
if (_timer == 2 && ocr > 255)
|
||||
{
|
||||
ocr = F_CPU / frequency / 2 / 32 - 1;
|
||||
prescalarbits = 0b011;
|
||||
}
|
||||
|
||||
if (ocr > 255)
|
||||
{
|
||||
ocr = F_CPU / frequency / 2 / 64 - 1;
|
||||
prescalarbits = _timer == 0 ? 0b011 : 0b100;
|
||||
|
||||
if (_timer == 2 && ocr > 255)
|
||||
{
|
||||
ocr = F_CPU / frequency / 2 / 128 - 1;
|
||||
prescalarbits = 0b101;
|
||||
}
|
||||
|
||||
if (ocr > 255)
|
||||
{
|
||||
ocr = F_CPU / frequency / 2 / 256 - 1;
|
||||
prescalarbits = _timer == 0 ? 0b100 : 0b110;
|
||||
if (ocr > 255)
|
||||
{
|
||||
// can't do any better than /1024
|
||||
ocr = F_CPU / frequency / 2 / 1024 - 1;
|
||||
prescalarbits = _timer == 0 ? 0b101 : 0b111;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(TCCR0B)
|
||||
if (_timer == 0)
|
||||
{
|
||||
TCCR0B = prescalarbits;
|
||||
}
|
||||
else
|
||||
#endif
|
||||
#if defined(TCCR2B)
|
||||
{
|
||||
TCCR2B = prescalarbits;
|
||||
}
|
||||
#else
|
||||
{
|
||||
// dummy place holder to make the above ifdefs work
|
||||
}
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
// two choices for the 16 bit timers: ck/1 or ck/64
|
||||
ocr = F_CPU / frequency / 2 - 1;
|
||||
|
||||
prescalarbits = 0b001;
|
||||
if (ocr > 0xffff)
|
||||
{
|
||||
ocr = F_CPU / frequency / 2 / 64 - 1;
|
||||
prescalarbits = 0b011;
|
||||
}
|
||||
|
||||
if (_timer == 1)
|
||||
{
|
||||
#if defined(TCCR1B)
|
||||
TCCR1B = (TCCR1B & 0b11111000) | prescalarbits;
|
||||
#endif
|
||||
}
|
||||
#if defined(TCCR3B)
|
||||
else if (_timer == 3)
|
||||
TCCR3B = (TCCR3B & 0b11111000) | prescalarbits;
|
||||
#endif
|
||||
#if defined(TCCR4B)
|
||||
else if (_timer == 4)
|
||||
TCCR4B = (TCCR4B & 0b11111000) | prescalarbits;
|
||||
#endif
|
||||
#if defined(TCCR5B)
|
||||
else if (_timer == 5)
|
||||
TCCR5B = (TCCR5B & 0b11111000) | prescalarbits;
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
|
||||
// Calculate the toggle count
|
||||
if (duration > 0)
|
||||
{
|
||||
toggle_count = 2 * frequency * duration / 1000;
|
||||
}
|
||||
else
|
||||
{
|
||||
toggle_count = -1;
|
||||
}
|
||||
|
||||
// Set the OCR for the given timer,
|
||||
// set the toggle count,
|
||||
// then turn on the interrupts
|
||||
switch (_timer)
|
||||
{
|
||||
|
||||
#if defined(OCR0A) && defined(TIMSK0) && defined(OCIE0A)
|
||||
case 0:
|
||||
OCR0A = ocr;
|
||||
timer0_toggle_count = toggle_count;
|
||||
bitWrite(TIMSK0, OCIE0A, 1);
|
||||
break;
|
||||
#endif
|
||||
|
||||
case 1:
|
||||
#if defined(OCR1A) && defined(TIMSK1) && defined(OCIE1A)
|
||||
OCR1A = ocr;
|
||||
timer1_toggle_count = toggle_count;
|
||||
bitWrite(TIMSK1, OCIE1A, 1);
|
||||
#elif defined(OCR1A) && defined(TIMSK) && defined(OCIE1A)
|
||||
// this combination is for at least the ATmega32
|
||||
OCR1A = ocr;
|
||||
timer1_toggle_count = toggle_count;
|
||||
bitWrite(TIMSK, OCIE1A, 1);
|
||||
#endif
|
||||
break;
|
||||
|
||||
#if defined(OCR2A) && defined(TIMSK2) && defined(OCIE2A)
|
||||
case 2:
|
||||
OCR2A = ocr;
|
||||
timer2_toggle_count = toggle_count;
|
||||
bitWrite(TIMSK2, OCIE2A, 1);
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TIMSK3)
|
||||
case 3:
|
||||
OCR3A = ocr;
|
||||
timer3_toggle_count = toggle_count;
|
||||
bitWrite(TIMSK3, OCIE3A, 1);
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TIMSK4)
|
||||
case 4:
|
||||
OCR4A = ocr;
|
||||
timer4_toggle_count = toggle_count;
|
||||
bitWrite(TIMSK4, OCIE4A, 1);
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(OCR5A) && defined(TIMSK5) && defined(OCIE5A)
|
||||
case 5:
|
||||
OCR5A = ocr;
|
||||
timer5_toggle_count = toggle_count;
|
||||
bitWrite(TIMSK5, OCIE5A, 1);
|
||||
break;
|
||||
#endif
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// XXX: this function only works properly for timer 2 (the only one we use
|
||||
// currently). for the others, it should end the tone, but won't restore
|
||||
// proper PWM functionality for the timer.
|
||||
void disableTimer(uint8_t _timer)
|
||||
{
|
||||
switch (_timer)
|
||||
{
|
||||
case 0:
|
||||
#if defined(TIMSK0)
|
||||
TIMSK0 = 0;
|
||||
#elif defined(TIMSK)
|
||||
TIMSK = 0; // atmega32
|
||||
#endif
|
||||
break;
|
||||
|
||||
#if defined(TIMSK1) && defined(OCIE1A)
|
||||
case 1:
|
||||
bitWrite(TIMSK1, OCIE1A, 0);
|
||||
break;
|
||||
#endif
|
||||
|
||||
case 2:
|
||||
#if defined(TIMSK2) && defined(OCIE2A)
|
||||
bitWrite(TIMSK2, OCIE2A, 0); // disable interrupt
|
||||
#endif
|
||||
#if defined(TCCR2A) && defined(WGM20)
|
||||
TCCR2A = (1 << WGM20);
|
||||
#endif
|
||||
#if defined(TCCR2B) && defined(CS22)
|
||||
TCCR2B = (TCCR2B & 0b11111000) | (1 << CS22);
|
||||
#endif
|
||||
#if defined(OCR2A)
|
||||
OCR2A = 0;
|
||||
#endif
|
||||
break;
|
||||
|
||||
#if defined(TIMSK3)
|
||||
case 3:
|
||||
TIMSK3 = 0;
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TIMSK4)
|
||||
case 4:
|
||||
TIMSK4 = 0;
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TIMSK5)
|
||||
case 5:
|
||||
TIMSK5 = 0;
|
||||
break;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void noTone(uint8_t _pin)
|
||||
{
|
||||
int8_t _timer = -1;
|
||||
|
||||
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
|
||||
if (tone_pins[i] == _pin) {
|
||||
_timer = pgm_read_byte(tone_pin_to_timer_PGM + i);
|
||||
tone_pins[i] = 255;
|
||||
}
|
||||
}
|
||||
|
||||
disableTimer(_timer);
|
||||
|
||||
digitalWrite(_pin, 0);
|
||||
}
|
||||
|
||||
#ifdef USE_TIMER0
|
||||
ISR(TIMER0_COMPA_vect)
|
||||
{
|
||||
if (timer0_toggle_count != 0)
|
||||
{
|
||||
// toggle the pin
|
||||
*timer0_pin_port ^= timer0_pin_mask;
|
||||
|
||||
if (timer0_toggle_count > 0)
|
||||
timer0_toggle_count--;
|
||||
}
|
||||
else
|
||||
{
|
||||
disableTimer(0);
|
||||
*timer0_pin_port &= ~(timer0_pin_mask); // keep pin low after stop
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef USE_TIMER1
|
||||
ISR(TIMER1_COMPA_vect)
|
||||
{
|
||||
if (timer1_toggle_count != 0)
|
||||
{
|
||||
// toggle the pin
|
||||
*timer1_pin_port ^= timer1_pin_mask;
|
||||
|
||||
if (timer1_toggle_count > 0)
|
||||
timer1_toggle_count--;
|
||||
}
|
||||
else
|
||||
{
|
||||
disableTimer(1);
|
||||
*timer1_pin_port &= ~(timer1_pin_mask); // keep pin low after stop
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef USE_TIMER2
|
||||
ISR(TIMER2_COMPA_vect)
|
||||
{
|
||||
|
||||
if (timer2_toggle_count != 0)
|
||||
{
|
||||
// toggle the pin
|
||||
*timer2_pin_port ^= timer2_pin_mask;
|
||||
|
||||
if (timer2_toggle_count > 0)
|
||||
timer2_toggle_count--;
|
||||
}
|
||||
else
|
||||
{
|
||||
// need to call noTone() so that the tone_pins[] entry is reset, so the
|
||||
// timer gets initialized next time we call tone().
|
||||
// XXX: this assumes timer 2 is always the first one used.
|
||||
noTone(tone_pins[0]);
|
||||
// disableTimer(2);
|
||||
// *timer2_pin_port &= ~(timer2_pin_mask); // keep pin low after stop
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef USE_TIMER3
|
||||
ISR(TIMER3_COMPA_vect)
|
||||
{
|
||||
if (timer3_toggle_count != 0)
|
||||
{
|
||||
// toggle the pin
|
||||
*timer3_pin_port ^= timer3_pin_mask;
|
||||
|
||||
if (timer3_toggle_count > 0)
|
||||
timer3_toggle_count--;
|
||||
}
|
||||
else
|
||||
{
|
||||
disableTimer(3);
|
||||
*timer3_pin_port &= ~(timer3_pin_mask); // keep pin low after stop
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef USE_TIMER4
|
||||
ISR(TIMER4_COMPA_vect)
|
||||
{
|
||||
if (timer4_toggle_count != 0)
|
||||
{
|
||||
// toggle the pin
|
||||
*timer4_pin_port ^= timer4_pin_mask;
|
||||
|
||||
if (timer4_toggle_count > 0)
|
||||
timer4_toggle_count--;
|
||||
}
|
||||
else
|
||||
{
|
||||
disableTimer(4);
|
||||
*timer4_pin_port &= ~(timer4_pin_mask); // keep pin low after stop
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef USE_TIMER5
|
||||
ISR(TIMER5_COMPA_vect)
|
||||
{
|
||||
if (timer5_toggle_count != 0)
|
||||
{
|
||||
// toggle the pin
|
||||
*timer5_pin_port ^= timer5_pin_mask;
|
||||
|
||||
if (timer5_toggle_count > 0)
|
||||
timer5_toggle_count--;
|
||||
}
|
||||
else
|
||||
{
|
||||
disableTimer(5);
|
||||
*timer5_pin_port &= ~(timer5_pin_mask); // keep pin low after stop
|
||||
}
|
||||
}
|
||||
#endif
|
@ -1,206 +0,0 @@
|
||||
|
||||
|
||||
#ifndef __USBAPI__
|
||||
#define __USBAPI__
|
||||
|
||||
#if defined(USBCON)
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
// USB
|
||||
|
||||
class USBDevice_
|
||||
{
|
||||
public:
|
||||
USBDevice_();
|
||||
bool configured();
|
||||
|
||||
void attach();
|
||||
void detach(); // Serial port goes down too...
|
||||
void poll();
|
||||
};
|
||||
extern USBDevice_ USBDevice;
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
// Serial over CDC (Serial1 is the physical port)
|
||||
|
||||
struct ring_buffer;
|
||||
|
||||
#if (RAMEND < 1000)
|
||||
#define SERIAL_BUFFER_SIZE 16
|
||||
#else
|
||||
#define SERIAL_BUFFER_SIZE 64
|
||||
#endif
|
||||
|
||||
class Serial_ : public Stream
|
||||
{
|
||||
public:
|
||||
void begin(uint16_t baud_count);
|
||||
void end(void);
|
||||
|
||||
virtual int available(void);
|
||||
virtual void accept(void);
|
||||
virtual int peek(void);
|
||||
virtual int read(void);
|
||||
virtual void flush(void);
|
||||
virtual size_t write(uint8_t);
|
||||
using Print::write; // pull in write(str) and write(buf, size) from Print
|
||||
operator bool();
|
||||
|
||||
volatile uint8_t _rx_buffer_head;
|
||||
volatile uint8_t _rx_buffer_tail;
|
||||
unsigned char _rx_buffer[SERIAL_BUFFER_SIZE];
|
||||
};
|
||||
extern Serial_ Serial;
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
// Mouse
|
||||
|
||||
#define MOUSE_LEFT 1
|
||||
#define MOUSE_RIGHT 2
|
||||
#define MOUSE_MIDDLE 4
|
||||
#define MOUSE_ALL (MOUSE_LEFT | MOUSE_RIGHT | MOUSE_MIDDLE)
|
||||
|
||||
class Mouse_
|
||||
{
|
||||
private:
|
||||
uint8_t _buttons;
|
||||
void buttons(uint8_t b);
|
||||
public:
|
||||
Mouse_(void);
|
||||
void begin(void);
|
||||
void end(void);
|
||||
void click(uint8_t b = MOUSE_LEFT);
|
||||
void move(signed char x, signed char y, signed char wheel = 0);
|
||||
void press(uint8_t b = MOUSE_LEFT); // press LEFT by default
|
||||
void release(uint8_t b = MOUSE_LEFT); // release LEFT by default
|
||||
bool isPressed(uint8_t b = MOUSE_LEFT); // check LEFT by default
|
||||
};
|
||||
extern Mouse_ Mouse;
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
// Keyboard
|
||||
|
||||
#define KEY_LEFT_CTRL 0x80
|
||||
#define KEY_LEFT_SHIFT 0x81
|
||||
#define KEY_LEFT_ALT 0x82
|
||||
#define KEY_LEFT_GUI 0x83
|
||||
#define KEY_RIGHT_CTRL 0x84
|
||||
#define KEY_RIGHT_SHIFT 0x85
|
||||
#define KEY_RIGHT_ALT 0x86
|
||||
#define KEY_RIGHT_GUI 0x87
|
||||
|
||||
#define KEY_UP_ARROW 0xDA
|
||||
#define KEY_DOWN_ARROW 0xD9
|
||||
#define KEY_LEFT_ARROW 0xD8
|
||||
#define KEY_RIGHT_ARROW 0xD7
|
||||
#define KEY_BACKSPACE 0xB2
|
||||
#define KEY_TAB 0xB3
|
||||
#define KEY_RETURN 0xB0
|
||||
#define KEY_ESC 0xB1
|
||||
#define KEY_INSERT 0xD1
|
||||
#define KEY_DELETE 0xD4
|
||||
#define KEY_PAGE_UP 0xD3
|
||||
#define KEY_PAGE_DOWN 0xD6
|
||||
#define KEY_HOME 0xD2
|
||||
#define KEY_END 0xD5
|
||||
#define KEY_CAPS_LOCK 0xC1
|
||||
#define KEY_F1 0xC2
|
||||
#define KEY_F2 0xC3
|
||||
#define KEY_F3 0xC4
|
||||
#define KEY_F4 0xC5
|
||||
#define KEY_F5 0xC6
|
||||
#define KEY_F6 0xC7
|
||||
#define KEY_F7 0xC8
|
||||
#define KEY_F8 0xC9
|
||||
#define KEY_F9 0xCA
|
||||
#define KEY_F10 0xCB
|
||||
#define KEY_F11 0xCC
|
||||
#define KEY_F12 0xCD
|
||||
|
||||
// Low level key report: up to 6 keys and shift, ctrl etc at once
|
||||
typedef struct
|
||||
{
|
||||
uint8_t modifiers;
|
||||
uint8_t reserved;
|
||||
uint8_t keys[6];
|
||||
} KeyReport;
|
||||
|
||||
class Keyboard_ : public Print
|
||||
{
|
||||
private:
|
||||
KeyReport _keyReport;
|
||||
void sendReport(KeyReport* keys);
|
||||
public:
|
||||
Keyboard_(void);
|
||||
void begin(void);
|
||||
void end(void);
|
||||
virtual size_t write(uint8_t k);
|
||||
virtual size_t press(uint8_t k);
|
||||
virtual size_t release(uint8_t k);
|
||||
virtual void releaseAll(void);
|
||||
};
|
||||
extern Keyboard_ Keyboard;
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
// Low level API
|
||||
|
||||
typedef struct
|
||||
{
|
||||
uint8_t bmRequestType;
|
||||
uint8_t bRequest;
|
||||
uint8_t wValueL;
|
||||
uint8_t wValueH;
|
||||
uint16_t wIndex;
|
||||
uint16_t wLength;
|
||||
} Setup;
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
// HID 'Driver'
|
||||
|
||||
int HID_GetInterface(uint8_t* interfaceNum);
|
||||
int HID_GetDescriptor(int i);
|
||||
bool HID_Setup(Setup& setup);
|
||||
void HID_SendReport(uint8_t id, const void* data, int len);
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
// MSC 'Driver'
|
||||
|
||||
int MSC_GetInterface(uint8_t* interfaceNum);
|
||||
int MSC_GetDescriptor(int i);
|
||||
bool MSC_Setup(Setup& setup);
|
||||
bool MSC_Data(uint8_t rx,uint8_t tx);
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
// CSC 'Driver'
|
||||
|
||||
int CDC_GetInterface(uint8_t* interfaceNum);
|
||||
int CDC_GetDescriptor(int i);
|
||||
bool CDC_Setup(Setup& setup);
|
||||
|
||||
//================================================================================
|
||||
//================================================================================
|
||||
|
||||
#define TRANSFER_PGM 0x80
|
||||
#define TRANSFER_RELEASE 0x40
|
||||
#define TRANSFER_ZERO 0x20
|
||||
|
||||
int USB_SendControl(uint8_t flags, const void* d, int len);
|
||||
int USB_RecvControl(void* d, int len);
|
||||
|
||||
uint8_t USB_Available(uint8_t ep);
|
||||
int USB_Send(uint8_t ep, const void* data, int len); // blocking
|
||||
int USB_Recv(uint8_t ep, void* data, int len); // non-blocking
|
||||
int USB_Recv(uint8_t ep); // non-blocking
|
||||
void USB_Flush(uint8_t ep);
|
||||
|
||||
#endif
|
||||
|
||||
#endif /* if defined(USBCON) */
|
@ -1,694 +0,0 @@
|
||||
|
||||
|
||||
/* Copyright (c) 2010, Peter Barrett
|
||||
**
|
||||
** Permission to use, copy, modify, and/or distribute this software for
|
||||
** any purpose with or without fee is hereby granted, provided that the
|
||||
** above copyright notice and this permission notice appear in all copies.
|
||||
**
|
||||
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
|
||||
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
|
||||
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
|
||||
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
|
||||
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
||||
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
|
||||
** SOFTWARE.
|
||||
*/
|
||||
|
||||
#include "Platform.h"
|
||||
#include "USBAPI.h"
|
||||
#include "USBDesc.h"
|
||||
|
||||
#if defined(USBCON)
|
||||
|
||||
#define EP_TYPE_CONTROL 0x00
|
||||
#define EP_TYPE_BULK_IN 0x81
|
||||
#define EP_TYPE_BULK_OUT 0x80
|
||||
#define EP_TYPE_INTERRUPT_IN 0xC1
|
||||
#define EP_TYPE_INTERRUPT_OUT 0xC0
|
||||
#define EP_TYPE_ISOCHRONOUS_IN 0x41
|
||||
#define EP_TYPE_ISOCHRONOUS_OUT 0x40
|
||||
|
||||
/** Pulse generation counters to keep track of the number of milliseconds remaining for each pulse type */
|
||||
#define TX_RX_LED_PULSE_MS 100
|
||||
volatile u8 TxLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */
|
||||
volatile u8 RxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */
|
||||
|
||||
//==================================================================
|
||||
//==================================================================
|
||||
|
||||
extern const u16 STRING_LANGUAGE[] PROGMEM;
|
||||
extern const u8 STRING_PRODUCT[] PROGMEM;
|
||||
extern const u8 STRING_MANUFACTURER[] PROGMEM;
|
||||
extern const DeviceDescriptor USB_DeviceDescriptor PROGMEM;
|
||||
extern const DeviceDescriptor USB_DeviceDescriptorA PROGMEM;
|
||||
|
||||
const u16 STRING_LANGUAGE[2] = {
|
||||
(3<<8) | (2+2),
|
||||
0x0409 // English
|
||||
};
|
||||
|
||||
#ifndef USB_PRODUCT
|
||||
// If no product is provided, use USB IO Board
|
||||
#define USB_PRODUCT "USB IO Board"
|
||||
#endif
|
||||
|
||||
const u8 STRING_PRODUCT[] PROGMEM = USB_PRODUCT;
|
||||
|
||||
#if USB_VID == 0x2341
|
||||
#define USB_MANUFACTURER "Arduino LLC"
|
||||
#elif USB_VID == 0x1b4f
|
||||
#define USB_MANUFACTURER "SparkFun"
|
||||
#elif !defined(USB_MANUFACTURER)
|
||||
// Fall through to unknown if no manufacturer name was provided in a macro
|
||||
#define USB_MANUFACTURER "Unknown"
|
||||
#endif
|
||||
|
||||
const u8 STRING_MANUFACTURER[] PROGMEM = USB_MANUFACTURER;
|
||||
|
||||
|
||||
#ifdef CDC_ENABLED
|
||||
#define DEVICE_CLASS 0x02
|
||||
#else
|
||||
#define DEVICE_CLASS 0x00
|
||||
#endif
|
||||
|
||||
// DEVICE DESCRIPTOR
|
||||
const DeviceDescriptor USB_DeviceDescriptor =
|
||||
D_DEVICE(0x00,0x00,0x00,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,0,1);
|
||||
|
||||
const DeviceDescriptor USB_DeviceDescriptorA =
|
||||
D_DEVICE(DEVICE_CLASS,0x00,0x00,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,0,1);
|
||||
|
||||
//==================================================================
|
||||
//==================================================================
|
||||
|
||||
volatile u8 _usbConfiguration = 0;
|
||||
|
||||
static inline void WaitIN(void)
|
||||
{
|
||||
while (!(UEINTX & (1<<TXINI)));
|
||||
}
|
||||
|
||||
static inline void ClearIN(void)
|
||||
{
|
||||
UEINTX = ~(1<<TXINI);
|
||||
}
|
||||
|
||||
static inline void WaitOUT(void)
|
||||
{
|
||||
while (!(UEINTX & (1<<RXOUTI)))
|
||||
;
|
||||
}
|
||||
|
||||
static inline u8 WaitForINOrOUT()
|
||||
{
|
||||
while (!(UEINTX & ((1<<TXINI)|(1<<RXOUTI))))
|
||||
;
|
||||
return (UEINTX & (1<<RXOUTI)) == 0;
|
||||
}
|
||||
|
||||
static inline void ClearOUT(void)
|
||||
{
|
||||
UEINTX = ~(1<<RXOUTI);
|
||||
}
|
||||
|
||||
void Recv(volatile u8* data, u8 count)
|
||||
{
|
||||
while (count--)
|
||||
*data++ = UEDATX;
|
||||
|
||||
RXLED1; // light the RX LED
|
||||
RxLEDPulse = TX_RX_LED_PULSE_MS;
|
||||
}
|
||||
|
||||
static inline u8 Recv8()
|
||||
{
|
||||
RXLED1; // light the RX LED
|
||||
RxLEDPulse = TX_RX_LED_PULSE_MS;
|
||||
|
||||
return UEDATX;
|
||||
}
|
||||
|
||||
static inline void Send8(u8 d)
|
||||
{
|
||||
UEDATX = d;
|
||||
}
|
||||
|
||||
static inline void SetEP(u8 ep)
|
||||
{
|
||||
UENUM = ep;
|
||||
}
|
||||
|
||||
static inline u8 FifoByteCount()
|
||||
{
|
||||
return UEBCLX;
|
||||
}
|
||||
|
||||
static inline u8 ReceivedSetupInt()
|
||||
{
|
||||
return UEINTX & (1<<RXSTPI);
|
||||
}
|
||||
|
||||
static inline void ClearSetupInt()
|
||||
{
|
||||
UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
|
||||
}
|
||||
|
||||
static inline void Stall()
|
||||
{
|
||||
UECONX = (1<<STALLRQ) | (1<<EPEN);
|
||||
}
|
||||
|
||||
static inline u8 ReadWriteAllowed()
|
||||
{
|
||||
return UEINTX & (1<<RWAL);
|
||||
}
|
||||
|
||||
static inline u8 Stalled()
|
||||
{
|
||||
return UEINTX & (1<<STALLEDI);
|
||||
}
|
||||
|
||||
static inline u8 FifoFree()
|
||||
{
|
||||
return UEINTX & (1<<FIFOCON);
|
||||
}
|
||||
|
||||
static inline void ReleaseRX()
|
||||
{
|
||||
UEINTX = 0x6B; // FIFOCON=0 NAKINI=1 RWAL=1 NAKOUTI=0 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=1
|
||||
}
|
||||
|
||||
static inline void ReleaseTX()
|
||||
{
|
||||
UEINTX = 0x3A; // FIFOCON=0 NAKINI=0 RWAL=1 NAKOUTI=1 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=0
|
||||
}
|
||||
|
||||
static inline u8 FrameNumber()
|
||||
{
|
||||
return UDFNUML;
|
||||
}
|
||||
|
||||
//==================================================================
|
||||
//==================================================================
|
||||
|
||||
u8 USBGetConfiguration(void)
|
||||
{
|
||||
return _usbConfiguration;
|
||||
}
|
||||
|
||||
#define USB_RECV_TIMEOUT
|
||||
class LockEP
|
||||
{
|
||||
u8 _sreg;
|
||||
public:
|
||||
LockEP(u8 ep) : _sreg(SREG)
|
||||
{
|
||||
cli();
|
||||
SetEP(ep & 7);
|
||||
}
|
||||
~LockEP()
|
||||
{
|
||||
SREG = _sreg;
|
||||
}
|
||||
};
|
||||
|
||||
// Number of bytes, assumes a rx endpoint
|
||||
u8 USB_Available(u8 ep)
|
||||
{
|
||||
LockEP lock(ep);
|
||||
return FifoByteCount();
|
||||
}
|
||||
|
||||
// Non Blocking receive
|
||||
// Return number of bytes read
|
||||
int USB_Recv(u8 ep, void* d, int len)
|
||||
{
|
||||
if (!_usbConfiguration || len < 0)
|
||||
return -1;
|
||||
|
||||
LockEP lock(ep);
|
||||
u8 n = FifoByteCount();
|
||||
len = min(n,len);
|
||||
n = len;
|
||||
u8* dst = (u8*)d;
|
||||
while (n--)
|
||||
*dst++ = Recv8();
|
||||
if (len && !FifoByteCount()) // release empty buffer
|
||||
ReleaseRX();
|
||||
|
||||
return len;
|
||||
}
|
||||
|
||||
// Recv 1 byte if ready
|
||||
int USB_Recv(u8 ep)
|
||||
{
|
||||
u8 c;
|
||||
if (USB_Recv(ep,&c,1) != 1)
|
||||
return -1;
|
||||
return c;
|
||||
}
|
||||
|
||||
// Space in send EP
|
||||
u8 USB_SendSpace(u8 ep)
|
||||
{
|
||||
LockEP lock(ep);
|
||||
if (!ReadWriteAllowed())
|
||||
return 0;
|
||||
return 64 - FifoByteCount();
|
||||
}
|
||||
|
||||
// Blocking Send of data to an endpoint
|
||||
int USB_Send(u8 ep, const void* d, int len)
|
||||
{
|
||||
if (!_usbConfiguration)
|
||||
return -1;
|
||||
|
||||
int r = len;
|
||||
const u8* data = (const u8*)d;
|
||||
u8 zero = ep & TRANSFER_ZERO;
|
||||
u8 timeout = 250; // 250ms timeout on send? TODO
|
||||
while (len)
|
||||
{
|
||||
u8 n = USB_SendSpace(ep);
|
||||
if (n == 0)
|
||||
{
|
||||
if (!(--timeout))
|
||||
return -1;
|
||||
delay(1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (n > len)
|
||||
n = len;
|
||||
len -= n;
|
||||
{
|
||||
LockEP lock(ep);
|
||||
if (ep & TRANSFER_ZERO)
|
||||
{
|
||||
while (n--)
|
||||
Send8(0);
|
||||
}
|
||||
else if (ep & TRANSFER_PGM)
|
||||
{
|
||||
while (n--)
|
||||
Send8(pgm_read_byte(data++));
|
||||
}
|
||||
else
|
||||
{
|
||||
while (n--)
|
||||
Send8(*data++);
|
||||
}
|
||||
if (!ReadWriteAllowed() || ((len == 0) && (ep & TRANSFER_RELEASE))) // Release full buffer
|
||||
ReleaseTX();
|
||||
}
|
||||
}
|
||||
TXLED1; // light the TX LED
|
||||
TxLEDPulse = TX_RX_LED_PULSE_MS;
|
||||
return r;
|
||||
}
|
||||
|
||||
extern const u8 _initEndpoints[] PROGMEM;
|
||||
const u8 _initEndpoints[] =
|
||||
{
|
||||
0,
|
||||
|
||||
#ifdef CDC_ENABLED
|
||||
EP_TYPE_INTERRUPT_IN, // CDC_ENDPOINT_ACM
|
||||
EP_TYPE_BULK_OUT, // CDC_ENDPOINT_OUT
|
||||
EP_TYPE_BULK_IN, // CDC_ENDPOINT_IN
|
||||
#endif
|
||||
|
||||
#ifdef HID_ENABLED
|
||||
EP_TYPE_INTERRUPT_IN // HID_ENDPOINT_INT
|
||||
#endif
|
||||
};
|
||||
|
||||
#define EP_SINGLE_64 0x32 // EP0
|
||||
#define EP_DOUBLE_64 0x36 // Other endpoints
|
||||
|
||||
static
|
||||
void InitEP(u8 index, u8 type, u8 size)
|
||||
{
|
||||
UENUM = index;
|
||||
UECONX = 1;
|
||||
UECFG0X = type;
|
||||
UECFG1X = size;
|
||||
}
|
||||
|
||||
static
|
||||
void InitEndpoints()
|
||||
{
|
||||
for (u8 i = 1; i < sizeof(_initEndpoints); i++)
|
||||
{
|
||||
UENUM = i;
|
||||
UECONX = 1;
|
||||
UECFG0X = pgm_read_byte(_initEndpoints+i);
|
||||
UECFG1X = EP_DOUBLE_64;
|
||||
}
|
||||
UERST = 0x7E; // And reset them
|
||||
UERST = 0;
|
||||
}
|
||||
|
||||
// Handle CLASS_INTERFACE requests
|
||||
static
|
||||
bool ClassInterfaceRequest(Setup& setup)
|
||||
{
|
||||
u8 i = setup.wIndex;
|
||||
|
||||
#ifdef CDC_ENABLED
|
||||
if (CDC_ACM_INTERFACE == i)
|
||||
return CDC_Setup(setup);
|
||||
#endif
|
||||
|
||||
#ifdef HID_ENABLED
|
||||
if (HID_INTERFACE == i)
|
||||
return HID_Setup(setup);
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
int _cmark;
|
||||
int _cend;
|
||||
void InitControl(int end)
|
||||
{
|
||||
SetEP(0);
|
||||
_cmark = 0;
|
||||
_cend = end;
|
||||
}
|
||||
|
||||
static
|
||||
bool SendControl(u8 d)
|
||||
{
|
||||
if (_cmark < _cend)
|
||||
{
|
||||
if (!WaitForINOrOUT())
|
||||
return false;
|
||||
Send8(d);
|
||||
if (!((_cmark + 1) & 0x3F))
|
||||
ClearIN(); // Fifo is full, release this packet
|
||||
}
|
||||
_cmark++;
|
||||
return true;
|
||||
};
|
||||
|
||||
// Clipped by _cmark/_cend
|
||||
int USB_SendControl(u8 flags, const void* d, int len)
|
||||
{
|
||||
int sent = len;
|
||||
const u8* data = (const u8*)d;
|
||||
bool pgm = flags & TRANSFER_PGM;
|
||||
while (len--)
|
||||
{
|
||||
u8 c = pgm ? pgm_read_byte(data++) : *data++;
|
||||
if (!SendControl(c))
|
||||
return -1;
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
// Send a USB descriptor string. The string is stored in PROGMEM as a
|
||||
// plain ASCII string but is sent out as UTF-16 with the correct 2-byte
|
||||
// prefix
|
||||
static bool USB_SendStringDescriptor(const u8*string_P, u8 string_len) {
|
||||
SendControl(2 + string_len * 2);
|
||||
SendControl(3);
|
||||
for(u8 i = 0; i < string_len; i++) {
|
||||
bool r = SendControl(pgm_read_byte(&string_P[i]));
|
||||
r &= SendControl(0); // high byte
|
||||
if(!r) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Does not timeout or cross fifo boundaries
|
||||
// Will only work for transfers <= 64 bytes
|
||||
// TODO
|
||||
int USB_RecvControl(void* d, int len)
|
||||
{
|
||||
WaitOUT();
|
||||
Recv((u8*)d,len);
|
||||
ClearOUT();
|
||||
return len;
|
||||
}
|
||||
|
||||
int SendInterfaces()
|
||||
{
|
||||
int total = 0;
|
||||
u8 interfaces = 0;
|
||||
|
||||
#ifdef CDC_ENABLED
|
||||
total = CDC_GetInterface(&interfaces);
|
||||
#endif
|
||||
|
||||
#ifdef HID_ENABLED
|
||||
total += HID_GetInterface(&interfaces);
|
||||
#endif
|
||||
|
||||
return interfaces;
|
||||
}
|
||||
|
||||
// Construct a dynamic configuration descriptor
|
||||
// This really needs dynamic endpoint allocation etc
|
||||
// TODO
|
||||
static
|
||||
bool SendConfiguration(int maxlen)
|
||||
{
|
||||
// Count and measure interfaces
|
||||
InitControl(0);
|
||||
int interfaces = SendInterfaces();
|
||||
ConfigDescriptor config = D_CONFIG(_cmark + sizeof(ConfigDescriptor),interfaces);
|
||||
|
||||
// Now send them
|
||||
InitControl(maxlen);
|
||||
USB_SendControl(0,&config,sizeof(ConfigDescriptor));
|
||||
SendInterfaces();
|
||||
return true;
|
||||
}
|
||||
|
||||
u8 _cdcComposite = 0;
|
||||
|
||||
static
|
||||
bool SendDescriptor(Setup& setup)
|
||||
{
|
||||
u8 t = setup.wValueH;
|
||||
if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t)
|
||||
return SendConfiguration(setup.wLength);
|
||||
|
||||
InitControl(setup.wLength);
|
||||
#ifdef HID_ENABLED
|
||||
if (HID_REPORT_DESCRIPTOR_TYPE == t)
|
||||
return HID_GetDescriptor(t);
|
||||
#endif
|
||||
|
||||
const u8* desc_addr = 0;
|
||||
if (USB_DEVICE_DESCRIPTOR_TYPE == t)
|
||||
{
|
||||
if (setup.wLength == 8)
|
||||
_cdcComposite = 1;
|
||||
desc_addr = _cdcComposite ? (const u8*)&USB_DeviceDescriptorA : (const u8*)&USB_DeviceDescriptor;
|
||||
}
|
||||
else if (USB_STRING_DESCRIPTOR_TYPE == t)
|
||||
{
|
||||
if (setup.wValueL == 0) {
|
||||
desc_addr = (const u8*)&STRING_LANGUAGE;
|
||||
}
|
||||
else if (setup.wValueL == IPRODUCT) {
|
||||
return USB_SendStringDescriptor(STRING_PRODUCT, strlen(USB_PRODUCT));
|
||||
}
|
||||
else if (setup.wValueL == IMANUFACTURER) {
|
||||
return USB_SendStringDescriptor(STRING_MANUFACTURER, strlen(USB_MANUFACTURER));
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
if (desc_addr == 0)
|
||||
return false;
|
||||
u8 desc_length = pgm_read_byte(desc_addr);
|
||||
|
||||
USB_SendControl(TRANSFER_PGM,desc_addr,desc_length);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Endpoint 0 interrupt
|
||||
ISR(USB_COM_vect)
|
||||
{
|
||||
SetEP(0);
|
||||
if (!ReceivedSetupInt())
|
||||
return;
|
||||
|
||||
Setup setup;
|
||||
Recv((u8*)&setup,8);
|
||||
ClearSetupInt();
|
||||
|
||||
u8 requestType = setup.bmRequestType;
|
||||
if (requestType & REQUEST_DEVICETOHOST)
|
||||
WaitIN();
|
||||
else
|
||||
ClearIN();
|
||||
|
||||
bool ok = true;
|
||||
if (REQUEST_STANDARD == (requestType & REQUEST_TYPE))
|
||||
{
|
||||
// Standard Requests
|
||||
u8 r = setup.bRequest;
|
||||
if (GET_STATUS == r)
|
||||
{
|
||||
Send8(0); // TODO
|
||||
Send8(0);
|
||||
}
|
||||
else if (CLEAR_FEATURE == r)
|
||||
{
|
||||
}
|
||||
else if (SET_FEATURE == r)
|
||||
{
|
||||
}
|
||||
else if (SET_ADDRESS == r)
|
||||
{
|
||||
WaitIN();
|
||||
UDADDR = setup.wValueL | (1<<ADDEN);
|
||||
}
|
||||
else if (GET_DESCRIPTOR == r)
|
||||
{
|
||||
ok = SendDescriptor(setup);
|
||||
}
|
||||
else if (SET_DESCRIPTOR == r)
|
||||
{
|
||||
ok = false;
|
||||
}
|
||||
else if (GET_CONFIGURATION == r)
|
||||
{
|
||||
Send8(1);
|
||||
}
|
||||
else if (SET_CONFIGURATION == r)
|
||||
{
|
||||
if (REQUEST_DEVICE == (requestType & REQUEST_RECIPIENT))
|
||||
{
|
||||
InitEndpoints();
|
||||
_usbConfiguration = setup.wValueL;
|
||||
} else
|
||||
ok = false;
|
||||
}
|
||||
else if (GET_INTERFACE == r)
|
||||
{
|
||||
}
|
||||
else if (SET_INTERFACE == r)
|
||||
{
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
InitControl(setup.wLength); // Max length of transfer
|
||||
ok = ClassInterfaceRequest(setup);
|
||||
}
|
||||
|
||||
if (ok)
|
||||
ClearIN();
|
||||
else
|
||||
{
|
||||
Stall();
|
||||
}
|
||||
}
|
||||
|
||||
void USB_Flush(u8 ep)
|
||||
{
|
||||
SetEP(ep);
|
||||
if (FifoByteCount())
|
||||
ReleaseTX();
|
||||
}
|
||||
|
||||
// General interrupt
|
||||
ISR(USB_GEN_vect)
|
||||
{
|
||||
u8 udint = UDINT;
|
||||
UDINT = 0;
|
||||
|
||||
// End of Reset
|
||||
if (udint & (1<<EORSTI))
|
||||
{
|
||||
InitEP(0,EP_TYPE_CONTROL,EP_SINGLE_64); // init ep0
|
||||
_usbConfiguration = 0; // not configured yet
|
||||
UEIENX = 1 << RXSTPE; // Enable interrupts for ep0
|
||||
}
|
||||
|
||||
// Start of Frame - happens every millisecond so we use it for TX and RX LED one-shot timing, too
|
||||
if (udint & (1<<SOFI))
|
||||
{
|
||||
#ifdef CDC_ENABLED
|
||||
USB_Flush(CDC_TX); // Send a tx frame if found
|
||||
if (USB_Available(CDC_RX)) // Handle received bytes (if any)
|
||||
Serial.accept();
|
||||
#endif
|
||||
|
||||
// check whether the one-shot period has elapsed. if so, turn off the LED
|
||||
if (TxLEDPulse && !(--TxLEDPulse))
|
||||
TXLED0;
|
||||
if (RxLEDPulse && !(--RxLEDPulse))
|
||||
RXLED0;
|
||||
}
|
||||
}
|
||||
|
||||
// VBUS or counting frames
|
||||
// Any frame counting?
|
||||
u8 USBConnected()
|
||||
{
|
||||
u8 f = UDFNUML;
|
||||
delay(3);
|
||||
return f != UDFNUML;
|
||||
}
|
||||
|
||||
//=======================================================================
|
||||
//=======================================================================
|
||||
|
||||
USBDevice_ USBDevice;
|
||||
|
||||
USBDevice_::USBDevice_()
|
||||
{
|
||||
}
|
||||
|
||||
void USBDevice_::attach()
|
||||
{
|
||||
_usbConfiguration = 0;
|
||||
UHWCON = 0x01; // power internal reg
|
||||
USBCON = (1<<USBE)|(1<<FRZCLK); // clock frozen, usb enabled
|
||||
#if F_CPU == 16000000UL
|
||||
PLLCSR = 0x12; // Need 16 MHz xtal
|
||||
#elif F_CPU == 8000000UL
|
||||
PLLCSR = 0x02; // Need 8 MHz xtal
|
||||
#endif
|
||||
while (!(PLLCSR & (1<<PLOCK))) // wait for lock pll
|
||||
;
|
||||
|
||||
// Some tests on specific versions of macosx (10.7.3), reported some
|
||||
// strange behaviuors when the board is reset using the serial
|
||||
// port touch at 1200 bps. This delay fixes this behaviour.
|
||||
delay(1);
|
||||
|
||||
USBCON = ((1<<USBE)|(1<<OTGPADE)); // start USB clock
|
||||
UDIEN = (1<<EORSTE)|(1<<SOFE); // Enable interrupts for EOR (End of Reset) and SOF (start of frame)
|
||||
UDCON = 0; // enable attach resistor
|
||||
|
||||
TX_RX_LED_INIT;
|
||||
}
|
||||
|
||||
void USBDevice_::detach()
|
||||
{
|
||||
}
|
||||
|
||||
// Check for interrupts
|
||||
// TODO: VBUS detection
|
||||
bool USBDevice_::configured()
|
||||
{
|
||||
return _usbConfiguration;
|
||||
}
|
||||
|
||||
void USBDevice_::poll()
|
||||
{
|
||||
}
|
||||
|
||||
#endif /* if defined(USBCON) */
|
@ -1,303 +0,0 @@
|
||||
|
||||
// Copyright (c) 2010, Peter Barrett
|
||||
/*
|
||||
** Permission to use, copy, modify, and/or distribute this software for
|
||||
** any purpose with or without fee is hereby granted, provided that the
|
||||
** above copyright notice and this permission notice appear in all copies.
|
||||
**
|
||||
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
|
||||
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
|
||||
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
|
||||
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
|
||||
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
||||
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
|
||||
** SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef __USBCORE_H__
|
||||
#define __USBCORE_H__
|
||||
|
||||
// Standard requests
|
||||
#define GET_STATUS 0
|
||||
#define CLEAR_FEATURE 1
|
||||
#define SET_FEATURE 3
|
||||
#define SET_ADDRESS 5
|
||||
#define GET_DESCRIPTOR 6
|
||||
#define SET_DESCRIPTOR 7
|
||||
#define GET_CONFIGURATION 8
|
||||
#define SET_CONFIGURATION 9
|
||||
#define GET_INTERFACE 10
|
||||
#define SET_INTERFACE 11
|
||||
|
||||
|
||||
// bmRequestType
|
||||
#define REQUEST_HOSTTODEVICE 0x00
|
||||
#define REQUEST_DEVICETOHOST 0x80
|
||||
#define REQUEST_DIRECTION 0x80
|
||||
|
||||
#define REQUEST_STANDARD 0x00
|
||||
#define REQUEST_CLASS 0x20
|
||||
#define REQUEST_VENDOR 0x40
|
||||
#define REQUEST_TYPE 0x60
|
||||
|
||||
#define REQUEST_DEVICE 0x00
|
||||
#define REQUEST_INTERFACE 0x01
|
||||
#define REQUEST_ENDPOINT 0x02
|
||||
#define REQUEST_OTHER 0x03
|
||||
#define REQUEST_RECIPIENT 0x03
|
||||
|
||||
#define REQUEST_DEVICETOHOST_CLASS_INTERFACE (REQUEST_DEVICETOHOST + REQUEST_CLASS + REQUEST_INTERFACE)
|
||||
#define REQUEST_HOSTTODEVICE_CLASS_INTERFACE (REQUEST_HOSTTODEVICE + REQUEST_CLASS + REQUEST_INTERFACE)
|
||||
|
||||
// Class requests
|
||||
|
||||
#define CDC_SET_LINE_CODING 0x20
|
||||
#define CDC_GET_LINE_CODING 0x21
|
||||
#define CDC_SET_CONTROL_LINE_STATE 0x22
|
||||
|
||||
#define MSC_RESET 0xFF
|
||||
#define MSC_GET_MAX_LUN 0xFE
|
||||
|
||||
#define HID_GET_REPORT 0x01
|
||||
#define HID_GET_IDLE 0x02
|
||||
#define HID_GET_PROTOCOL 0x03
|
||||
#define HID_SET_REPORT 0x09
|
||||
#define HID_SET_IDLE 0x0A
|
||||
#define HID_SET_PROTOCOL 0x0B
|
||||
|
||||
// Descriptors
|
||||
|
||||
#define USB_DEVICE_DESC_SIZE 18
|
||||
#define USB_CONFIGUARTION_DESC_SIZE 9
|
||||
#define USB_INTERFACE_DESC_SIZE 9
|
||||
#define USB_ENDPOINT_DESC_SIZE 7
|
||||
|
||||
#define USB_DEVICE_DESCRIPTOR_TYPE 1
|
||||
#define USB_CONFIGURATION_DESCRIPTOR_TYPE 2
|
||||
#define USB_STRING_DESCRIPTOR_TYPE 3
|
||||
#define USB_INTERFACE_DESCRIPTOR_TYPE 4
|
||||
#define USB_ENDPOINT_DESCRIPTOR_TYPE 5
|
||||
|
||||
#define USB_DEVICE_CLASS_COMMUNICATIONS 0x02
|
||||
#define USB_DEVICE_CLASS_HUMAN_INTERFACE 0x03
|
||||
#define USB_DEVICE_CLASS_STORAGE 0x08
|
||||
#define USB_DEVICE_CLASS_VENDOR_SPECIFIC 0xFF
|
||||
|
||||
#define USB_CONFIG_POWERED_MASK 0x40
|
||||
#define USB_CONFIG_BUS_POWERED 0x80
|
||||
#define USB_CONFIG_SELF_POWERED 0xC0
|
||||
#define USB_CONFIG_REMOTE_WAKEUP 0x20
|
||||
|
||||
// bMaxPower in Configuration Descriptor
|
||||
#define USB_CONFIG_POWER_MA(mA) ((mA)/2)
|
||||
|
||||
// bEndpointAddress in Endpoint Descriptor
|
||||
#define USB_ENDPOINT_DIRECTION_MASK 0x80
|
||||
#define USB_ENDPOINT_OUT(addr) ((addr) | 0x00)
|
||||
#define USB_ENDPOINT_IN(addr) ((addr) | 0x80)
|
||||
|
||||
#define USB_ENDPOINT_TYPE_MASK 0x03
|
||||
#define USB_ENDPOINT_TYPE_CONTROL 0x00
|
||||
#define USB_ENDPOINT_TYPE_ISOCHRONOUS 0x01
|
||||
#define USB_ENDPOINT_TYPE_BULK 0x02
|
||||
#define USB_ENDPOINT_TYPE_INTERRUPT 0x03
|
||||
|
||||
#define TOBYTES(x) ((x) & 0xFF),(((x) >> 8) & 0xFF)
|
||||
|
||||
#define CDC_V1_10 0x0110
|
||||
#define CDC_COMMUNICATION_INTERFACE_CLASS 0x02
|
||||
|
||||
#define CDC_CALL_MANAGEMENT 0x01
|
||||
#define CDC_ABSTRACT_CONTROL_MODEL 0x02
|
||||
#define CDC_HEADER 0x00
|
||||
#define CDC_ABSTRACT_CONTROL_MANAGEMENT 0x02
|
||||
#define CDC_UNION 0x06
|
||||
#define CDC_CS_INTERFACE 0x24
|
||||
#define CDC_CS_ENDPOINT 0x25
|
||||
#define CDC_DATA_INTERFACE_CLASS 0x0A
|
||||
|
||||
#define MSC_SUBCLASS_SCSI 0x06
|
||||
#define MSC_PROTOCOL_BULK_ONLY 0x50
|
||||
|
||||
#define HID_HID_DESCRIPTOR_TYPE 0x21
|
||||
#define HID_REPORT_DESCRIPTOR_TYPE 0x22
|
||||
#define HID_PHYSICAL_DESCRIPTOR_TYPE 0x23
|
||||
|
||||
|
||||
// Device
|
||||
typedef struct {
|
||||
u8 len; // 18
|
||||
u8 dtype; // 1 USB_DEVICE_DESCRIPTOR_TYPE
|
||||
u16 usbVersion; // 0x200
|
||||
u8 deviceClass;
|
||||
u8 deviceSubClass;
|
||||
u8 deviceProtocol;
|
||||
u8 packetSize0; // Packet 0
|
||||
u16 idVendor;
|
||||
u16 idProduct;
|
||||
u16 deviceVersion; // 0x100
|
||||
u8 iManufacturer;
|
||||
u8 iProduct;
|
||||
u8 iSerialNumber;
|
||||
u8 bNumConfigurations;
|
||||
} DeviceDescriptor;
|
||||
|
||||
// Config
|
||||
typedef struct {
|
||||
u8 len; // 9
|
||||
u8 dtype; // 2
|
||||
u16 clen; // total length
|
||||
u8 numInterfaces;
|
||||
u8 config;
|
||||
u8 iconfig;
|
||||
u8 attributes;
|
||||
u8 maxPower;
|
||||
} ConfigDescriptor;
|
||||
|
||||
// String
|
||||
|
||||
// Interface
|
||||
typedef struct
|
||||
{
|
||||
u8 len; // 9
|
||||
u8 dtype; // 4
|
||||
u8 number;
|
||||
u8 alternate;
|
||||
u8 numEndpoints;
|
||||
u8 interfaceClass;
|
||||
u8 interfaceSubClass;
|
||||
u8 protocol;
|
||||
u8 iInterface;
|
||||
} InterfaceDescriptor;
|
||||
|
||||
// Endpoint
|
||||
typedef struct
|
||||
{
|
||||
u8 len; // 7
|
||||
u8 dtype; // 5
|
||||
u8 addr;
|
||||
u8 attr;
|
||||
u16 packetSize;
|
||||
u8 interval;
|
||||
} EndpointDescriptor;
|
||||
|
||||
// Interface Association Descriptor
|
||||
// Used to bind 2 interfaces together in CDC compostite device
|
||||
typedef struct
|
||||
{
|
||||
u8 len; // 8
|
||||
u8 dtype; // 11
|
||||
u8 firstInterface;
|
||||
u8 interfaceCount;
|
||||
u8 functionClass;
|
||||
u8 funtionSubClass;
|
||||
u8 functionProtocol;
|
||||
u8 iInterface;
|
||||
} IADDescriptor;
|
||||
|
||||
// CDC CS interface descriptor
|
||||
typedef struct
|
||||
{
|
||||
u8 len; // 5
|
||||
u8 dtype; // 0x24
|
||||
u8 subtype;
|
||||
u8 d0;
|
||||
u8 d1;
|
||||
} CDCCSInterfaceDescriptor;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
u8 len; // 4
|
||||
u8 dtype; // 0x24
|
||||
u8 subtype;
|
||||
u8 d0;
|
||||
} CDCCSInterfaceDescriptor4;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
u8 len;
|
||||
u8 dtype; // 0x24
|
||||
u8 subtype; // 1
|
||||
u8 bmCapabilities;
|
||||
u8 bDataInterface;
|
||||
} CMFunctionalDescriptor;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
u8 len;
|
||||
u8 dtype; // 0x24
|
||||
u8 subtype; // 1
|
||||
u8 bmCapabilities;
|
||||
} ACMFunctionalDescriptor;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
// IAD
|
||||
IADDescriptor iad; // Only needed on compound device
|
||||
|
||||
// Control
|
||||
InterfaceDescriptor cif; //
|
||||
CDCCSInterfaceDescriptor header;
|
||||
CMFunctionalDescriptor callManagement; // Call Management
|
||||
ACMFunctionalDescriptor controlManagement; // ACM
|
||||
CDCCSInterfaceDescriptor functionalDescriptor; // CDC_UNION
|
||||
EndpointDescriptor cifin;
|
||||
|
||||
// Data
|
||||
InterfaceDescriptor dif;
|
||||
EndpointDescriptor in;
|
||||
EndpointDescriptor out;
|
||||
} CDCDescriptor;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
InterfaceDescriptor msc;
|
||||
EndpointDescriptor in;
|
||||
EndpointDescriptor out;
|
||||
} MSCDescriptor;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
u8 len; // 9
|
||||
u8 dtype; // 0x21
|
||||
u8 addr;
|
||||
u8 versionL; // 0x101
|
||||
u8 versionH; // 0x101
|
||||
u8 country;
|
||||
u8 desctype; // 0x22 report
|
||||
u8 descLenL;
|
||||
u8 descLenH;
|
||||
} HIDDescDescriptor;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
InterfaceDescriptor hid;
|
||||
HIDDescDescriptor desc;
|
||||
EndpointDescriptor in;
|
||||
} HIDDescriptor;
|
||||
|
||||
|
||||
#define D_DEVICE(_class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs) \
|
||||
{ 18, 1, 0x200, _class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs }
|
||||
|
||||
#define D_CONFIG(_totalLength,_interfaces) \
|
||||
{ 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED, USB_CONFIG_POWER_MA(500) }
|
||||
|
||||
#define D_INTERFACE(_n,_numEndpoints,_class,_subClass,_protocol) \
|
||||
{ 9, 4, _n, 0, _numEndpoints, _class,_subClass, _protocol, 0 }
|
||||
|
||||
#define D_ENDPOINT(_addr,_attr,_packetSize, _interval) \
|
||||
{ 7, 5, _addr,_attr,_packetSize, _interval }
|
||||
|
||||
#define D_IAD(_firstInterface, _count, _class, _subClass, _protocol) \
|
||||
{ 8, 11, _firstInterface, _count, _class, _subClass, _protocol, 0 }
|
||||
|
||||
#define D_HIDREPORT(_descriptorLength) \
|
||||
{ 9, 0x21, 0x1, 0x1, 0, 1, 0x22, _descriptorLength, 0 }
|
||||
|
||||
#define D_CDCCS(_subtype,_d0,_d1) { 5, 0x24, _subtype, _d0, _d1 }
|
||||
#define D_CDCCS4(_subtype,_d0) { 4, 0x24, _subtype, _d0 }
|
||||
|
||||
|
||||
#endif
|
@ -1,63 +0,0 @@
|
||||
|
||||
|
||||
/* Copyright (c) 2011, Peter Barrett
|
||||
**
|
||||
** Permission to use, copy, modify, and/or distribute this software for
|
||||
** any purpose with or without fee is hereby granted, provided that the
|
||||
** above copyright notice and this permission notice appear in all copies.
|
||||
**
|
||||
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
|
||||
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
|
||||
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
|
||||
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
|
||||
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
||||
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
|
||||
** SOFTWARE.
|
||||
*/
|
||||
|
||||
#define CDC_ENABLED
|
||||
#define HID_ENABLED
|
||||
|
||||
|
||||
#ifdef CDC_ENABLED
|
||||
#define CDC_INTERFACE_COUNT 2
|
||||
#define CDC_ENPOINT_COUNT 3
|
||||
#else
|
||||
#define CDC_INTERFACE_COUNT 0
|
||||
#define CDC_ENPOINT_COUNT 0
|
||||
#endif
|
||||
|
||||
#ifdef HID_ENABLED
|
||||
#define HID_INTERFACE_COUNT 1
|
||||
#define HID_ENPOINT_COUNT 1
|
||||
#else
|
||||
#define HID_INTERFACE_COUNT 0
|
||||
#define HID_ENPOINT_COUNT 0
|
||||
#endif
|
||||
|
||||
#define CDC_ACM_INTERFACE 0 // CDC ACM
|
||||
#define CDC_DATA_INTERFACE 1 // CDC Data
|
||||
#define CDC_FIRST_ENDPOINT 1
|
||||
#define CDC_ENDPOINT_ACM (CDC_FIRST_ENDPOINT) // CDC First
|
||||
#define CDC_ENDPOINT_OUT (CDC_FIRST_ENDPOINT+1)
|
||||
#define CDC_ENDPOINT_IN (CDC_FIRST_ENDPOINT+2)
|
||||
|
||||
#define HID_INTERFACE (CDC_ACM_INTERFACE + CDC_INTERFACE_COUNT) // HID Interface
|
||||
#define HID_FIRST_ENDPOINT (CDC_FIRST_ENDPOINT + CDC_ENPOINT_COUNT)
|
||||
#define HID_ENDPOINT_INT (HID_FIRST_ENDPOINT)
|
||||
|
||||
#define INTERFACE_COUNT (MSC_INTERFACE + MSC_INTERFACE_COUNT)
|
||||
|
||||
#ifdef CDC_ENABLED
|
||||
#define CDC_RX CDC_ENDPOINT_OUT
|
||||
#define CDC_TX CDC_ENDPOINT_IN
|
||||
#endif
|
||||
|
||||
#ifdef HID_ENABLED
|
||||
#define HID_TX HID_ENDPOINT_INT
|
||||
#endif
|
||||
|
||||
#define IMANUFACTURER 1
|
||||
#define IPRODUCT 2
|
||||
|
@ -1,88 +0,0 @@
|
||||
/*
|
||||
* Udp.cpp: Library to send/receive UDP packets.
|
||||
*
|
||||
* NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these)
|
||||
* 1) UDP does not guarantee the order in which assembled UDP packets are received. This
|
||||
* might not happen often in practice, but in larger network topologies, a UDP
|
||||
* packet can be received out of sequence.
|
||||
* 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being
|
||||
* aware of it. Again, this may not be a concern in practice on small local networks.
|
||||
* For more information, see http://www.cafeaulait.org/course/week12/35.html
|
||||
*
|
||||
* MIT License:
|
||||
* Copyright (c) 2008 Bjoern Hartmann
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
* bjoern@cs.stanford.edu 12/30/2008
|
||||
*/
|
||||
|
||||
#ifndef udp_h
|
||||
#define udp_h
|
||||
|
||||
#include <Stream.h>
|
||||
#include <IPAddress.h>
|
||||
|
||||
class UDP : public Stream {
|
||||
|
||||
public:
|
||||
virtual uint8_t begin(uint16_t) =0; // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use
|
||||
virtual void stop() =0; // Finish with the UDP socket
|
||||
|
||||
// Sending UDP packets
|
||||
|
||||
// Start building up a packet to send to the remote host specific in ip and port
|
||||
// Returns 1 if successful, 0 if there was a problem with the supplied IP address or port
|
||||
virtual int beginPacket(IPAddress ip, uint16_t port) =0;
|
||||
// Start building up a packet to send to the remote host specific in host and port
|
||||
// Returns 1 if successful, 0 if there was a problem resolving the hostname or port
|
||||
virtual int beginPacket(const char *host, uint16_t port) =0;
|
||||
// Finish off this packet and send it
|
||||
// Returns 1 if the packet was sent successfully, 0 if there was an error
|
||||
virtual int endPacket() =0;
|
||||
// Write a single byte into the packet
|
||||
virtual size_t write(uint8_t) =0;
|
||||
// Write size bytes from buffer into the packet
|
||||
virtual size_t write(const uint8_t *buffer, size_t size) =0;
|
||||
|
||||
// Start processing the next available incoming packet
|
||||
// Returns the size of the packet in bytes, or 0 if no packets are available
|
||||
virtual int parsePacket() =0;
|
||||
// Number of bytes remaining in the current packet
|
||||
virtual int available() =0;
|
||||
// Read a single byte from the current packet
|
||||
virtual int read() =0;
|
||||
// Read up to len bytes from the current packet and place them into buffer
|
||||
// Returns the number of bytes read, or 0 if none are available
|
||||
virtual int read(unsigned char* buffer, size_t len) =0;
|
||||
// Read up to len characters from the current packet and place them into buffer
|
||||
// Returns the number of characters read, or 0 if none are available
|
||||
virtual int read(char* buffer, size_t len) =0;
|
||||
// Return the next byte from the current packet without moving on to the next byte
|
||||
virtual int peek() =0;
|
||||
virtual void flush() =0; // Finish reading the current packet
|
||||
|
||||
// Return the IP address of the host who sent the current incoming packet
|
||||
virtual IPAddress remoteIP() =0;
|
||||
// Return the port of the host who sent the current incoming packet
|
||||
virtual uint16_t remotePort() =0;
|
||||
protected:
|
||||
uint8_t* rawIPAddress(IPAddress& addr) { return addr.raw_address(); };
|
||||
};
|
||||
|
||||
#endif
|
@ -1,168 +0,0 @@
|
||||
/*
|
||||
WCharacter.h - Character utility functions for Wiring & Arduino
|
||||
Copyright (c) 2010 Hernando Barragan. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#ifndef Character_h
|
||||
#define Character_h
|
||||
|
||||
#include <ctype.h>
|
||||
|
||||
// WCharacter.h prototypes
|
||||
inline boolean isAlphaNumeric(int c) __attribute__((always_inline));
|
||||
inline boolean isAlpha(int c) __attribute__((always_inline));
|
||||
inline boolean isAscii(int c) __attribute__((always_inline));
|
||||
inline boolean isWhitespace(int c) __attribute__((always_inline));
|
||||
inline boolean isControl(int c) __attribute__((always_inline));
|
||||
inline boolean isDigit(int c) __attribute__((always_inline));
|
||||
inline boolean isGraph(int c) __attribute__((always_inline));
|
||||
inline boolean isLowerCase(int c) __attribute__((always_inline));
|
||||
inline boolean isPrintable(int c) __attribute__((always_inline));
|
||||
inline boolean isPunct(int c) __attribute__((always_inline));
|
||||
inline boolean isSpace(int c) __attribute__((always_inline));
|
||||
inline boolean isUpperCase(int c) __attribute__((always_inline));
|
||||
inline boolean isHexadecimalDigit(int c) __attribute__((always_inline));
|
||||
inline int toAscii(int c) __attribute__((always_inline));
|
||||
inline int toLowerCase(int c) __attribute__((always_inline));
|
||||
inline int toUpperCase(int c)__attribute__((always_inline));
|
||||
|
||||
|
||||
// Checks for an alphanumeric character.
|
||||
// It is equivalent to (isalpha(c) || isdigit(c)).
|
||||
inline boolean isAlphaNumeric(int c)
|
||||
{
|
||||
return ( isalnum(c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks for an alphabetic character.
|
||||
// It is equivalent to (isupper(c) || islower(c)).
|
||||
inline boolean isAlpha(int c)
|
||||
{
|
||||
return ( isalpha(c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks whether c is a 7-bit unsigned char value
|
||||
// that fits into the ASCII character set.
|
||||
inline boolean isAscii(int c)
|
||||
{
|
||||
return ( isascii (c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks for a blank character, that is, a space or a tab.
|
||||
inline boolean isWhitespace(int c)
|
||||
{
|
||||
return ( isblank (c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks for a control character.
|
||||
inline boolean isControl(int c)
|
||||
{
|
||||
return ( iscntrl (c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks for a digit (0 through 9).
|
||||
inline boolean isDigit(int c)
|
||||
{
|
||||
return ( isdigit (c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks for any printable character except space.
|
||||
inline boolean isGraph(int c)
|
||||
{
|
||||
return ( isgraph (c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks for a lower-case character.
|
||||
inline boolean isLowerCase(int c)
|
||||
{
|
||||
return (islower (c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks for any printable character including space.
|
||||
inline boolean isPrintable(int c)
|
||||
{
|
||||
return ( isprint (c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks for any printable character which is not a space
|
||||
// or an alphanumeric character.
|
||||
inline boolean isPunct(int c)
|
||||
{
|
||||
return ( ispunct (c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks for white-space characters. For the avr-libc library,
|
||||
// these are: space, formfeed ('\f'), newline ('\n'), carriage
|
||||
// return ('\r'), horizontal tab ('\t'), and vertical tab ('\v').
|
||||
inline boolean isSpace(int c)
|
||||
{
|
||||
return ( isspace (c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks for an uppercase letter.
|
||||
inline boolean isUpperCase(int c)
|
||||
{
|
||||
return ( isupper (c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Checks for a hexadecimal digits, i.e. one of 0 1 2 3 4 5 6 7
|
||||
// 8 9 a b c d e f A B C D E F.
|
||||
inline boolean isHexadecimalDigit(int c)
|
||||
{
|
||||
return ( isxdigit (c) == 0 ? false : true);
|
||||
}
|
||||
|
||||
|
||||
// Converts c to a 7-bit unsigned char value that fits into the
|
||||
// ASCII character set, by clearing the high-order bits.
|
||||
inline int toAscii(int c)
|
||||
{
|
||||
return toascii (c);
|
||||
}
|
||||
|
||||
|
||||
// Warning:
|
||||
// Many people will be unhappy if you use this function.
|
||||
// This function will convert accented letters into random
|
||||
// characters.
|
||||
|
||||
// Converts the letter c to lower case, if possible.
|
||||
inline int toLowerCase(int c)
|
||||
{
|
||||
return tolower (c);
|
||||
}
|
||||
|
||||
|
||||
// Converts the letter c to upper case, if possible.
|
||||
inline int toUpperCase(int c)
|
||||
{
|
||||
return toupper (c);
|
||||
}
|
||||
|
||||
#endif
|
@ -1,334 +0,0 @@
|
||||
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
|
||||
|
||||
/*
|
||||
Part of the Wiring project - http://wiring.uniandes.edu.co
|
||||
|
||||
Copyright (c) 2004-05 Hernando Barragan
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General
|
||||
Public License along with this library; if not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
|
||||
Boston, MA 02111-1307 USA
|
||||
|
||||
Modified 24 November 2006 by David A. Mellis
|
||||
Modified 1 August 2010 by Mark Sproul
|
||||
*/
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <avr/io.h>
|
||||
#include <avr/interrupt.h>
|
||||
#include <avr/pgmspace.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "wiring_private.h"
|
||||
|
||||
static volatile voidFuncPtr intFunc[EXTERNAL_NUM_INTERRUPTS];
|
||||
// volatile static voidFuncPtr twiIntFunc;
|
||||
|
||||
void attachInterrupt(uint8_t interruptNum, void (*userFunc)(void), int mode) {
|
||||
if(interruptNum < EXTERNAL_NUM_INTERRUPTS) {
|
||||
intFunc[interruptNum] = userFunc;
|
||||
|
||||
// Configure the interrupt mode (trigger on low input, any change, rising
|
||||
// edge, or falling edge). The mode constants were chosen to correspond
|
||||
// to the configuration bits in the hardware register, so we simply shift
|
||||
// the mode into place.
|
||||
|
||||
// Enable the interrupt.
|
||||
|
||||
switch (interruptNum) {
|
||||
#if defined(__AVR_ATmega32U4__)
|
||||
// I hate doing this, but the register assignment differs between the 1280/2560
|
||||
// and the 32U4. Since avrlib defines registers PCMSK1 and PCMSK2 that aren't
|
||||
// even present on the 32U4 this is the only way to distinguish between them.
|
||||
case 0:
|
||||
EICRA = (EICRA & ~((1<<ISC00) | (1<<ISC01))) | (mode << ISC00);
|
||||
EIMSK |= (1<<INT0);
|
||||
break;
|
||||
case 1:
|
||||
EICRA = (EICRA & ~((1<<ISC10) | (1<<ISC11))) | (mode << ISC10);
|
||||
EIMSK |= (1<<INT1);
|
||||
break;
|
||||
case 2:
|
||||
EICRA = (EICRA & ~((1<<ISC20) | (1<<ISC21))) | (mode << ISC20);
|
||||
EIMSK |= (1<<INT2);
|
||||
break;
|
||||
case 3:
|
||||
EICRA = (EICRA & ~((1<<ISC30) | (1<<ISC31))) | (mode << ISC30);
|
||||
EIMSK |= (1<<INT3);
|
||||
break;
|
||||
case 4:
|
||||
EICRB = (EICRB & ~((1<<ISC60) | (1<<ISC61))) | (mode << ISC60);
|
||||
EIMSK |= (1<<INT6);
|
||||
break;
|
||||
#elif defined(EICRA) && defined(EICRB) && defined(EIMSK)
|
||||
case 2:
|
||||
EICRA = (EICRA & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00);
|
||||
EIMSK |= (1 << INT0);
|
||||
break;
|
||||
case 3:
|
||||
EICRA = (EICRA & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10);
|
||||
EIMSK |= (1 << INT1);
|
||||
break;
|
||||
case 4:
|
||||
EICRA = (EICRA & ~((1 << ISC20) | (1 << ISC21))) | (mode << ISC20);
|
||||
EIMSK |= (1 << INT2);
|
||||
break;
|
||||
case 5:
|
||||
EICRA = (EICRA & ~((1 << ISC30) | (1 << ISC31))) | (mode << ISC30);
|
||||
EIMSK |= (1 << INT3);
|
||||
break;
|
||||
case 0:
|
||||
EICRB = (EICRB & ~((1 << ISC40) | (1 << ISC41))) | (mode << ISC40);
|
||||
EIMSK |= (1 << INT4);
|
||||
break;
|
||||
case 1:
|
||||
EICRB = (EICRB & ~((1 << ISC50) | (1 << ISC51))) | (mode << ISC50);
|
||||
EIMSK |= (1 << INT5);
|
||||
break;
|
||||
case 6:
|
||||
EICRB = (EICRB & ~((1 << ISC60) | (1 << ISC61))) | (mode << ISC60);
|
||||
EIMSK |= (1 << INT6);
|
||||
break;
|
||||
case 7:
|
||||
EICRB = (EICRB & ~((1 << ISC70) | (1 << ISC71))) | (mode << ISC70);
|
||||
EIMSK |= (1 << INT7);
|
||||
break;
|
||||
#else
|
||||
case 0:
|
||||
#if defined(EICRA) && defined(ISC00) && defined(EIMSK)
|
||||
EICRA = (EICRA & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00);
|
||||
EIMSK |= (1 << INT0);
|
||||
#elif defined(MCUCR) && defined(ISC00) && defined(GICR)
|
||||
MCUCR = (MCUCR & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00);
|
||||
GICR |= (1 << INT0);
|
||||
#elif defined(MCUCR) && defined(ISC00) && defined(GIMSK)
|
||||
MCUCR = (MCUCR & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00);
|
||||
GIMSK |= (1 << INT0);
|
||||
#else
|
||||
#error attachInterrupt not finished for this CPU (case 0)
|
||||
#endif
|
||||
break;
|
||||
|
||||
case 1:
|
||||
#if defined(EICRA) && defined(ISC10) && defined(ISC11) && defined(EIMSK)
|
||||
EICRA = (EICRA & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10);
|
||||
EIMSK |= (1 << INT1);
|
||||
#elif defined(MCUCR) && defined(ISC10) && defined(ISC11) && defined(GICR)
|
||||
MCUCR = (MCUCR & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10);
|
||||
GICR |= (1 << INT1);
|
||||
#elif defined(MCUCR) && defined(ISC10) && defined(GIMSK) && defined(GIMSK)
|
||||
MCUCR = (MCUCR & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10);
|
||||
GIMSK |= (1 << INT1);
|
||||
#else
|
||||
#warning attachInterrupt may need some more work for this cpu (case 1)
|
||||
#endif
|
||||
break;
|
||||
|
||||
case 2:
|
||||
#if defined(EICRA) && defined(ISC20) && defined(ISC21) && defined(EIMSK)
|
||||
EICRA = (EICRA & ~((1 << ISC20) | (1 << ISC21))) | (mode << ISC20);
|
||||
EIMSK |= (1 << INT2);
|
||||
#elif defined(MCUCR) && defined(ISC20) && defined(ISC21) && defined(GICR)
|
||||
MCUCR = (MCUCR & ~((1 << ISC20) | (1 << ISC21))) | (mode << ISC20);
|
||||
GICR |= (1 << INT2);
|
||||
#elif defined(MCUCR) && defined(ISC20) && defined(GIMSK) && defined(GIMSK)
|
||||
MCUCR = (MCUCR & ~((1 << ISC20) | (1 << ISC21))) | (mode << ISC20);
|
||||
GIMSK |= (1 << INT2);
|
||||
#endif
|
||||
break;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void detachInterrupt(uint8_t interruptNum) {
|
||||
if(interruptNum < EXTERNAL_NUM_INTERRUPTS) {
|
||||
// Disable the interrupt. (We can't assume that interruptNum is equal
|
||||
// to the number of the EIMSK bit to clear, as this isn't true on the
|
||||
// ATmega8. There, INT0 is 6 and INT1 is 7.)
|
||||
switch (interruptNum) {
|
||||
#if defined(__AVR_ATmega32U4__)
|
||||
case 0:
|
||||
EIMSK &= ~(1<<INT0);
|
||||
break;
|
||||
case 1:
|
||||
EIMSK &= ~(1<<INT1);
|
||||
break;
|
||||
case 2:
|
||||
EIMSK &= ~(1<<INT2);
|
||||
break;
|
||||
case 3:
|
||||
EIMSK &= ~(1<<INT3);
|
||||
break;
|
||||
case 4:
|
||||
EIMSK &= ~(1<<INT6);
|
||||
break;
|
||||
#elif defined(EICRA) && defined(EICRB) && defined(EIMSK)
|
||||
case 2:
|
||||
EIMSK &= ~(1 << INT0);
|
||||
break;
|
||||
case 3:
|
||||
EIMSK &= ~(1 << INT1);
|
||||
break;
|
||||
case 4:
|
||||
EIMSK &= ~(1 << INT2);
|
||||
break;
|
||||
case 5:
|
||||
EIMSK &= ~(1 << INT3);
|
||||
break;
|
||||
case 0:
|
||||
EIMSK &= ~(1 << INT4);
|
||||
break;
|
||||
case 1:
|
||||
EIMSK &= ~(1 << INT5);
|
||||
break;
|
||||
case 6:
|
||||
EIMSK &= ~(1 << INT6);
|
||||
break;
|
||||
case 7:
|
||||
EIMSK &= ~(1 << INT7);
|
||||
break;
|
||||
#else
|
||||
case 0:
|
||||
#if defined(EIMSK) && defined(INT0)
|
||||
EIMSK &= ~(1 << INT0);
|
||||
#elif defined(GICR) && defined(ISC00)
|
||||
GICR &= ~(1 << INT0); // atmega32
|
||||
#elif defined(GIMSK) && defined(INT0)
|
||||
GIMSK &= ~(1 << INT0);
|
||||
#else
|
||||
#error detachInterrupt not finished for this cpu
|
||||
#endif
|
||||
break;
|
||||
|
||||
case 1:
|
||||
#if defined(EIMSK) && defined(INT1)
|
||||
EIMSK &= ~(1 << INT1);
|
||||
#elif defined(GICR) && defined(INT1)
|
||||
GICR &= ~(1 << INT1); // atmega32
|
||||
#elif defined(GIMSK) && defined(INT1)
|
||||
GIMSK &= ~(1 << INT1);
|
||||
#else
|
||||
#warning detachInterrupt may need some more work for this cpu (case 1)
|
||||
#endif
|
||||
break;
|
||||
#endif
|
||||
}
|
||||
|
||||
intFunc[interruptNum] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
void attachInterruptTwi(void (*userFunc)(void) ) {
|
||||
twiIntFunc = userFunc;
|
||||
}
|
||||
*/
|
||||
|
||||
#if defined(__AVR_ATmega32U4__)
|
||||
ISR(INT0_vect) {
|
||||
if(intFunc[EXTERNAL_INT_0])
|
||||
intFunc[EXTERNAL_INT_0]();
|
||||
}
|
||||
|
||||
ISR(INT1_vect) {
|
||||
if(intFunc[EXTERNAL_INT_1])
|
||||
intFunc[EXTERNAL_INT_1]();
|
||||
}
|
||||
|
||||
ISR(INT2_vect) {
|
||||
if(intFunc[EXTERNAL_INT_2])
|
||||
intFunc[EXTERNAL_INT_2]();
|
||||
}
|
||||
|
||||
ISR(INT3_vect) {
|
||||
if(intFunc[EXTERNAL_INT_3])
|
||||
intFunc[EXTERNAL_INT_3]();
|
||||
}
|
||||
|
||||
ISR(INT6_vect) {
|
||||
if(intFunc[EXTERNAL_INT_4])
|
||||
intFunc[EXTERNAL_INT_4]();
|
||||
}
|
||||
|
||||
#elif defined(EICRA) && defined(EICRB)
|
||||
|
||||
ISR(INT0_vect) {
|
||||
if(intFunc[EXTERNAL_INT_2])
|
||||
intFunc[EXTERNAL_INT_2]();
|
||||
}
|
||||
|
||||
ISR(INT1_vect) {
|
||||
if(intFunc[EXTERNAL_INT_3])
|
||||
intFunc[EXTERNAL_INT_3]();
|
||||
}
|
||||
|
||||
ISR(INT2_vect) {
|
||||
if(intFunc[EXTERNAL_INT_4])
|
||||
intFunc[EXTERNAL_INT_4]();
|
||||
}
|
||||
|
||||
ISR(INT3_vect) {
|
||||
if(intFunc[EXTERNAL_INT_5])
|
||||
intFunc[EXTERNAL_INT_5]();
|
||||
}
|
||||
|
||||
ISR(INT4_vect) {
|
||||
if(intFunc[EXTERNAL_INT_0])
|
||||
intFunc[EXTERNAL_INT_0]();
|
||||
}
|
||||
|
||||
ISR(INT5_vect) {
|
||||
if(intFunc[EXTERNAL_INT_1])
|
||||
intFunc[EXTERNAL_INT_1]();
|
||||
}
|
||||
|
||||
ISR(INT6_vect) {
|
||||
if(intFunc[EXTERNAL_INT_6])
|
||||
intFunc[EXTERNAL_INT_6]();
|
||||
}
|
||||
|
||||
ISR(INT7_vect) {
|
||||
if(intFunc[EXTERNAL_INT_7])
|
||||
intFunc[EXTERNAL_INT_7]();
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
ISR(INT0_vect) {
|
||||
if(intFunc[EXTERNAL_INT_0])
|
||||
intFunc[EXTERNAL_INT_0]();
|
||||
}
|
||||
|
||||
ISR(INT1_vect) {
|
||||
if(intFunc[EXTERNAL_INT_1])
|
||||
intFunc[EXTERNAL_INT_1]();
|
||||
}
|
||||
|
||||
#if defined(EICRA) && defined(ISC20)
|
||||
ISR(INT2_vect) {
|
||||
if(intFunc[EXTERNAL_INT_2])
|
||||
intFunc[EXTERNAL_INT_2]();
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
/*
|
||||
ISR(TWI_vect) {
|
||||
if(twiIntFunc)
|
||||
twiIntFunc();
|
||||
}
|
||||
*/
|
||||
|
@ -1,60 +0,0 @@
|
||||
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
|
||||
|
||||
/*
|
||||
Part of the Wiring project - http://wiring.org.co
|
||||
Copyright (c) 2004-06 Hernando Barragan
|
||||
Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General
|
||||
Public License along with this library; if not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
|
||||
Boston, MA 02111-1307 USA
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
extern "C" {
|
||||
#include "stdlib.h"
|
||||
}
|
||||
|
||||
void randomSeed(unsigned int seed)
|
||||
{
|
||||
if (seed != 0) {
|
||||
srandom(seed);
|
||||
}
|
||||
}
|
||||
|
||||
long random(long howbig)
|
||||
{
|
||||
if (howbig == 0) {
|
||||
return 0;
|
||||
}
|
||||
return random() % howbig;
|
||||
}
|
||||
|
||||
long random(long howsmall, long howbig)
|
||||
{
|
||||
if (howsmall >= howbig) {
|
||||
return howsmall;
|
||||
}
|
||||
long diff = howbig - howsmall;
|
||||
return random(diff) + howsmall;
|
||||
}
|
||||
|
||||
long map(long x, long in_min, long in_max, long out_min, long out_max)
|
||||
{
|
||||
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
|
||||
}
|
||||
|
||||
unsigned int makeWord(unsigned int w) { return w; }
|
||||
unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; }
|
@ -1,746 +0,0 @@
|
||||
/*
|
||||
WString.cpp - String library for Wiring & Arduino
|
||||
...mostly rewritten by Paul Stoffregen...
|
||||
Copyright (c) 2009-10 Hernando Barragan. All rights reserved.
|
||||
Copyright 2011, Paul Stoffregen, paul@pjrc.com
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#include "WString.h"
|
||||
|
||||
|
||||
/*********************************************/
|
||||
/* Constructors */
|
||||
/*********************************************/
|
||||
|
||||
String::String(const char *cstr)
|
||||
{
|
||||
init();
|
||||
if (cstr) copy(cstr, strlen(cstr));
|
||||
}
|
||||
|
||||
String::String(const String &value)
|
||||
{
|
||||
init();
|
||||
*this = value;
|
||||
}
|
||||
|
||||
String::String(const __FlashStringHelper *pstr)
|
||||
{
|
||||
init();
|
||||
*this = pstr;
|
||||
}
|
||||
|
||||
#ifdef __GXX_EXPERIMENTAL_CXX0X__
|
||||
String::String(String &&rval)
|
||||
{
|
||||
init();
|
||||
move(rval);
|
||||
}
|
||||
String::String(StringSumHelper &&rval)
|
||||
{
|
||||
init();
|
||||
move(rval);
|
||||
}
|
||||
#endif
|
||||
|
||||
String::String(char c)
|
||||
{
|
||||
init();
|
||||
char buf[2];
|
||||
buf[0] = c;
|
||||
buf[1] = 0;
|
||||
*this = buf;
|
||||
}
|
||||
|
||||
String::String(unsigned char value, unsigned char base)
|
||||
{
|
||||
init();
|
||||
char buf[9];
|
||||
utoa(value, buf, base);
|
||||
*this = buf;
|
||||
}
|
||||
|
||||
String::String(int value, unsigned char base)
|
||||
{
|
||||
init();
|
||||
char buf[18];
|
||||
itoa(value, buf, base);
|
||||
*this = buf;
|
||||
}
|
||||
|
||||
String::String(unsigned int value, unsigned char base)
|
||||
{
|
||||
init();
|
||||
char buf[17];
|
||||
utoa(value, buf, base);
|
||||
*this = buf;
|
||||
}
|
||||
|
||||
String::String(long value, unsigned char base)
|
||||
{
|
||||
init();
|
||||
char buf[34];
|
||||
ltoa(value, buf, base);
|
||||
*this = buf;
|
||||
}
|
||||
|
||||
String::String(unsigned long value, unsigned char base)
|
||||
{
|
||||
init();
|
||||
char buf[33];
|
||||
ultoa(value, buf, base);
|
||||
*this = buf;
|
||||
}
|
||||
|
||||
String::String(float value, int decimalPlaces)
|
||||
{
|
||||
init();
|
||||
char buf[33];
|
||||
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
|
||||
}
|
||||
|
||||
String::String(double value, int decimalPlaces)
|
||||
{
|
||||
init();
|
||||
char buf[33];
|
||||
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
|
||||
}
|
||||
|
||||
String::~String()
|
||||
{
|
||||
free(buffer);
|
||||
}
|
||||
|
||||
/*********************************************/
|
||||
/* Memory Management */
|
||||
/*********************************************/
|
||||
|
||||
inline void String::init(void)
|
||||
{
|
||||
buffer = NULL;
|
||||
capacity = 0;
|
||||
len = 0;
|
||||
flags = 0;
|
||||
}
|
||||
|
||||
void String::invalidate(void)
|
||||
{
|
||||
if (buffer) free(buffer);
|
||||
buffer = NULL;
|
||||
capacity = len = 0;
|
||||
}
|
||||
|
||||
unsigned char String::reserve(unsigned int size)
|
||||
{
|
||||
if (buffer && capacity >= size) return 1;
|
||||
if (changeBuffer(size)) {
|
||||
if (len == 0) buffer[0] = 0;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
unsigned char String::changeBuffer(unsigned int maxStrLen)
|
||||
{
|
||||
char *newbuffer = (char *)realloc(buffer, maxStrLen + 1);
|
||||
if (newbuffer) {
|
||||
buffer = newbuffer;
|
||||
capacity = maxStrLen;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*********************************************/
|
||||
/* Copy and Move */
|
||||
/*********************************************/
|
||||
|
||||
String & String::copy(const char *cstr, unsigned int length)
|
||||
{
|
||||
if (!reserve(length)) {
|
||||
invalidate();
|
||||
return *this;
|
||||
}
|
||||
len = length;
|
||||
strcpy(buffer, cstr);
|
||||
return *this;
|
||||
}
|
||||
|
||||
String & String::copy(const __FlashStringHelper *pstr, unsigned int length)
|
||||
{
|
||||
if (!reserve(length)) {
|
||||
invalidate();
|
||||
return *this;
|
||||
}
|
||||
len = length;
|
||||
strcpy_P(buffer, (const prog_char *)pstr);
|
||||
return *this;
|
||||
}
|
||||
|
||||
#ifdef __GXX_EXPERIMENTAL_CXX0X__
|
||||
void String::move(String &rhs)
|
||||
{
|
||||
if (buffer) {
|
||||
if (capacity >= rhs.len) {
|
||||
strcpy(buffer, rhs.buffer);
|
||||
len = rhs.len;
|
||||
rhs.len = 0;
|
||||
return;
|
||||
} else {
|
||||
free(buffer);
|
||||
}
|
||||
}
|
||||
buffer = rhs.buffer;
|
||||
capacity = rhs.capacity;
|
||||
len = rhs.len;
|
||||
rhs.buffer = NULL;
|
||||
rhs.capacity = 0;
|
||||
rhs.len = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
String & String::operator = (const String &rhs)
|
||||
{
|
||||
if (this == &rhs) return *this;
|
||||
|
||||
if (rhs.buffer) copy(rhs.buffer, rhs.len);
|
||||
else invalidate();
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
#ifdef __GXX_EXPERIMENTAL_CXX0X__
|
||||
String & String::operator = (String &&rval)
|
||||
{
|
||||
if (this != &rval) move(rval);
|
||||
return *this;
|
||||
}
|
||||
|
||||
String & String::operator = (StringSumHelper &&rval)
|
||||
{
|
||||
if (this != &rval) move(rval);
|
||||
return *this;
|
||||
}
|
||||
#endif
|
||||
|
||||
String & String::operator = (const char *cstr)
|
||||
{
|
||||
if (cstr) copy(cstr, strlen(cstr));
|
||||
else invalidate();
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
String & String::operator = (const __FlashStringHelper *pstr)
|
||||
{
|
||||
if (pstr) copy(pstr, strlen_P((const prog_char *)pstr));
|
||||
else invalidate();
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
/*********************************************/
|
||||
/* concat */
|
||||
/*********************************************/
|
||||
|
||||
unsigned char String::concat(const String &s)
|
||||
{
|
||||
return concat(s.buffer, s.len);
|
||||
}
|
||||
|
||||
unsigned char String::concat(const char *cstr, unsigned int length)
|
||||
{
|
||||
unsigned int newlen = len + length;
|
||||
if (!cstr) return 0;
|
||||
if (length == 0) return 1;
|
||||
if (!reserve(newlen)) return 0;
|
||||
strcpy(buffer + len, cstr);
|
||||
len = newlen;
|
||||
return 1;
|
||||
}
|
||||
|
||||
unsigned char String::concat(const char *cstr)
|
||||
{
|
||||
if (!cstr) return 0;
|
||||
return concat(cstr, strlen(cstr));
|
||||
}
|
||||
|
||||
unsigned char String::concat(char c)
|
||||
{
|
||||
char buf[2];
|
||||
buf[0] = c;
|
||||
buf[1] = 0;
|
||||
return concat(buf, 1);
|
||||
}
|
||||
|
||||
unsigned char String::concat(unsigned char num)
|
||||
{
|
||||
char buf[4];
|
||||
itoa(num, buf, 10);
|
||||
return concat(buf, strlen(buf));
|
||||
}
|
||||
|
||||
unsigned char String::concat(int num)
|
||||
{
|
||||
char buf[12];
|
||||
itoa(num, buf, 10);
|
||||
return concat(buf, strlen(buf));
|
||||
}
|
||||
|
||||
unsigned char String::concat(unsigned int num)
|
||||
{
|
||||
char buf[11];
|
||||
utoa(num, buf, 10);
|
||||
return concat(buf, strlen(buf));
|
||||
}
|
||||
|
||||
unsigned char String::concat(long num)
|
||||
{
|
||||
char buf[12];
|
||||
ltoa(num, buf, 10);
|
||||
return concat(buf, strlen(buf));
|
||||
}
|
||||
|
||||
unsigned char String::concat(unsigned long num)
|
||||
{
|
||||
char buf[11];
|
||||
ultoa(num, buf, 10);
|
||||
return concat(buf, strlen(buf));
|
||||
}
|
||||
|
||||
unsigned char String::concat(float num)
|
||||
{
|
||||
char buf[20];
|
||||
char* string = dtostrf(num, 4, 2, buf);
|
||||
return concat(string, strlen(string));
|
||||
}
|
||||
|
||||
unsigned char String::concat(double num)
|
||||
{
|
||||
char buf[20];
|
||||
char* string = dtostrf(num, 4, 2, buf);
|
||||
return concat(string, strlen(string));
|
||||
}
|
||||
|
||||
unsigned char String::concat(const __FlashStringHelper * str)
|
||||
{
|
||||
if (!str) return 0;
|
||||
int length = strlen_P((const char *) str);
|
||||
if (length == 0) return 1;
|
||||
unsigned int newlen = len + length;
|
||||
if (!reserve(newlen)) return 0;
|
||||
strcpy_P(buffer + len, (const char *) str);
|
||||
len = newlen;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*********************************************/
|
||||
/* Concatenate */
|
||||
/*********************************************/
|
||||
|
||||
StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs)
|
||||
{
|
||||
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
|
||||
if (!a.concat(rhs.buffer, rhs.len)) a.invalidate();
|
||||
return a;
|
||||
}
|
||||
|
||||
StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr)
|
||||
{
|
||||
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
|
||||
if (!cstr || !a.concat(cstr, strlen(cstr))) a.invalidate();
|
||||
return a;
|
||||
}
|
||||
|
||||
StringSumHelper & operator + (const StringSumHelper &lhs, char c)
|
||||
{
|
||||
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
|
||||
if (!a.concat(c)) a.invalidate();
|
||||
return a;
|
||||
}
|
||||
|
||||
StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num)
|
||||
{
|
||||
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
|
||||
if (!a.concat(num)) a.invalidate();
|
||||
return a;
|
||||
}
|
||||
|
||||
StringSumHelper & operator + (const StringSumHelper &lhs, int num)
|
||||
{
|
||||
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
|
||||
if (!a.concat(num)) a.invalidate();
|
||||
return a;
|
||||
}
|
||||
|
||||
StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num)
|
||||
{
|
||||
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
|
||||
if (!a.concat(num)) a.invalidate();
|
||||
return a;
|
||||
}
|
||||
|
||||
StringSumHelper & operator + (const StringSumHelper &lhs, long num)
|
||||
{
|
||||
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
|
||||
if (!a.concat(num)) a.invalidate();
|
||||
return a;
|
||||
}
|
||||
|
||||
StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num)
|
||||
{
|
||||
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
|
||||
if (!a.concat(num)) a.invalidate();
|
||||
return a;
|
||||
}
|
||||
|
||||
StringSumHelper & operator + (const StringSumHelper &lhs, float num)
|
||||
{
|
||||
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
|
||||
if (!a.concat(num)) a.invalidate();
|
||||
return a;
|
||||
}
|
||||
|
||||
StringSumHelper & operator + (const StringSumHelper &lhs, double num)
|
||||
{
|
||||
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
|
||||
if (!a.concat(num)) a.invalidate();
|
||||
return a;
|
||||
}
|
||||
|
||||
StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHelper *rhs)
|
||||
{
|
||||
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
|
||||
if (!a.concat(rhs)) a.invalidate();
|
||||
return a;
|
||||
}
|
||||
|
||||
/*********************************************/
|
||||
/* Comparison */
|
||||
/*********************************************/
|
||||
|
||||
int String::compareTo(const String &s) const
|
||||
{
|
||||
if (!buffer || !s.buffer) {
|
||||
if (s.buffer && s.len > 0) return 0 - *(unsigned char *)s.buffer;
|
||||
if (buffer && len > 0) return *(unsigned char *)buffer;
|
||||
return 0;
|
||||
}
|
||||
return strcmp(buffer, s.buffer);
|
||||
}
|
||||
|
||||
unsigned char String::equals(const String &s2) const
|
||||
{
|
||||
return (len == s2.len && compareTo(s2) == 0);
|
||||
}
|
||||
|
||||
unsigned char String::equals(const char *cstr) const
|
||||
{
|
||||
if (len == 0) return (cstr == NULL || *cstr == 0);
|
||||
if (cstr == NULL) return buffer[0] == 0;
|
||||
return strcmp(buffer, cstr) == 0;
|
||||
}
|
||||
|
||||
unsigned char String::operator<(const String &rhs) const
|
||||
{
|
||||
return compareTo(rhs) < 0;
|
||||
}
|
||||
|
||||
unsigned char String::operator>(const String &rhs) const
|
||||
{
|
||||
return compareTo(rhs) > 0;
|
||||
}
|
||||
|
||||
unsigned char String::operator<=(const String &rhs) const
|
||||
{
|
||||
return compareTo(rhs) <= 0;
|
||||
}
|
||||
|
||||
unsigned char String::operator>=(const String &rhs) const
|
||||
{
|
||||
return compareTo(rhs) >= 0;
|
||||
}
|
||||
|
||||
unsigned char String::equalsIgnoreCase( const String &s2 ) const
|
||||
{
|
||||
if (this == &s2) return 1;
|
||||
if (len != s2.len) return 0;
|
||||
if (len == 0) return 1;
|
||||
const char *p1 = buffer;
|
||||
const char *p2 = s2.buffer;
|
||||
while (*p1) {
|
||||
if (tolower(*p1++) != tolower(*p2++)) return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
unsigned char String::startsWith( const String &s2 ) const
|
||||
{
|
||||
if (len < s2.len) return 0;
|
||||
return startsWith(s2, 0);
|
||||
}
|
||||
|
||||
unsigned char String::startsWith( const String &s2, unsigned int offset ) const
|
||||
{
|
||||
if (offset > len - s2.len || !buffer || !s2.buffer) return 0;
|
||||
return strncmp( &buffer[offset], s2.buffer, s2.len ) == 0;
|
||||
}
|
||||
|
||||
unsigned char String::endsWith( const String &s2 ) const
|
||||
{
|
||||
if ( len < s2.len || !buffer || !s2.buffer) return 0;
|
||||
return strcmp(&buffer[len - s2.len], s2.buffer) == 0;
|
||||
}
|
||||
|
||||
/*********************************************/
|
||||
/* Character Access */
|
||||
/*********************************************/
|
||||
|
||||
char String::charAt(unsigned int loc) const
|
||||
{
|
||||
return operator[](loc);
|
||||
}
|
||||
|
||||
void String::setCharAt(unsigned int loc, char c)
|
||||
{
|
||||
if (loc < len) buffer[loc] = c;
|
||||
}
|
||||
|
||||
char & String::operator[](unsigned int index)
|
||||
{
|
||||
static char dummy_writable_char;
|
||||
if (index >= len || !buffer) {
|
||||
dummy_writable_char = 0;
|
||||
return dummy_writable_char;
|
||||
}
|
||||
return buffer[index];
|
||||
}
|
||||
|
||||
char String::operator[]( unsigned int index ) const
|
||||
{
|
||||
if (index >= len || !buffer) return 0;
|
||||
return buffer[index];
|
||||
}
|
||||
|
||||
void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const
|
||||
{
|
||||
if (!bufsize || !buf) return;
|
||||
if (index >= len) {
|
||||
buf[0] = 0;
|
||||
return;
|
||||
}
|
||||
unsigned int n = bufsize - 1;
|
||||
if (n > len - index) n = len - index;
|
||||
strncpy((char *)buf, buffer + index, n);
|
||||
buf[n] = 0;
|
||||
}
|
||||
|
||||
/*********************************************/
|
||||
/* Search */
|
||||
/*********************************************/
|
||||
|
||||
int String::indexOf(char c) const
|
||||
{
|
||||
return indexOf(c, 0);
|
||||
}
|
||||
|
||||
int String::indexOf( char ch, unsigned int fromIndex ) const
|
||||
{
|
||||
if (fromIndex >= len) return -1;
|
||||
const char* temp = strchr(buffer + fromIndex, ch);
|
||||
if (temp == NULL) return -1;
|
||||
return temp - buffer;
|
||||
}
|
||||
|
||||
int String::indexOf(const String &s2) const
|
||||
{
|
||||
return indexOf(s2, 0);
|
||||
}
|
||||
|
||||
int String::indexOf(const String &s2, unsigned int fromIndex) const
|
||||
{
|
||||
if (fromIndex >= len) return -1;
|
||||
const char *found = strstr(buffer + fromIndex, s2.buffer);
|
||||
if (found == NULL) return -1;
|
||||
return found - buffer;
|
||||
}
|
||||
|
||||
int String::lastIndexOf( char theChar ) const
|
||||
{
|
||||
return lastIndexOf(theChar, len - 1);
|
||||
}
|
||||
|
||||
int String::lastIndexOf(char ch, unsigned int fromIndex) const
|
||||
{
|
||||
if (fromIndex >= len) return -1;
|
||||
char tempchar = buffer[fromIndex + 1];
|
||||
buffer[fromIndex + 1] = '\0';
|
||||
char* temp = strrchr( buffer, ch );
|
||||
buffer[fromIndex + 1] = tempchar;
|
||||
if (temp == NULL) return -1;
|
||||
return temp - buffer;
|
||||
}
|
||||
|
||||
int String::lastIndexOf(const String &s2) const
|
||||
{
|
||||
return lastIndexOf(s2, len - s2.len);
|
||||
}
|
||||
|
||||
int String::lastIndexOf(const String &s2, unsigned int fromIndex) const
|
||||
{
|
||||
if (s2.len == 0 || len == 0 || s2.len > len) return -1;
|
||||
if (fromIndex >= len) fromIndex = len - 1;
|
||||
int found = -1;
|
||||
for (char *p = buffer; p <= buffer + fromIndex; p++) {
|
||||
p = strstr(p, s2.buffer);
|
||||
if (!p) break;
|
||||
if ((unsigned int)(p - buffer) <= fromIndex) found = p - buffer;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
String String::substring(unsigned int left, unsigned int right) const
|
||||
{
|
||||
if (left > right) {
|
||||
unsigned int temp = right;
|
||||
right = left;
|
||||
left = temp;
|
||||
}
|
||||
String out;
|
||||
if (left > len) return out;
|
||||
if (right > len) right = len;
|
||||
char temp = buffer[right]; // save the replaced character
|
||||
buffer[right] = '\0';
|
||||
out = buffer + left; // pointer arithmetic
|
||||
buffer[right] = temp; //restore character
|
||||
return out;
|
||||
}
|
||||
|
||||
/*********************************************/
|
||||
/* Modification */
|
||||
/*********************************************/
|
||||
|
||||
void String::replace(char find, char replace)
|
||||
{
|
||||
if (!buffer) return;
|
||||
for (char *p = buffer; *p; p++) {
|
||||
if (*p == find) *p = replace;
|
||||
}
|
||||
}
|
||||
|
||||
void String::replace(const String& find, const String& replace)
|
||||
{
|
||||
if (len == 0 || find.len == 0) return;
|
||||
int diff = replace.len - find.len;
|
||||
char *readFrom = buffer;
|
||||
char *foundAt;
|
||||
if (diff == 0) {
|
||||
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
|
||||
memcpy(foundAt, replace.buffer, replace.len);
|
||||
readFrom = foundAt + replace.len;
|
||||
}
|
||||
} else if (diff < 0) {
|
||||
char *writeTo = buffer;
|
||||
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
|
||||
unsigned int n = foundAt - readFrom;
|
||||
memcpy(writeTo, readFrom, n);
|
||||
writeTo += n;
|
||||
memcpy(writeTo, replace.buffer, replace.len);
|
||||
writeTo += replace.len;
|
||||
readFrom = foundAt + find.len;
|
||||
len += diff;
|
||||
}
|
||||
strcpy(writeTo, readFrom);
|
||||
} else {
|
||||
unsigned int size = len; // compute size needed for result
|
||||
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
|
||||
readFrom = foundAt + find.len;
|
||||
size += diff;
|
||||
}
|
||||
if (size == len) return;
|
||||
if (size > capacity && !changeBuffer(size)) return; // XXX: tell user!
|
||||
int index = len - 1;
|
||||
while (index >= 0 && (index = lastIndexOf(find, index)) >= 0) {
|
||||
readFrom = buffer + index + find.len;
|
||||
memmove(readFrom + diff, readFrom, len - (readFrom - buffer));
|
||||
len += diff;
|
||||
buffer[len] = 0;
|
||||
memcpy(buffer + index, replace.buffer, replace.len);
|
||||
index--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void String::remove(unsigned int index){
|
||||
if (index >= len) { return; }
|
||||
int count = len - index;
|
||||
remove(index, count);
|
||||
}
|
||||
|
||||
void String::remove(unsigned int index, unsigned int count){
|
||||
if (index >= len) { return; }
|
||||
if (count <= 0) { return; }
|
||||
if (index + count > len) { count = len - index; }
|
||||
char *writeTo = buffer + index;
|
||||
len = len - count;
|
||||
strncpy(writeTo, buffer + index + count,len - index);
|
||||
buffer[len] = 0;
|
||||
}
|
||||
|
||||
void String::toLowerCase(void)
|
||||
{
|
||||
if (!buffer) return;
|
||||
for (char *p = buffer; *p; p++) {
|
||||
*p = tolower(*p);
|
||||
}
|
||||
}
|
||||
|
||||
void String::toUpperCase(void)
|
||||
{
|
||||
if (!buffer) return;
|
||||
for (char *p = buffer; *p; p++) {
|
||||
*p = toupper(*p);
|
||||
}
|
||||
}
|
||||
|
||||
void String::trim(void)
|
||||
{
|
||||
if (!buffer || len == 0) return;
|
||||
char *begin = buffer;
|
||||
while (isspace(*begin)) begin++;
|
||||
char *end = buffer + len - 1;
|
||||
while (isspace(*end) && end >= begin) end--;
|
||||
len = end + 1 - begin;
|
||||
if (begin > buffer) memcpy(buffer, begin, len);
|
||||
buffer[len] = 0;
|
||||
}
|
||||
|
||||
/*********************************************/
|
||||
/* Parsing / Conversion */
|
||||
/*********************************************/
|
||||
|
||||
long String::toInt(void) const
|
||||
{
|
||||
if (buffer) return atol(buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
float String::toFloat(void) const
|
||||
{
|
||||
if (buffer) return float(atof(buffer));
|
||||
return 0;
|
||||
}
|
@ -1,225 +0,0 @@
|
||||
/*
|
||||
WString.h - String library for Wiring & Arduino
|
||||
...mostly rewritten by Paul Stoffregen...
|
||||
Copyright (c) 2009-10 Hernando Barragan. All right reserved.
|
||||
Copyright 2011, Paul Stoffregen, paul@pjrc.com
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#ifndef String_class_h
|
||||
#define String_class_h
|
||||
#ifdef __cplusplus
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ctype.h>
|
||||
#include <avr/pgmspace.h>
|
||||
|
||||
// When compiling programs with this class, the following gcc parameters
|
||||
// dramatically increase performance and memory (RAM) efficiency, typically
|
||||
// with little or no increase in code size.
|
||||
// -felide-constructors
|
||||
// -std=c++0x
|
||||
|
||||
class __FlashStringHelper;
|
||||
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))
|
||||
|
||||
// An inherited class for holding the result of a concatenation. These
|
||||
// result objects are assumed to be writable by subsequent concatenations.
|
||||
class StringSumHelper;
|
||||
|
||||
// The string class
|
||||
class String
|
||||
{
|
||||
// use a function pointer to allow for "if (s)" without the
|
||||
// complications of an operator bool(). for more information, see:
|
||||
// http://www.artima.com/cppsource/safebool.html
|
||||
typedef void (String::*StringIfHelperType)() const;
|
||||
void StringIfHelper() const {}
|
||||
|
||||
public:
|
||||
// constructors
|
||||
// creates a copy of the initial value.
|
||||
// if the initial value is null or invalid, or if memory allocation
|
||||
// fails, the string will be marked as invalid (i.e. "if (s)" will
|
||||
// be false).
|
||||
String(const char *cstr = "");
|
||||
String(const String &str);
|
||||
String(const __FlashStringHelper *str);
|
||||
#ifdef __GXX_EXPERIMENTAL_CXX0X__
|
||||
String(String &&rval);
|
||||
String(StringSumHelper &&rval);
|
||||
#endif
|
||||
explicit String(char c);
|
||||
explicit String(unsigned char, unsigned char base=10);
|
||||
explicit String(int, unsigned char base=10);
|
||||
explicit String(unsigned int, unsigned char base=10);
|
||||
explicit String(long, unsigned char base=10);
|
||||
explicit String(unsigned long, unsigned char base=10);
|
||||
explicit String(float, int decimalPlaces=2);
|
||||
explicit String(double, int decimalPlaces=2);
|
||||
~String(void);
|
||||
|
||||
// memory management
|
||||
// return true on success, false on failure (in which case, the string
|
||||
// is left unchanged). reserve(0), if successful, will validate an
|
||||
// invalid string (i.e., "if (s)" will be true afterwards)
|
||||
unsigned char reserve(unsigned int size);
|
||||
inline unsigned int length(void) const {return len;}
|
||||
|
||||
// creates a copy of the assigned value. if the value is null or
|
||||
// invalid, or if the memory allocation fails, the string will be
|
||||
// marked as invalid ("if (s)" will be false).
|
||||
String & operator = (const String &rhs);
|
||||
String & operator = (const char *cstr);
|
||||
String & operator = (const __FlashStringHelper *str);
|
||||
#ifdef __GXX_EXPERIMENTAL_CXX0X__
|
||||
String & operator = (String &&rval);
|
||||
String & operator = (StringSumHelper &&rval);
|
||||
#endif
|
||||
|
||||
// concatenate (works w/ built-in types)
|
||||
|
||||
// returns true on success, false on failure (in which case, the string
|
||||
// is left unchanged). if the argument is null or invalid, the
|
||||
// concatenation is considered unsucessful.
|
||||
unsigned char concat(const String &str);
|
||||
unsigned char concat(const char *cstr);
|
||||
unsigned char concat(char c);
|
||||
unsigned char concat(unsigned char c);
|
||||
unsigned char concat(int num);
|
||||
unsigned char concat(unsigned int num);
|
||||
unsigned char concat(long num);
|
||||
unsigned char concat(unsigned long num);
|
||||
unsigned char concat(float num);
|
||||
unsigned char concat(double num);
|
||||
unsigned char concat(const __FlashStringHelper * str);
|
||||
|
||||
// if there's not enough memory for the concatenated value, the string
|
||||
// will be left unchanged (but this isn't signalled in any way)
|
||||
String & operator += (const String &rhs) {concat(rhs); return (*this);}
|
||||
String & operator += (const char *cstr) {concat(cstr); return (*this);}
|
||||
String & operator += (char c) {concat(c); return (*this);}
|
||||
String & operator += (unsigned char num) {concat(num); return (*this);}
|
||||
String & operator += (int num) {concat(num); return (*this);}
|
||||
String & operator += (unsigned int num) {concat(num); return (*this);}
|
||||
String & operator += (long num) {concat(num); return (*this);}
|
||||
String & operator += (unsigned long num) {concat(num); return (*this);}
|
||||
String & operator += (float num) {concat(num); return (*this);}
|
||||
String & operator += (double num) {concat(num); return (*this);}
|
||||
String & operator += (const __FlashStringHelper *str){concat(str); return (*this);}
|
||||
|
||||
friend StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs);
|
||||
friend StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr);
|
||||
friend StringSumHelper & operator + (const StringSumHelper &lhs, char c);
|
||||
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num);
|
||||
friend StringSumHelper & operator + (const StringSumHelper &lhs, int num);
|
||||
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num);
|
||||
friend StringSumHelper & operator + (const StringSumHelper &lhs, long num);
|
||||
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num);
|
||||
friend StringSumHelper & operator + (const StringSumHelper &lhs, float num);
|
||||
friend StringSumHelper & operator + (const StringSumHelper &lhs, double num);
|
||||
friend StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHelper *rhs);
|
||||
|
||||
// comparison (only works w/ Strings and "strings")
|
||||
operator StringIfHelperType() const { return buffer ? &String::StringIfHelper : 0; }
|
||||
int compareTo(const String &s) const;
|
||||
unsigned char equals(const String &s) const;
|
||||
unsigned char equals(const char *cstr) const;
|
||||
unsigned char operator == (const String &rhs) const {return equals(rhs);}
|
||||
unsigned char operator == (const char *cstr) const {return equals(cstr);}
|
||||
unsigned char operator != (const String &rhs) const {return !equals(rhs);}
|
||||
unsigned char operator != (const char *cstr) const {return !equals(cstr);}
|
||||
unsigned char operator < (const String &rhs) const;
|
||||
unsigned char operator > (const String &rhs) const;
|
||||
unsigned char operator <= (const String &rhs) const;
|
||||
unsigned char operator >= (const String &rhs) const;
|
||||
unsigned char equalsIgnoreCase(const String &s) const;
|
||||
unsigned char startsWith( const String &prefix) const;
|
||||
unsigned char startsWith(const String &prefix, unsigned int offset) const;
|
||||
unsigned char endsWith(const String &suffix) const;
|
||||
|
||||
// character acccess
|
||||
char charAt(unsigned int index) const;
|
||||
void setCharAt(unsigned int index, char c);
|
||||
char operator [] (unsigned int index) const;
|
||||
char& operator [] (unsigned int index);
|
||||
void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const;
|
||||
void toCharArray(char *buf, unsigned int bufsize, unsigned int index=0) const
|
||||
{getBytes((unsigned char *)buf, bufsize, index);}
|
||||
const char * c_str() const { return buffer; }
|
||||
|
||||
// search
|
||||
int indexOf( char ch ) const;
|
||||
int indexOf( char ch, unsigned int fromIndex ) const;
|
||||
int indexOf( const String &str ) const;
|
||||
int indexOf( const String &str, unsigned int fromIndex ) const;
|
||||
int lastIndexOf( char ch ) const;
|
||||
int lastIndexOf( char ch, unsigned int fromIndex ) const;
|
||||
int lastIndexOf( const String &str ) const;
|
||||
int lastIndexOf( const String &str, unsigned int fromIndex ) const;
|
||||
String substring( unsigned int beginIndex ) const { return substring(beginIndex, len); };
|
||||
String substring( unsigned int beginIndex, unsigned int endIndex ) const;
|
||||
|
||||
// modification
|
||||
void replace(char find, char replace);
|
||||
void replace(const String& find, const String& replace);
|
||||
void remove(unsigned int index);
|
||||
void remove(unsigned int index, unsigned int count);
|
||||
void toLowerCase(void);
|
||||
void toUpperCase(void);
|
||||
void trim(void);
|
||||
|
||||
// parsing/conversion
|
||||
long toInt(void) const;
|
||||
float toFloat(void) const;
|
||||
|
||||
protected:
|
||||
char *buffer; // the actual char array
|
||||
unsigned int capacity; // the array length minus one (for the '\0')
|
||||
unsigned int len; // the String length (not counting the '\0')
|
||||
unsigned char flags; // unused, for future features
|
||||
protected:
|
||||
void init(void);
|
||||
void invalidate(void);
|
||||
unsigned char changeBuffer(unsigned int maxStrLen);
|
||||
unsigned char concat(const char *cstr, unsigned int length);
|
||||
|
||||
// copy and move
|
||||
String & copy(const char *cstr, unsigned int length);
|
||||
String & copy(const __FlashStringHelper *pstr, unsigned int length);
|
||||
#ifdef __GXX_EXPERIMENTAL_CXX0X__
|
||||
void move(String &rhs);
|
||||
#endif
|
||||
};
|
||||
|
||||
class StringSumHelper : public String
|
||||
{
|
||||
public:
|
||||
StringSumHelper(const String &s) : String(s) {}
|
||||
StringSumHelper(const char *p) : String(p) {}
|
||||
StringSumHelper(char c) : String(c) {}
|
||||
StringSumHelper(unsigned char num) : String(num) {}
|
||||
StringSumHelper(int num) : String(num) {}
|
||||
StringSumHelper(unsigned int num) : String(num) {}
|
||||
StringSumHelper(long num) : String(num) {}
|
||||
StringSumHelper(unsigned long num) : String(num) {}
|
||||
StringSumHelper(float num) : String(num) {}
|
||||
StringSumHelper(double num) : String(num) {}
|
||||
};
|
||||
|
||||
#endif // __cplusplus
|
||||
#endif // String_class_h
|
@ -1,515 +0,0 @@
|
||||
#ifndef Binary_h
|
||||
#define Binary_h
|
||||
|
||||
#define B0 0
|
||||
#define B00 0
|
||||
#define B000 0
|
||||
#define B0000 0
|
||||
#define B00000 0
|
||||
#define B000000 0
|
||||
#define B0000000 0
|
||||
#define B00000000 0
|
||||
#define B1 1
|
||||
#define B01 1
|
||||
#define B001 1
|
||||
#define B0001 1
|
||||
#define B00001 1
|
||||
#define B000001 1
|
||||
#define B0000001 1
|
||||
#define B00000001 1
|
||||
#define B10 2
|
||||
#define B010 2
|
||||
#define B0010 2
|
||||
#define B00010 2
|
||||
#define B000010 2
|
||||
#define B0000010 2
|
||||
#define B00000010 2
|
||||
#define B11 3
|
||||
#define B011 3
|
||||
#define B0011 3
|
||||
#define B00011 3
|
||||
#define B000011 3
|
||||
#define B0000011 3
|
||||
#define B00000011 3
|
||||
#define B100 4
|
||||
#define B0100 4
|
||||
#define B00100 4
|
||||
#define B000100 4
|
||||
#define B0000100 4
|
||||
#define B00000100 4
|
||||
#define B101 5
|
||||
#define B0101 5
|
||||
#define B00101 5
|
||||
#define B000101 5
|
||||
#define B0000101 5
|
||||
#define B00000101 5
|
||||
#define B110 6
|
||||
#define B0110 6
|
||||
#define B00110 6
|
||||
#define B000110 6
|
||||
#define B0000110 6
|
||||
#define B00000110 6
|
||||
#define B111 7
|
||||
#define B0111 7
|
||||
#define B00111 7
|
||||
#define B000111 7
|
||||
#define B0000111 7
|
||||
#define B00000111 7
|
||||
#define B1000 8
|
||||
#define B01000 8
|
||||
#define B001000 8
|
||||
#define B0001000 8
|
||||
#define B00001000 8
|
||||
#define B1001 9
|
||||
#define B01001 9
|
||||
#define B001001 9
|
||||
#define B0001001 9
|
||||
#define B00001001 9
|
||||
#define B1010 10
|
||||
#define B01010 10
|
||||
#define B001010 10
|
||||
#define B0001010 10
|
||||
#define B00001010 10
|
||||
#define B1011 11
|
||||
#define B01011 11
|
||||
#define B001011 11
|
||||
#define B0001011 11
|
||||
#define B00001011 11
|
||||
#define B1100 12
|
||||
#define B01100 12
|
||||
#define B001100 12
|
||||
#define B0001100 12
|
||||
#define B00001100 12
|
||||
#define B1101 13
|
||||
#define B01101 13
|
||||
#define B001101 13
|
||||
#define B0001101 13
|
||||
#define B00001101 13
|
||||
#define B1110 14
|
||||
#define B01110 14
|
||||
#define B001110 14
|
||||
#define B0001110 14
|
||||
#define B00001110 14
|
||||
#define B1111 15
|
||||
#define B01111 15
|
||||
#define B001111 15
|
||||
#define B0001111 15
|
||||
#define B00001111 15
|
||||
#define B10000 16
|
||||
#define B010000 16
|
||||
#define B0010000 16
|
||||
#define B00010000 16
|
||||
#define B10001 17
|
||||
#define B010001 17
|
||||
#define B0010001 17
|
||||
#define B00010001 17
|
||||
#define B10010 18
|
||||
#define B010010 18
|
||||
#define B0010010 18
|
||||
#define B00010010 18
|
||||
#define B10011 19
|
||||
#define B010011 19
|
||||
#define B0010011 19
|
||||
#define B00010011 19
|
||||
#define B10100 20
|
||||
#define B010100 20
|
||||
#define B0010100 20
|
||||
#define B00010100 20
|
||||
#define B10101 21
|
||||
#define B010101 21
|
||||
#define B0010101 21
|
||||
#define B00010101 21
|
||||
#define B10110 22
|
||||
#define B010110 22
|
||||
#define B0010110 22
|
||||
#define B00010110 22
|
||||
#define B10111 23
|
||||
#define B010111 23
|
||||
#define B0010111 23
|
||||
#define B00010111 23
|
||||
#define B11000 24
|
||||
#define B011000 24
|
||||
#define B0011000 24
|
||||
#define B00011000 24
|
||||
#define B11001 25
|
||||
#define B011001 25
|
||||
#define B0011001 25
|
||||
#define B00011001 25
|
||||
#define B11010 26
|
||||
#define B011010 26
|
||||
#define B0011010 26
|
||||
#define B00011010 26
|
||||
#define B11011 27
|
||||
#define B011011 27
|
||||
#define B0011011 27
|
||||
#define B00011011 27
|
||||
#define B11100 28
|
||||
#define B011100 28
|
||||
#define B0011100 28
|
||||
#define B00011100 28
|
||||
#define B11101 29
|
||||
#define B011101 29
|
||||
#define B0011101 29
|
||||
#define B00011101 29
|
||||
#define B11110 30
|
||||
#define B011110 30
|
||||
#define B0011110 30
|
||||
#define B00011110 30
|
||||
#define B11111 31
|
||||
#define B011111 31
|
||||
#define B0011111 31
|
||||
#define B00011111 31
|
||||
#define B100000 32
|
||||
#define B0100000 32
|
||||
#define B00100000 32
|
||||
#define B100001 33
|
||||
#define B0100001 33
|
||||
#define B00100001 33
|
||||
#define B100010 34
|
||||
#define B0100010 34
|
||||
#define B00100010 34
|
||||
#define B100011 35
|
||||
#define B0100011 35
|
||||
#define B00100011 35
|
||||
#define B100100 36
|
||||
#define B0100100 36
|
||||
#define B00100100 36
|
||||
#define B100101 37
|
||||
#define B0100101 37
|
||||
#define B00100101 37
|
||||
#define B100110 38
|
||||
#define B0100110 38
|
||||
#define B00100110 38
|
||||
#define B100111 39
|
||||
#define B0100111 39
|
||||
#define B00100111 39
|
||||
#define B101000 40
|
||||
#define B0101000 40
|
||||
#define B00101000 40
|
||||
#define B101001 41
|
||||
#define B0101001 41
|
||||
#define B00101001 41
|
||||
#define B101010 42
|
||||
#define B0101010 42
|
||||
#define B00101010 42
|
||||
#define B101011 43
|
||||
#define B0101011 43
|
||||
#define B00101011 43
|
||||
#define B101100 44
|
||||
#define B0101100 44
|
||||
#define B00101100 44
|
||||
#define B101101 45
|
||||
#define B0101101 45
|
||||
#define B00101101 45
|
||||
#define B101110 46
|
||||
#define B0101110 46
|
||||
#define B00101110 46
|
||||
#define B101111 47
|
||||
#define B0101111 47
|
||||
#define B00101111 47
|
||||
#define B110000 48
|
||||
#define B0110000 48
|
||||
#define B00110000 48
|
||||
#define B110001 49
|
||||
#define B0110001 49
|
||||
#define B00110001 49
|
||||
#define B110010 50
|
||||
#define B0110010 50
|
||||
#define B00110010 50
|
||||
#define B110011 51
|
||||
#define B0110011 51
|
||||
#define B00110011 51
|
||||
#define B110100 52
|
||||
#define B0110100 52
|
||||
#define B00110100 52
|
||||
#define B110101 53
|
||||
#define B0110101 53
|
||||
#define B00110101 53
|
||||
#define B110110 54
|
||||
#define B0110110 54
|
||||
#define B00110110 54
|
||||
#define B110111 55
|
||||
#define B0110111 55
|
||||
#define B00110111 55
|
||||
#define B111000 56
|
||||
#define B0111000 56
|
||||
#define B00111000 56
|
||||
#define B111001 57
|
||||
#define B0111001 57
|
||||
#define B00111001 57
|
||||
#define B111010 58
|
||||
#define B0111010 58
|
||||
#define B00111010 58
|
||||
#define B111011 59
|
||||
#define B0111011 59
|
||||
#define B00111011 59
|
||||
#define B111100 60
|
||||
#define B0111100 60
|
||||
#define B00111100 60
|
||||
#define B111101 61
|
||||
#define B0111101 61
|
||||
#define B00111101 61
|
||||
#define B111110 62
|
||||
#define B0111110 62
|
||||
#define B00111110 62
|
||||
#define B111111 63
|
||||
#define B0111111 63
|
||||
#define B00111111 63
|
||||
#define B1000000 64
|
||||
#define B01000000 64
|
||||
#define B1000001 65
|
||||
#define B01000001 65
|
||||
#define B1000010 66
|
||||
#define B01000010 66
|
||||
#define B1000011 67
|
||||
#define B01000011 67
|
||||
#define B1000100 68
|
||||
#define B01000100 68
|
||||
#define B1000101 69
|
||||
#define B01000101 69
|
||||
#define B1000110 70
|
||||
#define B01000110 70
|
||||
#define B1000111 71
|
||||
#define B01000111 71
|
||||
#define B1001000 72
|
||||
#define B01001000 72
|
||||
#define B1001001 73
|
||||
#define B01001001 73
|
||||
#define B1001010 74
|
||||
#define B01001010 74
|
||||
#define B1001011 75
|
||||
#define B01001011 75
|
||||
#define B1001100 76
|
||||
#define B01001100 76
|
||||
#define B1001101 77
|
||||
#define B01001101 77
|
||||
#define B1001110 78
|
||||
#define B01001110 78
|
||||
#define B1001111 79
|
||||
#define B01001111 79
|
||||
#define B1010000 80
|
||||
#define B01010000 80
|
||||
#define B1010001 81
|
||||
#define B01010001 81
|
||||
#define B1010010 82
|
||||
#define B01010010 82
|
||||
#define B1010011 83
|
||||
#define B01010011 83
|
||||
#define B1010100 84
|
||||
#define B01010100 84
|
||||
#define B1010101 85
|
||||
#define B01010101 85
|
||||
#define B1010110 86
|
||||
#define B01010110 86
|
||||
#define B1010111 87
|
||||
#define B01010111 87
|
||||
#define B1011000 88
|
||||
#define B01011000 88
|
||||
#define B1011001 89
|
||||
#define B01011001 89
|
||||
#define B1011010 90
|
||||
#define B01011010 90
|
||||
#define B1011011 91
|
||||
#define B01011011 91
|
||||
#define B1011100 92
|
||||
#define B01011100 92
|
||||
#define B1011101 93
|
||||
#define B01011101 93
|
||||
#define B1011110 94
|
||||
#define B01011110 94
|
||||
#define B1011111 95
|
||||
#define B01011111 95
|
||||
#define B1100000 96
|
||||
#define B01100000 96
|
||||
#define B1100001 97
|
||||
#define B01100001 97
|
||||
#define B1100010 98
|
||||
#define B01100010 98
|
||||
#define B1100011 99
|
||||
#define B01100011 99
|
||||
#define B1100100 100
|
||||
#define B01100100 100
|
||||
#define B1100101 101
|
||||
#define B01100101 101
|
||||
#define B1100110 102
|
||||
#define B01100110 102
|
||||
#define B1100111 103
|
||||
#define B01100111 103
|
||||
#define B1101000 104
|
||||
#define B01101000 104
|
||||
#define B1101001 105
|
||||
#define B01101001 105
|
||||
#define B1101010 106
|
||||
#define B01101010 106
|
||||
#define B1101011 107
|
||||
#define B01101011 107
|
||||
#define B1101100 108
|
||||
#define B01101100 108
|
||||
#define B1101101 109
|
||||
#define B01101101 109
|
||||
#define B1101110 110
|
||||
#define B01101110 110
|
||||
#define B1101111 111
|
||||
#define B01101111 111
|
||||
#define B1110000 112
|
||||
#define B01110000 112
|
||||
#define B1110001 113
|
||||
#define B01110001 113
|
||||
#define B1110010 114
|
||||
#define B01110010 114
|
||||
#define B1110011 115
|
||||
#define B01110011 115
|
||||
#define B1110100 116
|
||||
#define B01110100 116
|
||||
#define B1110101 117
|
||||
#define B01110101 117
|
||||
#define B1110110 118
|
||||
#define B01110110 118
|
||||
#define B1110111 119
|
||||
#define B01110111 119
|
||||
#define B1111000 120
|
||||
#define B01111000 120
|
||||
#define B1111001 121
|
||||
#define B01111001 121
|
||||
#define B1111010 122
|
||||
#define B01111010 122
|
||||
#define B1111011 123
|
||||
#define B01111011 123
|
||||
#define B1111100 124
|
||||
#define B01111100 124
|
||||
#define B1111101 125
|
||||
#define B01111101 125
|
||||
#define B1111110 126
|
||||
#define B01111110 126
|
||||
#define B1111111 127
|
||||
#define B01111111 127
|
||||
#define B10000000 128
|
||||
#define B10000001 129
|
||||
#define B10000010 130
|
||||
#define B10000011 131
|
||||
#define B10000100 132
|
||||
#define B10000101 133
|
||||
#define B10000110 134
|
||||
#define B10000111 135
|
||||
#define B10001000 136
|
||||
#define B10001001 137
|
||||
#define B10001010 138
|
||||
#define B10001011 139
|
||||
#define B10001100 140
|
||||
#define B10001101 141
|
||||
#define B10001110 142
|
||||
#define B10001111 143
|
||||
#define B10010000 144
|
||||
#define B10010001 145
|
||||
#define B10010010 146
|
||||
#define B10010011 147
|
||||
#define B10010100 148
|
||||
#define B10010101 149
|
||||
#define B10010110 150
|
||||
#define B10010111 151
|
||||
#define B10011000 152
|
||||
#define B10011001 153
|
||||
#define B10011010 154
|
||||
#define B10011011 155
|
||||
#define B10011100 156
|
||||
#define B10011101 157
|
||||
#define B10011110 158
|
||||
#define B10011111 159
|
||||
#define B10100000 160
|
||||
#define B10100001 161
|
||||
#define B10100010 162
|
||||
#define B10100011 163
|
||||
#define B10100100 164
|
||||
#define B10100101 165
|
||||
#define B10100110 166
|
||||
#define B10100111 167
|
||||
#define B10101000 168
|
||||
#define B10101001 169
|
||||
#define B10101010 170
|
||||
#define B10101011 171
|
||||
#define B10101100 172
|
||||
#define B10101101 173
|
||||
#define B10101110 174
|
||||
#define B10101111 175
|
||||
#define B10110000 176
|
||||
#define B10110001 177
|
||||
#define B10110010 178
|
||||
#define B10110011 179
|
||||
#define B10110100 180
|
||||
#define B10110101 181
|
||||
#define B10110110 182
|
||||
#define B10110111 183
|
||||
#define B10111000 184
|
||||
#define B10111001 185
|
||||
#define B10111010 186
|
||||
#define B10111011 187
|
||||
#define B10111100 188
|
||||
#define B10111101 189
|
||||
#define B10111110 190
|
||||
#define B10111111 191
|
||||
#define B11000000 192
|
||||
#define B11000001 193
|
||||
#define B11000010 194
|
||||
#define B11000011 195
|
||||
#define B11000100 196
|
||||
#define B11000101 197
|
||||
#define B11000110 198
|
||||
#define B11000111 199
|
||||
#define B11001000 200
|
||||
#define B11001001 201
|
||||
#define B11001010 202
|
||||
#define B11001011 203
|
||||
#define B11001100 204
|
||||
#define B11001101 205
|
||||
#define B11001110 206
|
||||
#define B11001111 207
|
||||
#define B11010000 208
|
||||
#define B11010001 209
|
||||
#define B11010010 210
|
||||
#define B11010011 211
|
||||
#define B11010100 212
|
||||
#define B11010101 213
|
||||
#define B11010110 214
|
||||
#define B11010111 215
|
||||
#define B11011000 216
|
||||
#define B11011001 217
|
||||
#define B11011010 218
|
||||
#define B11011011 219
|
||||
#define B11011100 220
|
||||
#define B11011101 221
|
||||
#define B11011110 222
|
||||
#define B11011111 223
|
||||
#define B11100000 224
|
||||
#define B11100001 225
|
||||
#define B11100010 226
|
||||
#define B11100011 227
|
||||
#define B11100100 228
|
||||
#define B11100101 229
|
||||
#define B11100110 230
|
||||
#define B11100111 231
|
||||
#define B11101000 232
|
||||
#define B11101001 233
|
||||
#define B11101010 234
|
||||
#define B11101011 235
|
||||
#define B11101100 236
|
||||
#define B11101101 237
|
||||
#define B11101110 238
|
||||
#define B11101111 239
|
||||
#define B11110000 240
|
||||
#define B11110001 241
|
||||
#define B11110010 242
|
||||
#define B11110011 243
|
||||
#define B11110100 244
|
||||
#define B11110101 245
|
||||
#define B11110110 246
|
||||
#define B11110111 247
|
||||
#define B11111000 248
|
||||
#define B11111001 249
|
||||
#define B11111010 250
|
||||
#define B11111011 251
|
||||
#define B11111100 252
|
||||
#define B11111101 253
|
||||
#define B11111110 254
|
||||
#define B11111111 255
|
||||
|
||||
#endif
|
@ -1,20 +0,0 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
init();
|
||||
|
||||
#if defined(USBCON)
|
||||
USBDevice.attach();
|
||||
#endif
|
||||
|
||||
setup();
|
||||
|
||||
for (;;) {
|
||||
loop();
|
||||
if (serialEventRun) serialEventRun();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
@ -1,28 +0,0 @@
|
||||
#include <new.h>
|
||||
|
||||
void * operator new(size_t size)
|
||||
{
|
||||
return malloc(size);
|
||||
}
|
||||
|
||||
void * operator new[](size_t size)
|
||||
{
|
||||
return malloc(size);
|
||||
}
|
||||
|
||||
void operator delete(void * ptr)
|
||||
{
|
||||
free(ptr);
|
||||
}
|
||||
|
||||
void operator delete[](void * ptr)
|
||||
{
|
||||
free(ptr);
|
||||
}
|
||||
|
||||
int __cxa_guard_acquire(__guard *g) {return !*(char *)(g);};
|
||||
void __cxa_guard_release (__guard *g) {*(char *)g = 1;};
|
||||
void __cxa_guard_abort (__guard *) {};
|
||||
|
||||
void __cxa_pure_virtual(void) {};
|
||||
|
@ -1,24 +0,0 @@
|
||||
/* Header to define new/delete operators as they aren't provided by avr-gcc by default
|
||||
Taken from http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=59453
|
||||
*/
|
||||
|
||||
#ifndef NEW_H
|
||||
#define NEW_H
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
void * operator new(size_t size);
|
||||
void * operator new[](size_t size);
|
||||
void operator delete(void * ptr);
|
||||
void operator delete[](void * ptr);
|
||||
|
||||
__extension__ typedef int __guard __attribute__((mode (__DI__)));
|
||||
|
||||
extern "C" int __cxa_guard_acquire(__guard *);
|
||||
extern "C" void __cxa_guard_release (__guard *);
|
||||
extern "C" void __cxa_guard_abort (__guard *);
|
||||
|
||||
extern "C" void __cxa_pure_virtual(void);
|
||||
|
||||
#endif
|
||||
|
@ -1,324 +0,0 @@
|
||||
/*
|
||||
wiring.c - Partial implementation of the Wiring API for the ATmega8.
|
||||
Part of Arduino - http://www.arduino.cc/
|
||||
|
||||
Copyright (c) 2005-2006 David A. Mellis
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General
|
||||
Public License along with this library; if not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
|
||||
Boston, MA 02111-1307 USA
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
#include "wiring_private.h"
|
||||
|
||||
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
|
||||
// the overflow handler is called every 256 ticks.
|
||||
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
|
||||
|
||||
// the whole number of milliseconds per timer0 overflow
|
||||
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
|
||||
|
||||
// the fractional number of milliseconds per timer0 overflow. we shift right
|
||||
// by three to fit these numbers into a byte. (for the clock speeds we care
|
||||
// about - 8 and 16 MHz - this doesn't lose precision.)
|
||||
#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
|
||||
#define FRACT_MAX (1000 >> 3)
|
||||
|
||||
volatile unsigned long timer0_overflow_count = 0;
|
||||
volatile unsigned long timer0_millis = 0;
|
||||
static unsigned char timer0_fract = 0;
|
||||
|
||||
#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
|
||||
ISR(TIM0_OVF_vect)
|
||||
#else
|
||||
ISR(TIMER0_OVF_vect)
|
||||
#endif
|
||||
{
|
||||
// copy these to local variables so they can be stored in registers
|
||||
// (volatile variables must be read from memory on every access)
|
||||
unsigned long m = timer0_millis;
|
||||
unsigned char f = timer0_fract;
|
||||
|
||||
m += MILLIS_INC;
|
||||
f += FRACT_INC;
|
||||
if (f >= FRACT_MAX) {
|
||||
f -= FRACT_MAX;
|
||||
m += 1;
|
||||
}
|
||||
|
||||
timer0_fract = f;
|
||||
timer0_millis = m;
|
||||
timer0_overflow_count++;
|
||||
}
|
||||
|
||||
unsigned long millis()
|
||||
{
|
||||
unsigned long m;
|
||||
uint8_t oldSREG = SREG;
|
||||
|
||||
// disable interrupts while we read timer0_millis or we might get an
|
||||
// inconsistent value (e.g. in the middle of a write to timer0_millis)
|
||||
cli();
|
||||
m = timer0_millis;
|
||||
SREG = oldSREG;
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
unsigned long micros() {
|
||||
unsigned long m;
|
||||
uint8_t oldSREG = SREG, t;
|
||||
|
||||
cli();
|
||||
m = timer0_overflow_count;
|
||||
#if defined(TCNT0)
|
||||
t = TCNT0;
|
||||
#elif defined(TCNT0L)
|
||||
t = TCNT0L;
|
||||
#else
|
||||
#error TIMER 0 not defined
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef TIFR0
|
||||
if ((TIFR0 & _BV(TOV0)) && (t < 255))
|
||||
m++;
|
||||
#else
|
||||
if ((TIFR & _BV(TOV0)) && (t < 255))
|
||||
m++;
|
||||
#endif
|
||||
|
||||
SREG = oldSREG;
|
||||
|
||||
return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
|
||||
}
|
||||
|
||||
void delay(unsigned long ms)
|
||||
{
|
||||
uint16_t start = (uint16_t)micros();
|
||||
|
||||
while (ms > 0) {
|
||||
if (((uint16_t)micros() - start) >= 1000) {
|
||||
ms--;
|
||||
start += 1000;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Delay for the given number of microseconds. Assumes a 8 or 16 MHz clock. */
|
||||
void delayMicroseconds(unsigned int us)
|
||||
{
|
||||
// calling avrlib's delay_us() function with low values (e.g. 1 or
|
||||
// 2 microseconds) gives delays longer than desired.
|
||||
//delay_us(us);
|
||||
#if F_CPU >= 20000000L
|
||||
// for the 20 MHz clock on rare Arduino boards
|
||||
|
||||
// for a one-microsecond delay, simply wait 2 cycle and return. The overhead
|
||||
// of the function call yields a delay of exactly a one microsecond.
|
||||
__asm__ __volatile__ (
|
||||
"nop" "\n\t"
|
||||
"nop"); //just waiting 2 cycle
|
||||
if (--us == 0)
|
||||
return;
|
||||
|
||||
// the following loop takes a 1/5 of a microsecond (4 cycles)
|
||||
// per iteration, so execute it five times for each microsecond of
|
||||
// delay requested.
|
||||
us = (us<<2) + us; // x5 us
|
||||
|
||||
// account for the time taken in the preceeding commands.
|
||||
us -= 2;
|
||||
|
||||
#elif F_CPU >= 16000000L
|
||||
// for the 16 MHz clock on most Arduino boards
|
||||
|
||||
// for a one-microsecond delay, simply return. the overhead
|
||||
// of the function call yields a delay of approximately 1 1/8 us.
|
||||
if (--us == 0)
|
||||
return;
|
||||
|
||||
// the following loop takes a quarter of a microsecond (4 cycles)
|
||||
// per iteration, so execute it four times for each microsecond of
|
||||
// delay requested.
|
||||
us <<= 2;
|
||||
|
||||
// account for the time taken in the preceeding commands.
|
||||
us -= 2;
|
||||
#else
|
||||
// for the 8 MHz internal clock on the ATmega168
|
||||
|
||||
// for a one- or two-microsecond delay, simply return. the overhead of
|
||||
// the function calls takes more than two microseconds. can't just
|
||||
// subtract two, since us is unsigned; we'd overflow.
|
||||
if (--us == 0)
|
||||
return;
|
||||
if (--us == 0)
|
||||
return;
|
||||
|
||||
// the following loop takes half of a microsecond (4 cycles)
|
||||
// per iteration, so execute it twice for each microsecond of
|
||||
// delay requested.
|
||||
us <<= 1;
|
||||
|
||||
// partially compensate for the time taken by the preceeding commands.
|
||||
// we can't subtract any more than this or we'd overflow w/ small delays.
|
||||
us--;
|
||||
#endif
|
||||
|
||||
// busy wait
|
||||
__asm__ __volatile__ (
|
||||
"1: sbiw %0,1" "\n\t" // 2 cycles
|
||||
"brne 1b" : "=w" (us) : "0" (us) // 2 cycles
|
||||
);
|
||||
}
|
||||
|
||||
void init()
|
||||
{
|
||||
// this needs to be called before setup() or some functions won't
|
||||
// work there
|
||||
sei();
|
||||
|
||||
// on the ATmega168, timer 0 is also used for fast hardware pwm
|
||||
// (using phase-correct PWM would mean that timer 0 overflowed half as often
|
||||
// resulting in different millis() behavior on the ATmega8 and ATmega168)
|
||||
#if defined(TCCR0A) && defined(WGM01)
|
||||
sbi(TCCR0A, WGM01);
|
||||
sbi(TCCR0A, WGM00);
|
||||
#endif
|
||||
|
||||
// set timer 0 prescale factor to 64
|
||||
#if defined(__AVR_ATmega128__)
|
||||
// CPU specific: different values for the ATmega128
|
||||
sbi(TCCR0, CS02);
|
||||
#elif defined(TCCR0) && defined(CS01) && defined(CS00)
|
||||
// this combination is for the standard atmega8
|
||||
sbi(TCCR0, CS01);
|
||||
sbi(TCCR0, CS00);
|
||||
#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
|
||||
// this combination is for the standard 168/328/1280/2560
|
||||
sbi(TCCR0B, CS01);
|
||||
sbi(TCCR0B, CS00);
|
||||
#elif defined(TCCR0A) && defined(CS01) && defined(CS00)
|
||||
// this combination is for the __AVR_ATmega645__ series
|
||||
sbi(TCCR0A, CS01);
|
||||
sbi(TCCR0A, CS00);
|
||||
#else
|
||||
#error Timer 0 prescale factor 64 not set correctly
|
||||
#endif
|
||||
|
||||
// enable timer 0 overflow interrupt
|
||||
#if defined(TIMSK) && defined(TOIE0)
|
||||
sbi(TIMSK, TOIE0);
|
||||
#elif defined(TIMSK0) && defined(TOIE0)
|
||||
sbi(TIMSK0, TOIE0);
|
||||
#else
|
||||
#error Timer 0 overflow interrupt not set correctly
|
||||
#endif
|
||||
|
||||
// timers 1 and 2 are used for phase-correct hardware pwm
|
||||
// this is better for motors as it ensures an even waveform
|
||||
// note, however, that fast pwm mode can achieve a frequency of up
|
||||
// 8 MHz (with a 16 MHz clock) at 50% duty cycle
|
||||
|
||||
#if defined(TCCR1B) && defined(CS11) && defined(CS10)
|
||||
TCCR1B = 0;
|
||||
|
||||
// set timer 1 prescale factor to 64
|
||||
sbi(TCCR1B, CS11);
|
||||
#if F_CPU >= 8000000L
|
||||
sbi(TCCR1B, CS10);
|
||||
#endif
|
||||
#elif defined(TCCR1) && defined(CS11) && defined(CS10)
|
||||
sbi(TCCR1, CS11);
|
||||
#if F_CPU >= 8000000L
|
||||
sbi(TCCR1, CS10);
|
||||
#endif
|
||||
#endif
|
||||
// put timer 1 in 8-bit phase correct pwm mode
|
||||
#if defined(TCCR1A) && defined(WGM10)
|
||||
sbi(TCCR1A, WGM10);
|
||||
#elif defined(TCCR1)
|
||||
#warning this needs to be finished
|
||||
#endif
|
||||
|
||||
// set timer 2 prescale factor to 64
|
||||
#if defined(TCCR2) && defined(CS22)
|
||||
sbi(TCCR2, CS22);
|
||||
#elif defined(TCCR2B) && defined(CS22)
|
||||
sbi(TCCR2B, CS22);
|
||||
#else
|
||||
#warning Timer 2 not finished (may not be present on this CPU)
|
||||
#endif
|
||||
|
||||
// configure timer 2 for phase correct pwm (8-bit)
|
||||
#if defined(TCCR2) && defined(WGM20)
|
||||
sbi(TCCR2, WGM20);
|
||||
#elif defined(TCCR2A) && defined(WGM20)
|
||||
sbi(TCCR2A, WGM20);
|
||||
#else
|
||||
#warning Timer 2 not finished (may not be present on this CPU)
|
||||
#endif
|
||||
|
||||
#if defined(TCCR3B) && defined(CS31) && defined(WGM30)
|
||||
sbi(TCCR3B, CS31); // set timer 3 prescale factor to 64
|
||||
sbi(TCCR3B, CS30);
|
||||
sbi(TCCR3A, WGM30); // put timer 3 in 8-bit phase correct pwm mode
|
||||
#endif
|
||||
|
||||
#if defined(TCCR4A) && defined(TCCR4B) && defined(TCCR4D) /* beginning of timer4 block for 32U4 and similar */
|
||||
sbi(TCCR4B, CS42); // set timer4 prescale factor to 64
|
||||
sbi(TCCR4B, CS41);
|
||||
sbi(TCCR4B, CS40);
|
||||
sbi(TCCR4D, WGM40); // put timer 4 in phase- and frequency-correct PWM mode
|
||||
sbi(TCCR4A, PWM4A); // enable PWM mode for comparator OCR4A
|
||||
sbi(TCCR4C, PWM4D); // enable PWM mode for comparator OCR4D
|
||||
#else /* beginning of timer4 block for ATMEGA1280 and ATMEGA2560 */
|
||||
#if defined(TCCR4B) && defined(CS41) && defined(WGM40)
|
||||
sbi(TCCR4B, CS41); // set timer 4 prescale factor to 64
|
||||
sbi(TCCR4B, CS40);
|
||||
sbi(TCCR4A, WGM40); // put timer 4 in 8-bit phase correct pwm mode
|
||||
#endif
|
||||
#endif /* end timer4 block for ATMEGA1280/2560 and similar */
|
||||
|
||||
#if defined(TCCR5B) && defined(CS51) && defined(WGM50)
|
||||
sbi(TCCR5B, CS51); // set timer 5 prescale factor to 64
|
||||
sbi(TCCR5B, CS50);
|
||||
sbi(TCCR5A, WGM50); // put timer 5 in 8-bit phase correct pwm mode
|
||||
#endif
|
||||
|
||||
#if defined(ADCSRA)
|
||||
// set a2d prescale factor to 128
|
||||
// 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
|
||||
// XXX: this will not work properly for other clock speeds, and
|
||||
// this code should use F_CPU to determine the prescale factor.
|
||||
sbi(ADCSRA, ADPS2);
|
||||
sbi(ADCSRA, ADPS1);
|
||||
sbi(ADCSRA, ADPS0);
|
||||
|
||||
// enable a2d conversions
|
||||
sbi(ADCSRA, ADEN);
|
||||
#endif
|
||||
|
||||
// the bootloader connects pins 0 and 1 to the USART; disconnect them
|
||||
// here so they can be used as normal digital i/o; they will be
|
||||
// reconnected in Serial.begin()
|
||||
#if defined(UCSRB)
|
||||
UCSRB = 0;
|
||||
#elif defined(UCSR0B)
|
||||
UCSR0B = 0;
|
||||
#endif
|
||||
}
|
@ -1,284 +0,0 @@
|
||||
/*
|
||||
wiring_analog.c - analog input and output
|
||||
Part of Arduino - http://www.arduino.cc/
|
||||
|
||||
Copyright (c) 2005-2006 David A. Mellis
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General
|
||||
Public License along with this library; if not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
|
||||
Boston, MA 02111-1307 USA
|
||||
|
||||
Modified 28 September 2010 by Mark Sproul
|
||||
|
||||
$Id: wiring.c 248 2007-02-03 15:36:30Z mellis $
|
||||
*/
|
||||
|
||||
#include "wiring_private.h"
|
||||
#include "pins_arduino.h"
|
||||
|
||||
uint8_t analog_reference = DEFAULT;
|
||||
|
||||
void analogReference(uint8_t mode)
|
||||
{
|
||||
// can't actually set the register here because the default setting
|
||||
// will connect AVCC and the AREF pin, which would cause a short if
|
||||
// there's something connected to AREF.
|
||||
analog_reference = mode;
|
||||
}
|
||||
|
||||
int analogRead(uint8_t pin)
|
||||
{
|
||||
uint8_t low, high;
|
||||
|
||||
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
|
||||
if (pin >= 54) pin -= 54; // allow for channel or pin numbers
|
||||
#elif defined(__AVR_ATmega32U4__)
|
||||
if (pin >= 18) pin -= 18; // allow for channel or pin numbers
|
||||
#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__)
|
||||
if (pin >= 24) pin -= 24; // allow for channel or pin numbers
|
||||
#elif defined(analogPinToChannel) && (defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__))
|
||||
pin = analogPinToChannel(pin);
|
||||
#else
|
||||
if (pin >= 14) pin -= 14; // allow for channel or pin numbers
|
||||
#endif
|
||||
|
||||
#if defined(__AVR_ATmega32U4__)
|
||||
pin = analogPinToChannel(pin);
|
||||
ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5);
|
||||
#elif defined(ADCSRB) && defined(MUX5)
|
||||
// the MUX5 bit of ADCSRB selects whether we're reading from channels
|
||||
// 0 to 7 (MUX5 low) or 8 to 15 (MUX5 high).
|
||||
ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5);
|
||||
#endif
|
||||
|
||||
// set the analog reference (high two bits of ADMUX) and select the
|
||||
// channel (low 4 bits). this also sets ADLAR (left-adjust result)
|
||||
// to 0 (the default).
|
||||
#if defined(ADMUX)
|
||||
ADMUX = (analog_reference << 6) | (pin & 0x07);
|
||||
#endif
|
||||
|
||||
// without a delay, we seem to read from the wrong channel
|
||||
//delay(1);
|
||||
|
||||
#if defined(ADCSRA) && defined(ADCL)
|
||||
// start the conversion
|
||||
sbi(ADCSRA, ADSC);
|
||||
|
||||
// ADSC is cleared when the conversion finishes
|
||||
while (bit_is_set(ADCSRA, ADSC));
|
||||
|
||||
// we have to read ADCL first; doing so locks both ADCL
|
||||
// and ADCH until ADCH is read. reading ADCL second would
|
||||
// cause the results of each conversion to be discarded,
|
||||
// as ADCL and ADCH would be locked when it completed.
|
||||
low = ADCL;
|
||||
high = ADCH;
|
||||
#else
|
||||
// we dont have an ADC, return 0
|
||||
low = 0;
|
||||
high = 0;
|
||||
#endif
|
||||
|
||||
// combine the two bytes
|
||||
return (high << 8) | low;
|
||||
}
|
||||
|
||||
// Right now, PWM output only works on the pins with
|
||||
// hardware support. These are defined in the appropriate
|
||||
// pins_*.c file. For the rest of the pins, we default
|
||||
// to digital output.
|
||||
void analogWrite(uint8_t pin, int val)
|
||||
{
|
||||
// We need to make sure the PWM output is enabled for those pins
|
||||
// that support it, as we turn it off when digitally reading or
|
||||
// writing with them. Also, make sure the pin is in output mode
|
||||
// for consistenty with Wiring, which doesn't require a pinMode
|
||||
// call for the analog output pins.
|
||||
pinMode(pin, OUTPUT);
|
||||
if (val == 0)
|
||||
{
|
||||
digitalWrite(pin, LOW);
|
||||
}
|
||||
else if (val == 255)
|
||||
{
|
||||
digitalWrite(pin, HIGH);
|
||||
}
|
||||
else
|
||||
{
|
||||
switch(digitalPinToTimer(pin))
|
||||
{
|
||||
// XXX fix needed for atmega8
|
||||
#if defined(TCCR0) && defined(COM00) && !defined(__AVR_ATmega8__)
|
||||
case TIMER0A:
|
||||
// connect pwm to pin on timer 0
|
||||
sbi(TCCR0, COM00);
|
||||
OCR0 = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR0A) && defined(COM0A1)
|
||||
case TIMER0A:
|
||||
// connect pwm to pin on timer 0, channel A
|
||||
sbi(TCCR0A, COM0A1);
|
||||
OCR0A = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR0A) && defined(COM0B1)
|
||||
case TIMER0B:
|
||||
// connect pwm to pin on timer 0, channel B
|
||||
sbi(TCCR0A, COM0B1);
|
||||
OCR0B = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR1A) && defined(COM1A1)
|
||||
case TIMER1A:
|
||||
// connect pwm to pin on timer 1, channel A
|
||||
sbi(TCCR1A, COM1A1);
|
||||
OCR1A = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR1A) && defined(COM1B1)
|
||||
case TIMER1B:
|
||||
// connect pwm to pin on timer 1, channel B
|
||||
sbi(TCCR1A, COM1B1);
|
||||
OCR1B = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR2) && defined(COM21)
|
||||
case TIMER2:
|
||||
// connect pwm to pin on timer 2
|
||||
sbi(TCCR2, COM21);
|
||||
OCR2 = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR2A) && defined(COM2A1)
|
||||
case TIMER2A:
|
||||
// connect pwm to pin on timer 2, channel A
|
||||
sbi(TCCR2A, COM2A1);
|
||||
OCR2A = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR2A) && defined(COM2B1)
|
||||
case TIMER2B:
|
||||
// connect pwm to pin on timer 2, channel B
|
||||
sbi(TCCR2A, COM2B1);
|
||||
OCR2B = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR3A) && defined(COM3A1)
|
||||
case TIMER3A:
|
||||
// connect pwm to pin on timer 3, channel A
|
||||
sbi(TCCR3A, COM3A1);
|
||||
OCR3A = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR3A) && defined(COM3B1)
|
||||
case TIMER3B:
|
||||
// connect pwm to pin on timer 3, channel B
|
||||
sbi(TCCR3A, COM3B1);
|
||||
OCR3B = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR3A) && defined(COM3C1)
|
||||
case TIMER3C:
|
||||
// connect pwm to pin on timer 3, channel C
|
||||
sbi(TCCR3A, COM3C1);
|
||||
OCR3C = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR4A)
|
||||
case TIMER4A:
|
||||
//connect pwm to pin on timer 4, channel A
|
||||
sbi(TCCR4A, COM4A1);
|
||||
#if defined(COM4A0) // only used on 32U4
|
||||
cbi(TCCR4A, COM4A0);
|
||||
#endif
|
||||
OCR4A = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR4A) && defined(COM4B1)
|
||||
case TIMER4B:
|
||||
// connect pwm to pin on timer 4, channel B
|
||||
sbi(TCCR4A, COM4B1);
|
||||
OCR4B = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR4A) && defined(COM4C1)
|
||||
case TIMER4C:
|
||||
// connect pwm to pin on timer 4, channel C
|
||||
sbi(TCCR4A, COM4C1);
|
||||
OCR4C = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR4C) && defined(COM4D1)
|
||||
case TIMER4D:
|
||||
// connect pwm to pin on timer 4, channel D
|
||||
sbi(TCCR4C, COM4D1);
|
||||
#if defined(COM4D0) // only used on 32U4
|
||||
cbi(TCCR4C, COM4D0);
|
||||
#endif
|
||||
OCR4D = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(TCCR5A) && defined(COM5A1)
|
||||
case TIMER5A:
|
||||
// connect pwm to pin on timer 5, channel A
|
||||
sbi(TCCR5A, COM5A1);
|
||||
OCR5A = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR5A) && defined(COM5B1)
|
||||
case TIMER5B:
|
||||
// connect pwm to pin on timer 5, channel B
|
||||
sbi(TCCR5A, COM5B1);
|
||||
OCR5B = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR5A) && defined(COM5C1)
|
||||
case TIMER5C:
|
||||
// connect pwm to pin on timer 5, channel C
|
||||
sbi(TCCR5A, COM5C1);
|
||||
OCR5C = val; // set pwm duty
|
||||
break;
|
||||
#endif
|
||||
|
||||
case NOT_ON_TIMER:
|
||||
default:
|
||||
if (val < 128) {
|
||||
digitalWrite(pin, LOW);
|
||||
} else {
|
||||
digitalWrite(pin, HIGH);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,178 +0,0 @@
|
||||
/*
|
||||
wiring_digital.c - digital input and output functions
|
||||
Part of Arduino - http://www.arduino.cc/
|
||||
|
||||
Copyright (c) 2005-2006 David A. Mellis
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General
|
||||
Public License along with this library; if not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
|
||||
Boston, MA 02111-1307 USA
|
||||
|
||||
Modified 28 September 2010 by Mark Sproul
|
||||
|
||||
$Id: wiring.c 248 2007-02-03 15:36:30Z mellis $
|
||||
*/
|
||||
|
||||
#define ARDUINO_MAIN
|
||||
#include "wiring_private.h"
|
||||
#include "pins_arduino.h"
|
||||
|
||||
void pinMode(uint8_t pin, uint8_t mode)
|
||||
{
|
||||
uint8_t bit = digitalPinToBitMask(pin);
|
||||
uint8_t port = digitalPinToPort(pin);
|
||||
volatile uint8_t *reg, *out;
|
||||
|
||||
if (port == NOT_A_PIN) return;
|
||||
|
||||
// JWS: can I let the optimizer do this?
|
||||
reg = portModeRegister(port);
|
||||
out = portOutputRegister(port);
|
||||
|
||||
if (mode == INPUT) {
|
||||
uint8_t oldSREG = SREG;
|
||||
cli();
|
||||
*reg &= ~bit;
|
||||
*out &= ~bit;
|
||||
SREG = oldSREG;
|
||||
} else if (mode == INPUT_PULLUP) {
|
||||
uint8_t oldSREG = SREG;
|
||||
cli();
|
||||
*reg &= ~bit;
|
||||
*out |= bit;
|
||||
SREG = oldSREG;
|
||||
} else {
|
||||
uint8_t oldSREG = SREG;
|
||||
cli();
|
||||
*reg |= bit;
|
||||
SREG = oldSREG;
|
||||
}
|
||||
}
|
||||
|
||||
// Forcing this inline keeps the callers from having to push their own stuff
|
||||
// on the stack. It is a good performance win and only takes 1 more byte per
|
||||
// user than calling. (It will take more bytes on the 168.)
|
||||
//
|
||||
// But shouldn't this be moved into pinMode? Seems silly to check and do on
|
||||
// each digitalread or write.
|
||||
//
|
||||
// Mark Sproul:
|
||||
// - Removed inline. Save 170 bytes on atmega1280
|
||||
// - changed to a switch statment; added 32 bytes but much easier to read and maintain.
|
||||
// - Added more #ifdefs, now compiles for atmega645
|
||||
//
|
||||
//static inline void turnOffPWM(uint8_t timer) __attribute__ ((always_inline));
|
||||
//static inline void turnOffPWM(uint8_t timer)
|
||||
static void turnOffPWM(uint8_t timer)
|
||||
{
|
||||
switch (timer)
|
||||
{
|
||||
#if defined(TCCR1A) && defined(COM1A1)
|
||||
case TIMER1A: cbi(TCCR1A, COM1A1); break;
|
||||
#endif
|
||||
#if defined(TCCR1A) && defined(COM1B1)
|
||||
case TIMER1B: cbi(TCCR1A, COM1B1); break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR2) && defined(COM21)
|
||||
case TIMER2: cbi(TCCR2, COM21); break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR0A) && defined(COM0A1)
|
||||
case TIMER0A: cbi(TCCR0A, COM0A1); break;
|
||||
#endif
|
||||
|
||||
#if defined(TIMER0B) && defined(COM0B1)
|
||||
case TIMER0B: cbi(TCCR0A, COM0B1); break;
|
||||
#endif
|
||||
#if defined(TCCR2A) && defined(COM2A1)
|
||||
case TIMER2A: cbi(TCCR2A, COM2A1); break;
|
||||
#endif
|
||||
#if defined(TCCR2A) && defined(COM2B1)
|
||||
case TIMER2B: cbi(TCCR2A, COM2B1); break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR3A) && defined(COM3A1)
|
||||
case TIMER3A: cbi(TCCR3A, COM3A1); break;
|
||||
#endif
|
||||
#if defined(TCCR3A) && defined(COM3B1)
|
||||
case TIMER3B: cbi(TCCR3A, COM3B1); break;
|
||||
#endif
|
||||
#if defined(TCCR3A) && defined(COM3C1)
|
||||
case TIMER3C: cbi(TCCR3A, COM3C1); break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR4A) && defined(COM4A1)
|
||||
case TIMER4A: cbi(TCCR4A, COM4A1); break;
|
||||
#endif
|
||||
#if defined(TCCR4A) && defined(COM4B1)
|
||||
case TIMER4B: cbi(TCCR4A, COM4B1); break;
|
||||
#endif
|
||||
#if defined(TCCR4A) && defined(COM4C1)
|
||||
case TIMER4C: cbi(TCCR4A, COM4C1); break;
|
||||
#endif
|
||||
#if defined(TCCR4C) && defined(COM4D1)
|
||||
case TIMER4D: cbi(TCCR4C, COM4D1); break;
|
||||
#endif
|
||||
|
||||
#if defined(TCCR5A)
|
||||
case TIMER5A: cbi(TCCR5A, COM5A1); break;
|
||||
case TIMER5B: cbi(TCCR5A, COM5B1); break;
|
||||
case TIMER5C: cbi(TCCR5A, COM5C1); break;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
void digitalWrite(uint8_t pin, uint8_t val)
|
||||
{
|
||||
uint8_t timer = digitalPinToTimer(pin);
|
||||
uint8_t bit = digitalPinToBitMask(pin);
|
||||
uint8_t port = digitalPinToPort(pin);
|
||||
volatile uint8_t *out;
|
||||
|
||||
if (port == NOT_A_PIN) return;
|
||||
|
||||
// If the pin that support PWM output, we need to turn it off
|
||||
// before doing a digital write.
|
||||
if (timer != NOT_ON_TIMER) turnOffPWM(timer);
|
||||
|
||||
out = portOutputRegister(port);
|
||||
|
||||
uint8_t oldSREG = SREG;
|
||||
cli();
|
||||
|
||||
if (val == LOW) {
|
||||
*out &= ~bit;
|
||||
} else {
|
||||
*out |= bit;
|
||||
}
|
||||
|
||||
SREG = oldSREG;
|
||||
}
|
||||
|
||||
int digitalRead(uint8_t pin)
|
||||
{
|
||||
uint8_t timer = digitalPinToTimer(pin);
|
||||
uint8_t bit = digitalPinToBitMask(pin);
|
||||
uint8_t port = digitalPinToPort(pin);
|
||||
|
||||
if (port == NOT_A_PIN) return LOW;
|
||||
|
||||
// If the pin that support PWM output, we need to turn it off
|
||||
// before getting a digital reading.
|
||||
if (timer != NOT_ON_TIMER) turnOffPWM(timer);
|
||||
|
||||
if (*portInputRegister(port) & bit) return HIGH;
|
||||
return LOW;
|
||||
}
|
@ -1,71 +0,0 @@
|
||||
/*
|
||||
wiring_private.h - Internal header file.
|
||||
Part of Arduino - http://www.arduino.cc/
|
||||
|
||||
Copyright (c) 2005-2006 David A. Mellis
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General
|
||||
Public License along with this library; if not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
|
||||
Boston, MA 02111-1307 USA
|
||||
|
||||
$Id: wiring.h 239 2007-01-12 17:58:39Z mellis $
|
||||
*/
|
||||
|
||||
#ifndef WiringPrivate_h
|
||||
#define WiringPrivate_h
|
||||
|
||||
#include <avr/io.h>
|
||||
#include <avr/interrupt.h>
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
#include "Arduino.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"{
|
||||
#endif
|
||||
|
||||
#ifndef cbi
|
||||
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
|
||||
#endif
|
||||
#ifndef sbi
|
||||
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
|
||||
#endif
|
||||
|
||||
#define EXTERNAL_INT_0 0
|
||||
#define EXTERNAL_INT_1 1
|
||||
#define EXTERNAL_INT_2 2
|
||||
#define EXTERNAL_INT_3 3
|
||||
#define EXTERNAL_INT_4 4
|
||||
#define EXTERNAL_INT_5 5
|
||||
#define EXTERNAL_INT_6 6
|
||||
#define EXTERNAL_INT_7 7
|
||||
|
||||
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
|
||||
#define EXTERNAL_NUM_INTERRUPTS 8
|
||||
#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__)
|
||||
#define EXTERNAL_NUM_INTERRUPTS 3
|
||||
#elif defined(__AVR_ATmega32U4__)
|
||||
#define EXTERNAL_NUM_INTERRUPTS 5
|
||||
#else
|
||||
#define EXTERNAL_NUM_INTERRUPTS 2
|
||||
#endif
|
||||
|
||||
typedef void (*voidFuncPtr)(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
|
||||
#endif
|
@ -1,69 +0,0 @@
|
||||
/*
|
||||
wiring_pulse.c - pulseIn() function
|
||||
Part of Arduino - http://www.arduino.cc/
|
||||
|
||||
Copyright (c) 2005-2006 David A. Mellis
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General
|
||||
Public License along with this library; if not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
|
||||
Boston, MA 02111-1307 USA
|
||||
|
||||
$Id: wiring.c 248 2007-02-03 15:36:30Z mellis $
|
||||
*/
|
||||
|
||||
#include "wiring_private.h"
|
||||
#include "pins_arduino.h"
|
||||
|
||||
/* Measures the length (in microseconds) of a pulse on the pin; state is HIGH
|
||||
* or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds
|
||||
* to 3 minutes in length, but must be called at least a few dozen microseconds
|
||||
* before the start of the pulse. */
|
||||
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
|
||||
{
|
||||
// cache the port and bit of the pin in order to speed up the
|
||||
// pulse width measuring loop and achieve finer resolution. calling
|
||||
// digitalRead() instead yields much coarser resolution.
|
||||
uint8_t bit = digitalPinToBitMask(pin);
|
||||
uint8_t port = digitalPinToPort(pin);
|
||||
uint8_t stateMask = (state ? bit : 0);
|
||||
unsigned long width = 0; // keep initialization out of time critical area
|
||||
|
||||
// convert the timeout from microseconds to a number of times through
|
||||
// the initial loop; it takes 16 clock cycles per iteration.
|
||||
unsigned long numloops = 0;
|
||||
unsigned long maxloops = microsecondsToClockCycles(timeout) / 16;
|
||||
|
||||
// wait for any previous pulse to end
|
||||
while ((*portInputRegister(port) & bit) == stateMask)
|
||||
if (numloops++ == maxloops)
|
||||
return 0;
|
||||
|
||||
// wait for the pulse to start
|
||||
while ((*portInputRegister(port) & bit) != stateMask)
|
||||
if (numloops++ == maxloops)
|
||||
return 0;
|
||||
|
||||
// wait for the pulse to stop
|
||||
while ((*portInputRegister(port) & bit) == stateMask) {
|
||||
if (numloops++ == maxloops)
|
||||
return 0;
|
||||
width++;
|
||||
}
|
||||
|
||||
// convert the reading to microseconds. The loop has been determined
|
||||
// to be 20 clock cycles long and have about 16 clocks between the edge
|
||||
// and the start of the loop. There will be some error introduced by
|
||||
// the interrupt handlers.
|
||||
return clockCyclesToMicroseconds(width * 21 + 16);
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
/*
|
||||
wiring_shift.c - shiftOut() function
|
||||
Part of Arduino - http://www.arduino.cc/
|
||||
|
||||
Copyright (c) 2005-2006 David A. Mellis
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General
|
||||
Public License along with this library; if not, write to the
|
||||
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
|
||||
Boston, MA 02111-1307 USA
|
||||
|
||||
$Id: wiring.c 248 2007-02-03 15:36:30Z mellis $
|
||||
*/
|
||||
|
||||
#include "wiring_private.h"
|
||||
|
||||
uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
|
||||
uint8_t value = 0;
|
||||
uint8_t i;
|
||||
|
||||
for (i = 0; i < 8; ++i) {
|
||||
digitalWrite(clockPin, HIGH);
|
||||
if (bitOrder == LSBFIRST)
|
||||
value |= digitalRead(dataPin) << i;
|
||||
else
|
||||
value |= digitalRead(dataPin) << (7 - i);
|
||||
digitalWrite(clockPin, LOW);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
|
||||
{
|
||||
uint8_t i;
|
||||
|
||||
for (i = 0; i < 8; i++) {
|
||||
if (bitOrder == LSBFIRST)
|
||||
digitalWrite(dataPin, !!(val & (1 << i)));
|
||||
else
|
||||
digitalWrite(dataPin, !!(val & (1 << (7 - i))));
|
||||
|
||||
digitalWrite(clockPin, HIGH);
|
||||
digitalWrite(clockPin, LOW);
|
||||
}
|
||||
}
|
@ -1,165 +0,0 @@
|
||||
#include "w5100.h"
|
||||
#include "socket.h"
|
||||
|
||||
extern "C" {
|
||||
#include "string.h"
|
||||
}
|
||||
|
||||
#include "Arduino.h"
|
||||
|
||||
#include "Ethernet.h"
|
||||
#include "EthernetClient.h"
|
||||
#include "EthernetServer.h"
|
||||
#include "Dns.h"
|
||||
|
||||
uint16_t EthernetClient::_srcport = 1024;
|
||||
|
||||
EthernetClient::EthernetClient() : _sock(MAX_SOCK_NUM) {
|
||||
}
|
||||
|
||||
EthernetClient::EthernetClient(uint8_t sock) : _sock(sock) {
|
||||
}
|
||||
|
||||
int EthernetClient::connect(const char* host, uint16_t port) {
|
||||
// Look up the host first
|
||||
int ret = 0;
|
||||
DNSClient dns;
|
||||
IPAddress remote_addr;
|
||||
|
||||
dns.begin(Ethernet.dnsServerIP());
|
||||
ret = dns.getHostByName(host, remote_addr);
|
||||
if (ret == 1) {
|
||||
return connect(remote_addr, port);
|
||||
} else {
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
int EthernetClient::connect(IPAddress ip, uint16_t port) {
|
||||
if (_sock != MAX_SOCK_NUM)
|
||||
return 0;
|
||||
|
||||
for (int i = 0; i < MAX_SOCK_NUM; i++) {
|
||||
uint8_t s = W5100.readSnSR(i);
|
||||
if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) {
|
||||
_sock = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (_sock == MAX_SOCK_NUM)
|
||||
return 0;
|
||||
|
||||
_srcport++;
|
||||
if (_srcport == 0) _srcport = 1024;
|
||||
socket(_sock, SnMR::TCP, _srcport, 0);
|
||||
|
||||
if (!::connect(_sock, rawIPAddress(ip), port)) {
|
||||
_sock = MAX_SOCK_NUM;
|
||||
return 0;
|
||||
}
|
||||
|
||||
while (status() != SnSR::ESTABLISHED) {
|
||||
delay(1);
|
||||
if (status() == SnSR::CLOSED) {
|
||||
_sock = MAX_SOCK_NUM;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t EthernetClient::write(uint8_t b) {
|
||||
return write(&b, 1);
|
||||
}
|
||||
|
||||
size_t EthernetClient::write(const uint8_t *buf, size_t size) {
|
||||
if (_sock == MAX_SOCK_NUM) {
|
||||
setWriteError();
|
||||
return 0;
|
||||
}
|
||||
if (!send(_sock, buf, size)) {
|
||||
setWriteError();
|
||||
return 0;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
int EthernetClient::available() {
|
||||
if (_sock != MAX_SOCK_NUM)
|
||||
return W5100.getRXReceivedSize(_sock);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int EthernetClient::read() {
|
||||
uint8_t b;
|
||||
if ( recv(_sock, &b, 1) > 0 )
|
||||
{
|
||||
// recv worked
|
||||
return b;
|
||||
}
|
||||
else
|
||||
{
|
||||
// No data available
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
int EthernetClient::read(uint8_t *buf, size_t size) {
|
||||
return recv(_sock, buf, size);
|
||||
}
|
||||
|
||||
int EthernetClient::peek() {
|
||||
uint8_t b;
|
||||
// Unlike recv, peek doesn't check to see if there's any data available, so we must
|
||||
if (!available())
|
||||
return -1;
|
||||
::peek(_sock, &b);
|
||||
return b;
|
||||
}
|
||||
|
||||
void EthernetClient::flush() {
|
||||
while (available())
|
||||
read();
|
||||
}
|
||||
|
||||
void EthernetClient::stop() {
|
||||
if (_sock == MAX_SOCK_NUM)
|
||||
return;
|
||||
|
||||
// attempt to close the connection gracefully (send a FIN to other side)
|
||||
disconnect(_sock);
|
||||
unsigned long start = millis();
|
||||
|
||||
// wait a second for the connection to close
|
||||
while (status() != SnSR::CLOSED && millis() - start < 1000)
|
||||
delay(1);
|
||||
|
||||
// if it hasn't closed, close it forcefully
|
||||
if (status() != SnSR::CLOSED)
|
||||
close(_sock);
|
||||
|
||||
EthernetClass::_server_port[_sock] = 0;
|
||||
_sock = MAX_SOCK_NUM;
|
||||
}
|
||||
|
||||
uint8_t EthernetClient::connected() {
|
||||
if (_sock == MAX_SOCK_NUM) return 0;
|
||||
|
||||
uint8_t s = status();
|
||||
return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT ||
|
||||
(s == SnSR::CLOSE_WAIT && !available()));
|
||||
}
|
||||
|
||||
uint8_t EthernetClient::status() {
|
||||
if (_sock == MAX_SOCK_NUM) return SnSR::CLOSED;
|
||||
return W5100.readSnSR(_sock);
|
||||
}
|
||||
|
||||
// the next function allows us to use the client returned by
|
||||
// EthernetServer::available() as the condition in an if-statement.
|
||||
|
||||
EthernetClient::operator bool() {
|
||||
return _sock != MAX_SOCK_NUM;
|
||||
}
|
@ -1,136 +0,0 @@
|
||||
/*
|
||||
Twitter Client with Strings
|
||||
|
||||
This sketch connects to Twitter using an Ethernet shield. It parses the XML
|
||||
returned, and looks for <text>this is a tweet</text>
|
||||
|
||||
You can use the Arduino Ethernet shield, or the Adafruit Ethernet shield,
|
||||
either one will work, as long as it's got a Wiznet Ethernet module on board.
|
||||
|
||||
This example uses the DHCP routines in the Ethernet library which is part of the
|
||||
Arduino core from version 1.0 beta 1
|
||||
|
||||
This example uses the String library, which is part of the Arduino core from
|
||||
version 0019.
|
||||
|
||||
Circuit:
|
||||
* Ethernet shield attached to pins 10, 11, 12, 13
|
||||
|
||||
created 21 May 2011
|
||||
modified 9 Apr 2012
|
||||
by Tom Igoe
|
||||
|
||||
This code is in the public domain.
|
||||
|
||||
*/
|
||||
#include <SPI.h>
|
||||
#include <Ethernet.h>
|
||||
|
||||
|
||||
// Enter a MAC address and IP address for your controller below.
|
||||
// The IP address will be dependent on your local network:
|
||||
byte mac[] = {
|
||||
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 };
|
||||
IPAddress ip(192,168,1,20);
|
||||
|
||||
// initialize the library instance:
|
||||
EthernetClient client;
|
||||
|
||||
const unsigned long requestInterval = 60000; // delay between requests
|
||||
|
||||
char serverName[] = "api.twitter.com"; // twitter URL
|
||||
|
||||
boolean requested; // whether you've made a request since connecting
|
||||
unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds
|
||||
|
||||
String currentLine = ""; // string to hold the text from server
|
||||
String tweet = ""; // string to hold the tweet
|
||||
boolean readingTweet = false; // if you're currently reading the tweet
|
||||
|
||||
void setup() {
|
||||
// reserve space for the strings:
|
||||
currentLine.reserve(256);
|
||||
tweet.reserve(150);
|
||||
|
||||
// Open serial communications and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for Leonardo only
|
||||
}
|
||||
|
||||
|
||||
// attempt a DHCP connection:
|
||||
Serial.println("Attempting to get an IP address using DHCP:");
|
||||
if (!Ethernet.begin(mac)) {
|
||||
// if DHCP fails, start with a hard-coded address:
|
||||
Serial.println("failed to get an IP address using DHCP, trying manually");
|
||||
Ethernet.begin(mac, ip);
|
||||
}
|
||||
Serial.print("My address:");
|
||||
Serial.println(Ethernet.localIP());
|
||||
// connect to Twitter:
|
||||
connectToServer();
|
||||
}
|
||||
|
||||
|
||||
|
||||
void loop()
|
||||
{
|
||||
if (client.connected()) {
|
||||
if (client.available()) {
|
||||
// read incoming bytes:
|
||||
char inChar = client.read();
|
||||
|
||||
// add incoming byte to end of line:
|
||||
currentLine += inChar;
|
||||
|
||||
// if you get a newline, clear the line:
|
||||
if (inChar == '\n') {
|
||||
currentLine = "";
|
||||
}
|
||||
// if the current line ends with <text>, it will
|
||||
// be followed by the tweet:
|
||||
if ( currentLine.endsWith("<text>")) {
|
||||
// tweet is beginning. Clear the tweet string:
|
||||
readingTweet = true;
|
||||
tweet = "";
|
||||
}
|
||||
// if you're currently reading the bytes of a tweet,
|
||||
// add them to the tweet String:
|
||||
if (readingTweet) {
|
||||
if (inChar != '<') {
|
||||
tweet += inChar;
|
||||
}
|
||||
else {
|
||||
// if you got a "<" character,
|
||||
// you've reached the end of the tweet:
|
||||
readingTweet = false;
|
||||
Serial.println(tweet);
|
||||
// close the connection to the server:
|
||||
client.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (millis() - lastAttemptTime > requestInterval) {
|
||||
// if you're not connected, and two minutes have passed since
|
||||
// your last connection, then attempt to connect again:
|
||||
connectToServer();
|
||||
}
|
||||
}
|
||||
|
||||
void connectToServer() {
|
||||
// attempt to connect, and wait a millisecond:
|
||||
Serial.println("connecting to server...");
|
||||
if (client.connect(serverName, 80)) {
|
||||
Serial.println("making HTTP request...");
|
||||
// make HTTP GET request to twitter:
|
||||
client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino&count=1 HTTP/1.1");
|
||||
client.println("HOST: api.twitter.com");
|
||||
client.println("Connection: close");
|
||||
client.println();
|
||||
}
|
||||
// note the time of this connect attempt:
|
||||
lastAttemptTime = millis();
|
||||
}
|
||||
|
@ -1,41 +0,0 @@
|
||||
#ifndef _SOCKET_H_
|
||||
#define _SOCKET_H_
|
||||
|
||||
#include "w5100.h"
|
||||
|
||||
extern uint8_t socket(SOCKET s, uint8_t protocol, uint16_t port, uint8_t flag); // Opens a socket(TCP or UDP or IP_RAW mode)
|
||||
extern void close(SOCKET s); // Close socket
|
||||
extern uint8_t connect(SOCKET s, uint8_t * addr, uint16_t port); // Establish TCP connection (Active connection)
|
||||
extern void disconnect(SOCKET s); // disconnect the connection
|
||||
extern uint8_t listen(SOCKET s); // Establish TCP connection (Passive connection)
|
||||
extern uint16_t send(SOCKET s, const uint8_t * buf, uint16_t len); // Send data (TCP)
|
||||
extern int16_t recv(SOCKET s, uint8_t * buf, int16_t len); // Receive data (TCP)
|
||||
extern uint16_t peek(SOCKET s, uint8_t *buf);
|
||||
extern uint16_t sendto(SOCKET s, const uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t port); // Send data (UDP/IP RAW)
|
||||
extern uint16_t recvfrom(SOCKET s, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port); // Receive data (UDP/IP RAW)
|
||||
|
||||
extern uint16_t igmpsend(SOCKET s, const uint8_t * buf, uint16_t len);
|
||||
|
||||
// Functions to allow buffered UDP send (i.e. where the UDP datagram is built up over a
|
||||
// number of calls before being sent
|
||||
/*
|
||||
@brief This function sets up a UDP datagram, the data for which will be provided by one
|
||||
or more calls to bufferData and then finally sent with sendUDP.
|
||||
@return 1 if the datagram was successfully set up, or 0 if there was an error
|
||||
*/
|
||||
extern int startUDP(SOCKET s, uint8_t* addr, uint16_t port);
|
||||
/*
|
||||
@brief This function copies up to len bytes of data from buf into a UDP datagram to be
|
||||
sent later by sendUDP. Allows datagrams to be built up from a series of bufferData calls.
|
||||
@return Number of bytes successfully buffered
|
||||
*/
|
||||
uint16_t bufferData(SOCKET s, uint16_t offset, const uint8_t* buf, uint16_t len);
|
||||
/*
|
||||
@brief Send a UDP datagram built up from a sequence of startUDP followed by one or more
|
||||
calls to bufferData.
|
||||
@return 1 if the datagram was successfully sent, or 0 if there was an error
|
||||
*/
|
||||
int sendUDP(SOCKET s);
|
||||
|
||||
#endif
|
||||
/* _SOCKET_H_ */
|
@ -1,14 +0,0 @@
|
||||
|
||||
- make Firmata a subclass of HardwareSerial
|
||||
|
||||
- per-pin digital callback, since the per-port callback is a bit complicated
|
||||
for beginners (maybe Firmata is not for beginners...)
|
||||
|
||||
- simplify SimpleDigitalFirmata, take out the code that checks to see if the
|
||||
data has changed, since it is a bit complicated for this example. Ideally
|
||||
this example would be based on a call
|
||||
|
||||
- turn current SimpleDigitalFirmata into DigitalPortFirmata for a more complex
|
||||
example using the code which checks for changes before doing anything
|
||||
|
||||
- test integration with Wiring
|
@ -1,228 +0,0 @@
|
||||
/*
|
||||
* Firmata is a generic protocol for communicating with microcontrollers
|
||||
* from software on a host computer. It is intended to work with
|
||||
* any host computer software package.
|
||||
*
|
||||
* To download a host software package, please clink on the following link
|
||||
* to open the download page in your default browser.
|
||||
*
|
||||
* http://firmata.org/wiki/Download
|
||||
*/
|
||||
|
||||
/*
|
||||
Copyright (C) 2009 Jeff Hoefs. All rights reserved.
|
||||
Copyright (C) 2009 Shigeru Kobayashi. All rights reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
See file LICENSE.txt for further informations on licensing terms.
|
||||
*/
|
||||
|
||||
#include <Wire.h>
|
||||
#include <Firmata.h>
|
||||
|
||||
|
||||
#define I2C_WRITE B00000000
|
||||
#define I2C_READ B00001000
|
||||
#define I2C_READ_CONTINUOUSLY B00010000
|
||||
#define I2C_STOP_READING B00011000
|
||||
#define I2C_READ_WRITE_MODE_MASK B00011000
|
||||
|
||||
#define MAX_QUERIES 8
|
||||
|
||||
unsigned long currentMillis; // store the current value from millis()
|
||||
unsigned long previousMillis; // for comparison with currentMillis
|
||||
unsigned int samplingInterval = 32; // default sampling interval is 33ms
|
||||
unsigned int i2cReadDelayTime = 0; // default delay time between i2c read request and Wire.requestFrom()
|
||||
unsigned int powerPinsEnabled = 0; // use as boolean to prevent enablePowerPins from being called more than once
|
||||
|
||||
#define MINIMUM_SAMPLING_INTERVAL 10
|
||||
|
||||
#define REGISTER_NOT_SPECIFIED -1
|
||||
|
||||
struct i2c_device_info {
|
||||
byte addr;
|
||||
byte reg;
|
||||
byte bytes;
|
||||
};
|
||||
|
||||
i2c_device_info query[MAX_QUERIES];
|
||||
|
||||
byte i2cRxData[32];
|
||||
boolean readingContinuously = false;
|
||||
byte queryIndex = 0;
|
||||
|
||||
void readAndReportData(byte address, int theRegister, byte numBytes)
|
||||
{
|
||||
if (theRegister != REGISTER_NOT_SPECIFIED) {
|
||||
Wire.beginTransmission(address);
|
||||
Wire.write((byte)theRegister);
|
||||
Wire.endTransmission();
|
||||
delayMicroseconds(i2cReadDelayTime); // delay is necessary for some devices such as WiiNunchuck
|
||||
}
|
||||
else {
|
||||
theRegister = 0; // fill the register with a dummy value
|
||||
}
|
||||
|
||||
Wire.requestFrom(address, numBytes);
|
||||
|
||||
// check to be sure correct number of bytes were returned by slave
|
||||
if(numBytes == Wire.available()) {
|
||||
i2cRxData[0] = address;
|
||||
i2cRxData[1] = theRegister;
|
||||
for (int i = 0; i < numBytes; i++) {
|
||||
i2cRxData[2 + i] = Wire.read();
|
||||
}
|
||||
// send slave address, register and received bytes
|
||||
Firmata.sendSysex(I2C_REPLY, numBytes + 2, i2cRxData);
|
||||
}
|
||||
else {
|
||||
if(numBytes > Wire.available()) {
|
||||
Firmata.sendString("I2C Read Error: Too many bytes received");
|
||||
} else {
|
||||
Firmata.sendString("I2C Read Error: Too few bytes received");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void sysexCallback(byte command, byte argc, byte *argv)
|
||||
{
|
||||
byte mode;
|
||||
byte slaveAddress;
|
||||
byte slaveRegister;
|
||||
byte data;
|
||||
int delayTime;
|
||||
|
||||
if (command == I2C_REQUEST) {
|
||||
mode = argv[1] & I2C_READ_WRITE_MODE_MASK;
|
||||
slaveAddress = argv[0];
|
||||
|
||||
switch(mode) {
|
||||
case I2C_WRITE:
|
||||
Wire.beginTransmission(slaveAddress);
|
||||
for (byte i = 2; i < argc; i += 2) {
|
||||
data = argv[i] + (argv[i + 1] << 7);
|
||||
Wire.write(data);
|
||||
}
|
||||
Wire.endTransmission();
|
||||
delayMicroseconds(70); // TODO is this needed?
|
||||
break;
|
||||
case I2C_READ:
|
||||
if (argc == 6) {
|
||||
// a slave register is specified
|
||||
slaveRegister = argv[2] + (argv[3] << 7);
|
||||
data = argv[4] + (argv[5] << 7); // bytes to read
|
||||
readAndReportData(slaveAddress, (int)slaveRegister, data);
|
||||
}
|
||||
else {
|
||||
// a slave register is NOT specified
|
||||
data = argv[2] + (argv[3] << 7); // bytes to read
|
||||
readAndReportData(slaveAddress, (int)REGISTER_NOT_SPECIFIED, data);
|
||||
}
|
||||
break;
|
||||
case I2C_READ_CONTINUOUSLY:
|
||||
if ((queryIndex + 1) >= MAX_QUERIES) {
|
||||
// too many queries, just ignore
|
||||
Firmata.sendString("too many queries");
|
||||
break;
|
||||
}
|
||||
query[queryIndex].addr = slaveAddress;
|
||||
query[queryIndex].reg = argv[2] + (argv[3] << 7);
|
||||
query[queryIndex].bytes = argv[4] + (argv[5] << 7);
|
||||
readingContinuously = true;
|
||||
queryIndex++;
|
||||
break;
|
||||
case I2C_STOP_READING:
|
||||
readingContinuously = false;
|
||||
queryIndex = 0;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if (command == SAMPLING_INTERVAL) {
|
||||
samplingInterval = argv[0] + (argv[1] << 7);
|
||||
|
||||
if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) {
|
||||
samplingInterval = MINIMUM_SAMPLING_INTERVAL;
|
||||
}
|
||||
|
||||
samplingInterval -= 1;
|
||||
Firmata.sendString("sampling interval");
|
||||
}
|
||||
|
||||
else if (command == I2C_CONFIG) {
|
||||
delayTime = (argv[4] + (argv[5] << 7)); // MSB
|
||||
delayTime = (delayTime << 8) + (argv[2] + (argv[3] << 7)); // add LSB
|
||||
|
||||
if((argv[0] + (argv[1] << 7)) > 0) {
|
||||
enablePowerPins(PORTC3, PORTC2);
|
||||
}
|
||||
|
||||
if(delayTime > 0) {
|
||||
i2cReadDelayTime = delayTime;
|
||||
}
|
||||
|
||||
if(argc > 6) {
|
||||
// If you extend I2C_Config, handle your data here
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
void systemResetCallback()
|
||||
{
|
||||
readingContinuously = false;
|
||||
queryIndex = 0;
|
||||
}
|
||||
|
||||
/* reference: BlinkM_funcs.h by Tod E. Kurt, ThingM, http://thingm.com/ */
|
||||
// Enables Pins A2 and A3 to be used as GND and Power
|
||||
// so that I2C devices can be plugged directly
|
||||
// into Arduino header (pins A2 - A5)
|
||||
static void enablePowerPins(byte pwrpin, byte gndpin)
|
||||
{
|
||||
if(powerPinsEnabled == 0) {
|
||||
DDRC |= _BV(pwrpin) | _BV(gndpin);
|
||||
PORTC &=~ _BV(gndpin);
|
||||
PORTC |= _BV(pwrpin);
|
||||
powerPinsEnabled = 1;
|
||||
Firmata.sendString("Power pins enabled");
|
||||
delay(100);
|
||||
}
|
||||
}
|
||||
|
||||
void setup()
|
||||
{
|
||||
Firmata.setFirmwareVersion(2, 0);
|
||||
|
||||
Firmata.attach(START_SYSEX, sysexCallback);
|
||||
Firmata.attach(SYSTEM_RESET, systemResetCallback);
|
||||
|
||||
for (int i = 0; i < TOTAL_PINS; ++i) {
|
||||
pinMode(i, OUTPUT);
|
||||
}
|
||||
|
||||
Firmata.begin(57600);
|
||||
Wire.begin();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
while (Firmata.available()) {
|
||||
Firmata.processInput();
|
||||
}
|
||||
|
||||
currentMillis = millis();
|
||||
if (currentMillis - previousMillis > samplingInterval) {
|
||||
previousMillis += samplingInterval;
|
||||
|
||||
for (byte i = 0; i < queryIndex; i++) {
|
||||
readAndReportData(query[i].addr, query[i].reg, query[i].bytes);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,162 +0,0 @@
|
||||
/*
|
||||
GSM Twitter Client with Strings
|
||||
|
||||
This sketch connects to Twitter using an Arduino GSM shield.
|
||||
It parses the XML returned, and looks for the string <text>this is a tweet</text>
|
||||
|
||||
This example uses the String library, which is part of the Arduino core from
|
||||
version 0019.
|
||||
|
||||
Circuit:
|
||||
* GSM shield attached to an Arduino
|
||||
* SIM card with a data plan
|
||||
|
||||
created 8 Mar 2012
|
||||
by Tom Igoe
|
||||
|
||||
http://arduino.cc/en/Tutorial/GSMExamplesTwitterClient
|
||||
|
||||
This code is in the public domain.
|
||||
|
||||
*/
|
||||
|
||||
// libraries
|
||||
#include <GSM.h>
|
||||
|
||||
// PIN Number
|
||||
#define PINNUMBER ""
|
||||
|
||||
// APN data
|
||||
#define GPRS_APN "APN" // replace your GPRS APN
|
||||
#define GPRS_LOGIN "LOGIN" // replace with your GPRS login
|
||||
#define GPRS_PASSWORD "PASSWORD" // replace with your GPRS password
|
||||
|
||||
// initialize the library instance
|
||||
GSMClient client;
|
||||
GPRS gprs;
|
||||
GSM gsmAccess;
|
||||
|
||||
const unsigned long requestInterval = 30*1000; // delay between requests: 30 seconds
|
||||
|
||||
// API Twitter URL
|
||||
char server[] = "api.twitter.com";
|
||||
|
||||
boolean requested; // whether you've made a request since connecting
|
||||
unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds
|
||||
|
||||
String currentLine = ""; // string to hold the text from server
|
||||
String tweet = ""; // string to hold the tweet
|
||||
boolean readingTweet = false; // if you're currently reading the tweet
|
||||
|
||||
void setup()
|
||||
{
|
||||
// reserve space for the strings:
|
||||
currentLine.reserve(256);
|
||||
tweet.reserve(150);
|
||||
|
||||
// initialize serial communications and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for Leonardo only
|
||||
}
|
||||
|
||||
// connection state
|
||||
boolean notConnected = true;
|
||||
|
||||
// After starting the modem with GSM.begin()
|
||||
// attach the shield to the GPRS network with the APN, login and password
|
||||
while(notConnected)
|
||||
{
|
||||
if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
|
||||
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
|
||||
notConnected = false;
|
||||
else
|
||||
{
|
||||
Serial.println("Not connected");
|
||||
delay(1000);
|
||||
}
|
||||
}
|
||||
|
||||
Serial.println("Connected to GPRS network");
|
||||
|
||||
Serial.println("connecting...");
|
||||
connectToServer();
|
||||
}
|
||||
|
||||
|
||||
|
||||
void loop()
|
||||
{
|
||||
char c;
|
||||
if (client.connected())
|
||||
{
|
||||
if (client.available())
|
||||
{
|
||||
// read incoming bytes:
|
||||
char inChar = client.read();
|
||||
|
||||
// add incoming byte to end of line:
|
||||
currentLine += inChar;
|
||||
|
||||
// if you get a newline, clear the line:
|
||||
if (inChar == '\n')
|
||||
{
|
||||
currentLine = "";
|
||||
}
|
||||
|
||||
// if the current line ends with <text>, it will
|
||||
// be followed by the tweet:
|
||||
if (currentLine.endsWith("<text>"))
|
||||
{
|
||||
// tweet is beginning. Clear the tweet string:
|
||||
readingTweet = true;
|
||||
tweet = "";
|
||||
}
|
||||
|
||||
// if you're currently reading the bytes of a tweet,
|
||||
// add them to the tweet String:
|
||||
if (readingTweet)
|
||||
{
|
||||
if (inChar != '<')
|
||||
{
|
||||
tweet += inChar;
|
||||
}
|
||||
else
|
||||
{
|
||||
// if you got a "<" character,
|
||||
// you've reached the end of the tweet:
|
||||
readingTweet = false;
|
||||
Serial.println(tweet);
|
||||
|
||||
// close the connection to the server:
|
||||
client.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (millis() - lastAttemptTime > requestInterval)
|
||||
{
|
||||
// if you're not connected, and two minutes have passed since
|
||||
// your last connection, then attempt to connect again:
|
||||
connectToServer();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Connect to API Twitter server and do a request for timeline
|
||||
*/
|
||||
void connectToServer()
|
||||
{
|
||||
// attempt to connect, and wait a millisecond:
|
||||
Serial.println("connecting to server...");
|
||||
if (client.connect(server, 80))
|
||||
{
|
||||
Serial.println("making HTTP request...");
|
||||
// make HTTP GET request to twitter:
|
||||
client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino&count=1 HTTP/1.1");
|
||||
client.println("HOST: api.twitter.com");
|
||||
client.println();
|
||||
}
|
||||
// note the time of this connect attempt:
|
||||
lastAttemptTime = millis();
|
||||
}
|
@ -1,103 +0,0 @@
|
||||
/* 6 Wheel Calibration
|
||||
|
||||
Use this sketch to calibrate the wheels in your robot.
|
||||
Your robot should drive as straight as possible when
|
||||
putting both motors at the same speed.
|
||||
|
||||
Run the software and follow the on-screen instructions.
|
||||
Use the trimmer on the motor board to make sure the
|
||||
robot is working at its best!
|
||||
Circuit:
|
||||
* Arduino Robot
|
||||
|
||||
created 1 May 2013
|
||||
by X. Yang
|
||||
modified 12 May 2013
|
||||
by D. Cuartielles
|
||||
|
||||
This example is in the public domain
|
||||
*/
|
||||
|
||||
#include <ArduinoRobot.h> // inport the robot librsry
|
||||
// import the utility library
|
||||
// a description of its funtionality is below
|
||||
#include <utility/RobotTextManager.h>
|
||||
|
||||
// arrays to hold the text for instructions
|
||||
char script1[] ="Wheel Calibration";
|
||||
char script2[] ="1. Put Robot on a\n flat surface";
|
||||
char script3[] ="2. Adjust speed with the knob on top";
|
||||
char script4[] ="3. If robot goes\n straight, it's done";
|
||||
char script5[] ="4. Use screwdriver\n on the bottom trim";
|
||||
char script6[] ="- Robot turns left,\n screw it clockwise;";
|
||||
char script7[] ="- Turns right, screw it ct-colockwise;";
|
||||
char script8[] ="5. Repeat 4 until\n going straight";
|
||||
|
||||
int speedRobot; //robot speed
|
||||
int calibrationValue; //value for calibrate difference between wheels
|
||||
|
||||
void setup(){
|
||||
//necessary initialization sequence
|
||||
Robot.begin();
|
||||
Robot.beginTFT();
|
||||
Robot.beginSD();
|
||||
|
||||
// left and top margin for displaying text
|
||||
// see below for a description of this
|
||||
textManager.setMargin(5,5);
|
||||
// write all instructions at once
|
||||
writeAllscript();
|
||||
|
||||
}
|
||||
void loop(){
|
||||
//Control the robot's speed with knob on top
|
||||
int speedRobot=map(Robot.knobRead(),0,1023,-255,255);
|
||||
Robot.motorsWrite(speedRobot,speedRobot);
|
||||
|
||||
//read value of the pot on motor baord,to clibrate the wheels
|
||||
int calibrationValue=map(Robot.trimRead(),0,1023,-30,30);
|
||||
// print the values to the screen
|
||||
Robot.debugPrint(calibrationValue,110,145);
|
||||
delay(40);
|
||||
|
||||
}
|
||||
|
||||
void writeAllscript(){
|
||||
//prints 8 scripts one after another
|
||||
textManager.writeText(0,0,script1);
|
||||
textManager.writeText(1,0,script2);
|
||||
textManager.writeText(3,0,script3);
|
||||
textManager.writeText(5,0,script4);
|
||||
textManager.writeText(7,0,script5);
|
||||
textManager.writeText(9,0,script6);
|
||||
textManager.writeText(11,0,script7);
|
||||
textManager.writeText(13,0,script8);
|
||||
}
|
||||
|
||||
/**
|
||||
textManager mostly contains helper functions for
|
||||
R06_Wheel_Calibration and R01_Hello_User.
|
||||
|
||||
textManager.setMargin(margin_left, margin_top):
|
||||
Configure the left and top margin for text
|
||||
display. The margins will be used by
|
||||
textManager.writeText().
|
||||
Parameters:
|
||||
margin_left, margin_top: int, the margin values
|
||||
from the top and left side of the screen.
|
||||
Returns:
|
||||
none
|
||||
|
||||
textManager.writeText(line,column,text):
|
||||
Display text on the specific line and column.
|
||||
It's different from Robot.text() which
|
||||
uses pixels for positioning the text.
|
||||
Parameters:
|
||||
line:int, which line is the text displayed. Each line
|
||||
is 10px high.
|
||||
column:int, which column is the text displayed. Each
|
||||
column is 8px wide.
|
||||
text:a char array(string) of the text to be displayed.
|
||||
Returns:
|
||||
none
|
||||
*/
|
@ -1,123 +0,0 @@
|
||||
/* 08 Remote Control
|
||||
|
||||
*******************
|
||||
***
|
||||
***This example code is in an experimental state.
|
||||
***You are welcome to try this with your robot,
|
||||
***and no harm will come to it. We will provide a
|
||||
***detailed description of an updated version of this
|
||||
***in a future update
|
||||
***
|
||||
*** For this example to work you need:
|
||||
***
|
||||
*** - download and install the IR-Remote library by Ken Shirriff
|
||||
*** to be found at https://github.com/shirriff/Arduino-IRremote
|
||||
*** - get a Sony remote control
|
||||
***
|
||||
*** This example will be updated soon, come back to the Robot
|
||||
*** page on the Arduino server for updates!!
|
||||
***
|
||||
*******************
|
||||
|
||||
If you connect a IR receiver to the robot,
|
||||
you can control it like you control a TV set.
|
||||
Using a Sony compatiable remote control,
|
||||
map some buttons to different actions.
|
||||
You can make the robot move around without
|
||||
even touching it!
|
||||
|
||||
Circuit:
|
||||
* Arduino Robot
|
||||
* Connect the IRreceiver to TDK2
|
||||
* Sony compatible remote control
|
||||
|
||||
based on the IRremote library
|
||||
by Ken Shirriff
|
||||
http://arcfn.com
|
||||
|
||||
created 1 May 2013
|
||||
by X. Yang
|
||||
modified 12 May 2013
|
||||
by D. Cuartielles
|
||||
|
||||
This example is in the public domain
|
||||
*/
|
||||
|
||||
// include the necessary libraries
|
||||
#include <IRremote.h>
|
||||
#include <ArduinoRobot.h>
|
||||
|
||||
// Define a few commands from your remote control
|
||||
#define IR_CODE_FORWARD 0x2C9B
|
||||
#define IR_CODE_BACKWARDS 0x6C9B
|
||||
#define IR_CODE_TURN_LEFT 0xD4B8F
|
||||
#define IR_CODE_TURN_RIGHT 0x34B8F
|
||||
|
||||
int RECV_PIN = TKD2; // the pin the IR receiver is connected to
|
||||
IRrecv irrecv(RECV_PIN); // an instance of the IR receiver object
|
||||
decode_results results; // container for received IR codes
|
||||
|
||||
void setup() {
|
||||
// initialize the Robot, SD card, display, and speaker
|
||||
Robot.begin();
|
||||
Robot.beginTFT();
|
||||
Robot.beginSD();
|
||||
|
||||
// print some text to the screen
|
||||
Robot.stroke(0, 0, 0);
|
||||
Robot.text("Remote Control code:", 5, 5);
|
||||
Robot.text("Command:", 5, 26);
|
||||
irrecv.enableIRIn(); // Start the receiver
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// if there is an IR command, process it
|
||||
if (irrecv.decode(&results)) {
|
||||
processResult();
|
||||
irrecv.resume(); // resume receiver
|
||||
}
|
||||
}
|
||||
|
||||
void processResult() {
|
||||
unsigned long res = results.value;
|
||||
// print the value to the screen
|
||||
Robot.debugPrint(res, 5, 15);
|
||||
|
||||
if(res == IR_CODE_FORWARD || res == IR_CODE_BACKWARDS || res == IR_CODE_TURN_LEFT || res == IR_CODE_TURN_RIGHT) {
|
||||
Robot.fill(255, 255, 255);
|
||||
Robot.stroke(255, 255, 255);
|
||||
|
||||
Robot.rect(5, 36, 55, 10);
|
||||
}
|
||||
switch(results.value){
|
||||
case IR_CODE_FORWARD:
|
||||
Robot.stroke(0, 0, 0);
|
||||
Robot.text("Forward", 5, 36);
|
||||
Robot.motorsWrite(255, 255);
|
||||
delay(300);
|
||||
Robot.motorsStop();
|
||||
break;
|
||||
case IR_CODE_BACKWARDS:
|
||||
Robot.stroke(0, 0, 0);
|
||||
Robot.text("Backwards", 5, 36);
|
||||
Robot.motorsWrite(-255, -255);
|
||||
delay(300);
|
||||
Robot.motorsStop();
|
||||
break;
|
||||
case IR_CODE_TURN_LEFT:
|
||||
Robot.stroke(0, 0, 0);
|
||||
Robot.text("Left", 5, 36);
|
||||
Robot.motorsWrite(-255, 255);
|
||||
delay(100);
|
||||
Robot.motorsStop();
|
||||
break;
|
||||
case IR_CODE_TURN_RIGHT:
|
||||
Robot.stroke(0, 0, 0);
|
||||
Robot.text("Right", 5, 36);
|
||||
Robot.motorsWrite(255, -255);
|
||||
delay(100);
|
||||
Robot.motorsStop();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
@ -1,126 +0,0 @@
|
||||
/*
|
||||
|
||||
This example connects to a WEP-encrypted Wifi network.
|
||||
Then it prints the MAC address of the Wifi shield,
|
||||
the IP address obtained, and other network details.
|
||||
|
||||
If you use 40-bit WEP, you need a key that is 10 characters long,
|
||||
and the characters must be hexadecimal (0-9 or A-F).
|
||||
e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work
|
||||
(too short) and ABBAISDEAF won't work (I and S are not
|
||||
hexadecimal characters).
|
||||
|
||||
For 128-bit, you need a string that is 26 characters long.
|
||||
D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters,
|
||||
all in the 0-9, A-F range.
|
||||
|
||||
Circuit:
|
||||
* WiFi shield attached
|
||||
|
||||
created 13 July 2010
|
||||
by dlf (Metodo2 srl)
|
||||
modified 31 May 2012
|
||||
by Tom Igoe
|
||||
*/
|
||||
#include <WiFi.h>
|
||||
|
||||
char ssid[] = "yourNetwork"; // your network SSID (name)
|
||||
char key[] = "D0D0DEADF00DABBADEAFBEADED"; // your network key
|
||||
int keyIndex = 0; // your network key Index number
|
||||
int status = WL_IDLE_STATUS; // the Wifi radio's status
|
||||
|
||||
void setup() {
|
||||
//Initialize serial and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for Leonardo only
|
||||
}
|
||||
|
||||
// check for the presence of the shield:
|
||||
if (WiFi.status() == WL_NO_SHIELD) {
|
||||
Serial.println("WiFi shield not present");
|
||||
// don't continue:
|
||||
while(true);
|
||||
}
|
||||
|
||||
// attempt to connect to Wifi network:
|
||||
while ( status != WL_CONNECTED) {
|
||||
Serial.print("Attempting to connect to WEP network, SSID: ");
|
||||
Serial.println(ssid);
|
||||
status = WiFi.begin(ssid, keyIndex, key);
|
||||
|
||||
// wait 10 seconds for connection:
|
||||
delay(10000);
|
||||
}
|
||||
|
||||
// once you are connected :
|
||||
Serial.print("You're connected to the network");
|
||||
printCurrentNet();
|
||||
printWifiData();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// check the network connection once every 10 seconds:
|
||||
delay(10000);
|
||||
printCurrentNet();
|
||||
}
|
||||
|
||||
void printWifiData() {
|
||||
// print your WiFi shield's IP address:
|
||||
IPAddress ip = WiFi.localIP();
|
||||
Serial.print("IP Address: ");
|
||||
Serial.println(ip);
|
||||
Serial.println(ip);
|
||||
|
||||
// print your MAC address:
|
||||
byte mac[6];
|
||||
WiFi.macAddress(mac);
|
||||
Serial.print("MAC address: ");
|
||||
Serial.print(mac[5],HEX);
|
||||
Serial.print(":");
|
||||
Serial.print(mac[4],HEX);
|
||||
Serial.print(":");
|
||||
Serial.print(mac[3],HEX);
|
||||
Serial.print(":");
|
||||
Serial.print(mac[2],HEX);
|
||||
Serial.print(":");
|
||||
Serial.print(mac[1],HEX);
|
||||
Serial.print(":");
|
||||
Serial.println(mac[0],HEX);
|
||||
}
|
||||
|
||||
void printCurrentNet() {
|
||||
// print the SSID of the network you're attached to:
|
||||
Serial.print("SSID: ");
|
||||
Serial.println(WiFi.SSID());
|
||||
|
||||
// print the MAC address of the router you're attached to:
|
||||
byte bssid[6];
|
||||
WiFi.BSSID(bssid);
|
||||
Serial.print("BSSID: ");
|
||||
Serial.print(bssid[5],HEX);
|
||||
Serial.print(":");
|
||||
Serial.print(bssid[4],HEX);
|
||||
Serial.print(":");
|
||||
Serial.print(bssid[3],HEX);
|
||||
Serial.print(":");
|
||||
Serial.print(bssid[2],HEX);
|
||||
Serial.print(":");
|
||||
Serial.print(bssid[1],HEX);
|
||||
Serial.print(":");
|
||||
Serial.println(bssid[0],HEX);
|
||||
|
||||
// print the received signal strength:
|
||||
long rssi = WiFi.RSSI();
|
||||
Serial.print("signal strength (RSSI):");
|
||||
Serial.println(rssi);
|
||||
|
||||
// print the encryption type:
|
||||
byte encryption = WiFi.encryptionType();
|
||||
Serial.print("Encryption Type:");
|
||||
Serial.println(encryption,HEX);
|
||||
Serial.println();
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,129 +0,0 @@
|
||||
/*
|
||||
WiFi Web Server LED Blink
|
||||
|
||||
A simple web server that lets you blink an LED via the web.
|
||||
This sketch will print the IP address of your WiFi Shield (once connected)
|
||||
to the Serial monitor. From there, you can open that address in a web browser
|
||||
to turn on and off the LED on pin 9.
|
||||
|
||||
If the IP address of your shield is yourAddress:
|
||||
http://yourAddress/H turns the LED on
|
||||
http://yourAddress/L turns it off
|
||||
|
||||
This example is written for a network using WPA encryption. For
|
||||
WEP or WPA, change the Wifi.begin() call accordingly.
|
||||
|
||||
Circuit:
|
||||
* WiFi shield attached
|
||||
* LED attached to pin 9
|
||||
|
||||
created 25 Nov 2012
|
||||
by Tom Igoe
|
||||
*/
|
||||
#include <SPI.h>
|
||||
#include <WiFi.h>
|
||||
|
||||
char ssid[] = "yourNetwork"; // your network SSID (name)
|
||||
char pass[] = "secretPassword"; // your network password
|
||||
int keyIndex = 0; // your network key Index number (needed only for WEP)
|
||||
|
||||
int status = WL_IDLE_STATUS;
|
||||
WiFiServer server(80);
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600); // initialize serial communication
|
||||
pinMode(9, OUTPUT); // set the LED pin mode
|
||||
|
||||
// check for the presence of the shield:
|
||||
if (WiFi.status() == WL_NO_SHIELD) {
|
||||
Serial.println("WiFi shield not present");
|
||||
while(true); // don't continue
|
||||
}
|
||||
|
||||
// attempt to connect to Wifi network:
|
||||
while ( status != WL_CONNECTED) {
|
||||
Serial.print("Attempting to connect to Network named: ");
|
||||
Serial.println(ssid); // print the network name (SSID);
|
||||
|
||||
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
|
||||
status = WiFi.begin(ssid, pass);
|
||||
// wait 10 seconds for connection:
|
||||
delay(10000);
|
||||
}
|
||||
server.begin(); // start the web server on port 80
|
||||
printWifiStatus(); // you're connected now, so print out the status
|
||||
}
|
||||
|
||||
|
||||
void loop() {
|
||||
WiFiClient client = server.available(); // listen for incoming clients
|
||||
|
||||
if (client) { // if you get a client,
|
||||
Serial.println("new client"); // print a message out the serial port
|
||||
String currentLine = ""; // make a String to hold incoming data from the client
|
||||
while (client.connected()) { // loop while the client's connected
|
||||
if (client.available()) { // if there's bytes to read from the client,
|
||||
char c = client.read(); // read a byte, then
|
||||
Serial.write(c); // print it out the serial monitor
|
||||
if (c == '\n') { // if the byte is a newline character
|
||||
|
||||
// if the current line is blank, you got two newline characters in a row.
|
||||
// that's the end of the client HTTP request, so send a response:
|
||||
if (currentLine.length() == 0) {
|
||||
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
|
||||
// and a content-type so the client knows what's coming, then a blank line:
|
||||
client.println("HTTP/1.1 200 OK");
|
||||
client.println("Content-type:text/html");
|
||||
client.println();
|
||||
|
||||
// the content of the HTTP response follows the header:
|
||||
client.print("Click <a href=\"/H\">here</a> turn the LED on pin 9 on<br>");
|
||||
client.print("Click <a href=\"/L\">here</a> turn the LED on pin 9 off<br>");
|
||||
|
||||
// The HTTP response ends with another blank line:
|
||||
client.println();
|
||||
// break out of the while loop:
|
||||
break;
|
||||
}
|
||||
else { // if you got a newline, then clear currentLine:
|
||||
currentLine = "";
|
||||
}
|
||||
}
|
||||
else if (c != '\r') { // if you got anything else but a carriage return character,
|
||||
currentLine += c; // add it to the end of the currentLine
|
||||
}
|
||||
|
||||
// Check to see if the client request was "GET /H" or "GET /L":
|
||||
if (currentLine.endsWith("GET /H")) {
|
||||
digitalWrite(9, HIGH); // GET /H turns the LED on
|
||||
}
|
||||
if (currentLine.endsWith("GET /L")) {
|
||||
digitalWrite(9, LOW); // GET /L turns the LED off
|
||||
}
|
||||
}
|
||||
}
|
||||
// close the connection:
|
||||
client.stop();
|
||||
Serial.println("client disonnected");
|
||||
}
|
||||
}
|
||||
|
||||
void printWifiStatus() {
|
||||
// print the SSID of the network you're attached to:
|
||||
Serial.print("SSID: ");
|
||||
Serial.println(WiFi.SSID());
|
||||
|
||||
// print your WiFi shield's IP address:
|
||||
IPAddress ip = WiFi.localIP();
|
||||
Serial.print("IP Address: ");
|
||||
Serial.println(ip);
|
||||
|
||||
// print the received signal strength:
|
||||
long rssi = WiFi.RSSI();
|
||||
Serial.print("signal strength (RSSI):");
|
||||
Serial.print(rssi);
|
||||
Serial.println(" dBm");
|
||||
// print where to go in a browser:
|
||||
Serial.print("To see this page in action, open a browser to http://");
|
||||
Serial.println(ip);
|
||||
}
|
@ -1,163 +0,0 @@
|
||||
/*
|
||||
Wifi Twitter Client with Strings
|
||||
|
||||
This sketch connects to Twitter using using an Arduino WiFi shield.
|
||||
It parses the XML returned, and looks for <text>this is a tweet</text>
|
||||
|
||||
This example is written for a network using WPA encryption. For
|
||||
WEP or WPA, change the Wifi.begin() call accordingly.
|
||||
|
||||
This example uses the String library, which is part of the Arduino core from
|
||||
version 0019.
|
||||
|
||||
Circuit:
|
||||
* WiFi shield attached to pins 10, 11, 12, 13
|
||||
|
||||
created 23 apr 2012
|
||||
modified 31 May 2012
|
||||
by Tom Igoe
|
||||
|
||||
This code is in the public domain.
|
||||
|
||||
*/
|
||||
#include <SPI.h>
|
||||
#include <WiFi.h>
|
||||
|
||||
char ssid[] = "yourNetwork"; // your network SSID (name)
|
||||
char pass[] = "password"; // your network password (use for WPA, or use as key for WEP)
|
||||
int keyIndex = 0; // your network key Index number (needed only for WEP)
|
||||
|
||||
int status = WL_IDLE_STATUS; // status of the wifi connection
|
||||
|
||||
// initialize the library instance:
|
||||
WiFiClient client;
|
||||
|
||||
const unsigned long requestInterval = 30*1000; // delay between requests; 30 seconds
|
||||
|
||||
// if you don't want to use DNS (and reduce your sketch size)
|
||||
// use the numeric IP instead of the name for the server:
|
||||
//IPAddress server(199,59,149,200); // numeric IP for api.twitter.com
|
||||
char server[] = "api.twitter.com"; // name address for twitter API
|
||||
|
||||
boolean requested; // whether you've made a request since connecting
|
||||
unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds
|
||||
|
||||
String currentLine = ""; // string to hold the text from server
|
||||
String tweet = ""; // string to hold the tweet
|
||||
boolean readingTweet = false; // if you're currently reading the tweet
|
||||
|
||||
void setup() {
|
||||
// reserve space for the strings:
|
||||
currentLine.reserve(256);
|
||||
tweet.reserve(150);
|
||||
//Initialize serial and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for Leonardo only
|
||||
}
|
||||
|
||||
// check for the presence of the shield:
|
||||
if (WiFi.status() == WL_NO_SHIELD) {
|
||||
Serial.println("WiFi shield not present");
|
||||
// don't continue:
|
||||
while(true);
|
||||
}
|
||||
|
||||
// attempt to connect to Wifi network:
|
||||
while ( status != WL_CONNECTED) {
|
||||
Serial.print("Attempting to connect to SSID: ");
|
||||
Serial.println(ssid);
|
||||
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
|
||||
status = WiFi.begin(ssid, pass);
|
||||
|
||||
// wait 10 seconds for connection:
|
||||
delay(10000);
|
||||
}
|
||||
// you're connected now, so print out the status:
|
||||
printWifiStatus();
|
||||
connectToServer();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
if (client.connected()) {
|
||||
if (client.available()) {
|
||||
// read incoming bytes:
|
||||
char inChar = client.read();
|
||||
|
||||
// add incoming byte to end of line:
|
||||
currentLine += inChar;
|
||||
|
||||
// if you get a newline, clear the line:
|
||||
if (inChar == '\n') {
|
||||
currentLine = "";
|
||||
}
|
||||
// if the current line ends with <text>, it will
|
||||
// be followed by the tweet:
|
||||
if ( currentLine.endsWith("<text>")) {
|
||||
// tweet is beginning. Clear the tweet string:
|
||||
readingTweet = true;
|
||||
tweet = "";
|
||||
// break out of the loop so this character isn't added to the tweet:
|
||||
return;
|
||||
}
|
||||
// if you're currently reading the bytes of a tweet,
|
||||
// add them to the tweet String:
|
||||
if (readingTweet) {
|
||||
if (inChar != '<') {
|
||||
tweet += inChar;
|
||||
}
|
||||
else {
|
||||
// if you got a "<" character,
|
||||
// you've reached the end of the tweet:
|
||||
readingTweet = false;
|
||||
Serial.println(tweet);
|
||||
// close the connection to the server:
|
||||
client.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (millis() - lastAttemptTime > requestInterval) {
|
||||
// if you're not connected, and two minutes have passed since
|
||||
// your last connection, then attempt to connect again:
|
||||
connectToServer();
|
||||
}
|
||||
}
|
||||
|
||||
void connectToServer() {
|
||||
// attempt to connect, and wait a millisecond:
|
||||
Serial.println("connecting to server...");
|
||||
if (client.connect(server, 80)) {
|
||||
Serial.println("making HTTP request...");
|
||||
// make HTTP GET request to twitter:
|
||||
client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino HTTP/1.1");
|
||||
client.println("Host: api.twitter.com");
|
||||
client.println("Connection: close");
|
||||
client.println();
|
||||
}
|
||||
// note the time of this connect attempt:
|
||||
lastAttemptTime = millis();
|
||||
}
|
||||
|
||||
|
||||
void printWifiStatus() {
|
||||
// print the SSID of the network you're attached to:
|
||||
Serial.print("SSID: ");
|
||||
Serial.println(WiFi.SSID());
|
||||
|
||||
// print your WiFi shield's IP address:
|
||||
IPAddress ip = WiFi.localIP();
|
||||
Serial.print("IP Address: ");
|
||||
Serial.println(ip);
|
||||
|
||||
// print the received signal strength:
|
||||
long rssi = WiFi.RSSI();
|
||||
Serial.print("signal strength (RSSI):");
|
||||
Serial.print(rssi);
|
||||
Serial.println(" dBm");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
@ -91,4 +91,4 @@ tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verb
|
||||
# Default blank usb manufacturer will be filled it at compile time
|
||||
# - from numeric vendor ID, set to Unknown otherwise
|
||||
build.usb_manufacturer=
|
||||
build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} -DUSB_MANUFACTURER={build.usb_manufacturer} '-DUSB_PRODUCT={build.usb_product}'
|
||||
build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'
|
||||
|
@ -36,6 +36,13 @@
|
||||
#define RXLED0 PORTB |= (1<<0)
|
||||
#define RXLED1 PORTB &= ~(1<<0)
|
||||
|
||||
#define D0 TKD0
|
||||
#define D1 TKD1
|
||||
#define D2 TKD2
|
||||
#define D3 TKD3
|
||||
#define D4 TKD4
|
||||
#define D5 TKD5
|
||||
|
||||
static const uint8_t RX = 0;
|
||||
static const uint8_t TX = 1;
|
||||
static const uint8_t SDA = 2;
|
||||
|
@ -36,6 +36,11 @@
|
||||
#define RXLED0 PORTB |= (1<<0)
|
||||
#define RXLED1 PORTB &= ~(1<<0)
|
||||
|
||||
#define D10 TK1
|
||||
#define D9 TK2
|
||||
#define D8 TK4
|
||||
#define D7 TK3
|
||||
|
||||
static const uint8_t RX = 0;
|
||||
static const uint8_t TX = 1;
|
||||
static const uint8_t SDA = 2;
|
||||
|
@ -135,7 +135,6 @@ inline void String::init(void)
|
||||
buffer = NULL;
|
||||
capacity = 0;
|
||||
len = 0;
|
||||
flags = 0;
|
||||
}
|
||||
|
||||
void String::invalidate(void)
|
||||
|
@ -191,7 +191,6 @@ protected:
|
||||
char *buffer; // the actual char array
|
||||
unsigned int capacity; // the array length minus one (for the '\0')
|
||||
unsigned int len; // the String length (not counting the '\0')
|
||||
unsigned char flags; // unused, for future features
|
||||
protected:
|
||||
void init(void);
|
||||
void invalidate(void);
|
||||
|
Binary file not shown.
@ -1,732 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2013 Arduino. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
|
||||
#include "CAN.h"
|
||||
#include "sn65hvd234.h"
|
||||
|
||||
/** Define the timemark mask. */
|
||||
#define TIMEMARK_MASK 0x0000ffff
|
||||
|
||||
/* CAN timeout for synchronization. */
|
||||
#define CAN_TIMEOUT 100000
|
||||
|
||||
/** The max value for CAN baudrate prescale. */
|
||||
#define CAN_BAUDRATE_MAX_DIV 128
|
||||
|
||||
/** Define the scope for TQ. */
|
||||
#define CAN_MIN_TQ_NUM 8
|
||||
#define CAN_MAX_TQ_NUM 25
|
||||
|
||||
/** Define the fixed bit time value. */
|
||||
#define CAN_BIT_SYNC 1
|
||||
#define CAN_BIT_IPT 2
|
||||
|
||||
typedef struct {
|
||||
uint8_t uc_tq; //! CAN_BIT_SYNC + uc_prog + uc_phase1 + uc_phase2 = uc_tq, 8 <= uc_tq <= 25.
|
||||
uint8_t uc_prog; //! Propagation segment, (3-bits + 1), 1~8;
|
||||
uint8_t uc_phase1; //! Phase segment 1, (3-bits + 1), 1~8;
|
||||
uint8_t uc_phase2; //! Phase segment 2, (3-bits + 1), 1~8, CAN_BIT_IPT <= uc_phase2;
|
||||
uint8_t uc_sjw; //! Resynchronization jump width, (2-bits + 1), min(uc_phase1, 4);
|
||||
uint8_t uc_sp; //! Sample point value, 0~100 in percent.
|
||||
} can_bit_timing_t;
|
||||
|
||||
|
||||
/** Values of bit time register for different baudrates, Sample point = ((1 + uc_prog + uc_phase1) / uc_tq) * 100%. */
|
||||
const can_bit_timing_t can_bit_time[] = {
|
||||
{8, (2 + 1), (1 + 1), (1 + 1), (2 + 1), 75},
|
||||
{9, (1 + 1), (2 + 1), (2 + 1), (1 + 1), 67},
|
||||
{10, (2 + 1), (2 + 1), (2 + 1), (2 + 1), 70},
|
||||
{11, (3 + 1), (2 + 1), (2 + 1), (3 + 1), 72},
|
||||
{12, (2 + 1), (3 + 1), (3 + 1), (3 + 1), 67},
|
||||
{13, (3 + 1), (3 + 1), (3 + 1), (3 + 1), 77},
|
||||
{14, (3 + 1), (3 + 1), (4 + 1), (3 + 1), 64},
|
||||
{15, (3 + 1), (4 + 1), (4 + 1), (3 + 1), 67},
|
||||
{16, (4 + 1), (4 + 1), (4 + 1), (3 + 1), 69},
|
||||
{17, (5 + 1), (4 + 1), (4 + 1), (3 + 1), 71},
|
||||
{18, (4 + 1), (5 + 1), (5 + 1), (3 + 1), 67},
|
||||
{19, (5 + 1), (5 + 1), (5 + 1), (3 + 1), 68},
|
||||
{20, (6 + 1), (5 + 1), (5 + 1), (3 + 1), 70},
|
||||
{21, (7 + 1), (5 + 1), (5 + 1), (3 + 1), 71},
|
||||
{22, (6 + 1), (6 + 1), (6 + 1), (3 + 1), 68},
|
||||
{23, (7 + 1), (7 + 1), (6 + 1), (3 + 1), 70},
|
||||
{24, (6 + 1), (7 + 1), (7 + 1), (3 + 1), 67},
|
||||
{25, (7 + 1), (7 + 1), (7 + 1), (3 + 1), 68}
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Configure CAN baudrate.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param ul_mck The input main clock for the CAN module.
|
||||
* \param ul_baudrate Baudrate value (kB/s), allowed values:
|
||||
* 1000, 800, 500, 250, 125, 50, 25, 10, 5.
|
||||
*
|
||||
* \retval Set the baudrate successfully or not.
|
||||
*/
|
||||
uint32_t CANRaw::set_baudrate(Can *p_can, uint32_t ul_mck, uint32_t ul_baudrate)
|
||||
{
|
||||
uint8_t uc_tq;
|
||||
uint8_t uc_prescale;
|
||||
uint32_t ul_mod;
|
||||
uint32_t ul_cur_mod;
|
||||
can_bit_timing_t *p_bit_time;
|
||||
|
||||
/* Check whether the baudrate prescale will be greater than the max divide value. */
|
||||
if (((ul_mck + (ul_baudrate * CAN_MAX_TQ_NUM * 1000 - 1)) /
|
||||
(ul_baudrate * CAN_MAX_TQ_NUM * 1000)) > CAN_BAUDRATE_MAX_DIV) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Check whether the input MCK is too small. */
|
||||
if (ul_mck < ul_baudrate * CAN_MIN_TQ_NUM * 1000) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Initialize it as the minimum Time Quantum. */
|
||||
uc_tq = CAN_MIN_TQ_NUM;
|
||||
|
||||
/* Initialize the remainder as the max value. When the remainder is 0, get the right TQ number. */
|
||||
ul_mod = 0xffffffff;
|
||||
/* Find out the approximate Time Quantum according to the baudrate. */
|
||||
for (uint8_t i = CAN_MIN_TQ_NUM; i <= CAN_MAX_TQ_NUM; i++) {
|
||||
if ((ul_mck / (ul_baudrate * i * 1000)) <= CAN_BAUDRATE_MAX_DIV) {
|
||||
ul_cur_mod = ul_mck % (ul_baudrate * i * 1000);
|
||||
if (ul_cur_mod < ul_mod){
|
||||
ul_mod = ul_cur_mod;
|
||||
uc_tq = i;
|
||||
if (!ul_mod) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Calculate the baudrate prescale value. */
|
||||
uc_prescale = ul_mck / (ul_baudrate * uc_tq * 1000);
|
||||
|
||||
/* Get the right CAN BIT Timing group. */
|
||||
p_bit_time = (can_bit_timing_t *)&can_bit_time[uc_tq - CAN_MIN_TQ_NUM];
|
||||
|
||||
/* Before modifying the CANBR register, disable the CAN controller. */
|
||||
//can_disable(p_can);
|
||||
p_can->CAN_MR &= ~CAN_MR_CANEN;
|
||||
|
||||
/* Write into the CAN baudrate register. */
|
||||
p_can->CAN_BR = CAN_BR_PHASE2(p_bit_time->uc_phase2 - 1) |
|
||||
CAN_BR_PHASE1(p_bit_time->uc_phase1 - 1) |
|
||||
CAN_BR_PROPAG(p_bit_time->uc_prog - 1) |
|
||||
CAN_BR_SJW(p_bit_time->uc_sjw - 1) |
|
||||
CAN_BR_BRP(uc_prescale - 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Initialize CAN controller.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param ul_mck CAN module input clock.
|
||||
* \param ul_baudrate CAN communication baudrate in kbs.
|
||||
*
|
||||
* \retval 0 If failed to initialize the CAN module; otherwise successful.
|
||||
*
|
||||
* \note PMC clock for CAN peripheral should be enabled before calling this function.
|
||||
*/
|
||||
uint32_t CANRaw::init(Can *p_can, uint32_t ul_mck, uint32_t ul_baudrate)
|
||||
{
|
||||
uint32_t ul_flag;
|
||||
uint32_t ul_tick;
|
||||
|
||||
/* Initialize the baudrate for CAN module. */
|
||||
ul_flag = set_baudrate(p_can, ul_mck, ul_baudrate);
|
||||
if (ul_flag == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Reset the CAN eight message mailbox. */
|
||||
can_reset_all_mailbox(p_can);
|
||||
|
||||
/* Enable the CAN controller. */
|
||||
can_enable(p_can);
|
||||
|
||||
/* Wait until the CAN is synchronized with the bus activity. */
|
||||
ul_flag = 0;
|
||||
ul_tick = 0;
|
||||
while (!(ul_flag & CAN_SR_WAKEUP) && (ul_tick < CAN_TIMEOUT)) {
|
||||
ul_flag = can_get_status(p_can);
|
||||
ul_tick++;
|
||||
}
|
||||
|
||||
/* Timeout or the CAN module has been synchronized with the bus. */
|
||||
if (CAN_TIMEOUT == ul_tick) {
|
||||
return 0;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Enable CAN Controller.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::enable(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR |= CAN_MR_CANEN;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Disable CAN Controller.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::disable(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR &= ~CAN_MR_CANEN;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Disable CAN Controller low power mode.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::disable_low_power_mode(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR &= ~CAN_MR_LPM;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Enable CAN Controller low power mode.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::enable_low_power_mode(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR |= CAN_MR_LPM;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Disable CAN Controller autobaud/listen mode.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::disable_autobaud_listen_mode(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR &= ~CAN_MR_ABM;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Enable CAN Controller autobaud/listen mode.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::enable_autobaud_listen_mode(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR |= CAN_MR_ABM;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief CAN Controller won't generate overload frame.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::disable_overload_frame(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR &= ~CAN_MR_OVL;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief CAN Controller will generate an overload frame after each successful
|
||||
* reception for mailboxes configured in Receive mode, Producer and Consumer.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::enable_overload_frame(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR |= CAN_MR_OVL;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Configure the timestamp capture point, at the start or the end of frame.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param ul_flag 0: Timestamp is captured at each start of frame;
|
||||
* 1: Timestamp is captured at each end of frame.
|
||||
*/
|
||||
void CANRaw::set_timestamp_capture_point(Can *p_can, uint32_t ul_flag)
|
||||
{
|
||||
if (ul_flag) {
|
||||
p_can->CAN_MR |= CAN_MR_TEOF;
|
||||
} else {
|
||||
p_can->CAN_MR &= ~CAN_MR_TEOF;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Disable CAN Controller time triggered mode.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::disable_time_triggered_mode(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR &= ~CAN_MR_TTM;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Enable CAN Controller time triggered mode.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::enable_time_triggered_mode(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR |= CAN_MR_TTM;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Disable CAN Controller timer freeze.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::disable_timer_freeze(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR &= ~CAN_MR_TIMFRZ;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Enable CAN Controller timer freeze.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::enable_timer_freeze(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR |= CAN_MR_TIMFRZ;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Disable CAN Controller transmit repeat function.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::disable_tx_repeat(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR |= CAN_MR_DRPT;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Enable CAN Controller transmit repeat function.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::enable_tx_repeat(Can *p_can)
|
||||
{
|
||||
p_can->CAN_MR &= ~CAN_MR_DRPT;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Configure CAN Controller reception synchronization stage.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param ul_stage The reception stage to be configured.
|
||||
*
|
||||
* \note This is just for debug purpose only.
|
||||
*/
|
||||
void CANRaw::set_rx_sync_stage(Can *p_can, uint32_t ul_stage)
|
||||
{
|
||||
p_can->CAN_MR = (p_can->CAN_MR & ~CAN_MR_RXSYNC_Msk) | ul_stage;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Enable CAN interrupt.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param dw_mask Interrupt to be enabled.
|
||||
*/
|
||||
void CANRaw::enable_interrupt(Can *p_can, uint32_t dw_mask)
|
||||
{
|
||||
p_can->CAN_IER = dw_mask;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Disable CAN interrupt.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param dw_mask Interrupt to be disabled.
|
||||
*/
|
||||
void CANRaw::disable_interrupt(Can *p_can, uint32_t dw_mask)
|
||||
{
|
||||
p_can->CAN_IDR = dw_mask;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Get CAN Interrupt Mask.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*
|
||||
* \retval CAN interrupt mask.
|
||||
*/
|
||||
uint32_t CANRaw::get_interrupt_mask(Can *p_can)
|
||||
{
|
||||
return (p_can->CAN_IMR);
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Get CAN status.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*
|
||||
* \retval CAN status.
|
||||
*/
|
||||
uint32_t CANRaw::get_status(Can *p_can)
|
||||
{
|
||||
return (p_can->CAN_SR);
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Get the 16-bit free-running internal timer count.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*
|
||||
* \retval The internal CAN free-running timer counter.
|
||||
*/
|
||||
uint32_t CANRaw::get_internal_timer_value(Can *p_can)
|
||||
{
|
||||
return (p_can->CAN_TIM);
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Get CAN timestamp register value.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*
|
||||
* \retval The timestamp value.
|
||||
*/
|
||||
uint32_t CANRaw::get_timestamp_value(Can *p_can)
|
||||
{
|
||||
return (p_can->CAN_TIMESTP);
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Get CAN transmit error counter.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*
|
||||
* \retval Transmit error counter.
|
||||
*/
|
||||
uint8_t CANRaw::get_tx_error_cnt(Can *p_can)
|
||||
{
|
||||
return (uint8_t) (p_can->CAN_ECR >> CAN_ECR_TEC_Pos);
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Get CAN receive error counter.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*
|
||||
* \retval Receive error counter.
|
||||
*/
|
||||
uint8_t CANRaw::get_rx_error_cnt(Can *p_can)
|
||||
{
|
||||
return (uint8_t) (p_can->CAN_ECR >> CAN_ECR_REC_Pos);
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Reset the internal free-running 16-bit timer.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*
|
||||
* \note If the internal timer counter is frozen, this function automatically
|
||||
* re-enables it.
|
||||
*/
|
||||
void CANRaw::reset_internal_timer(Can *p_can)
|
||||
{
|
||||
p_can->CAN_TCR |= CAN_TCR_TIMRST;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Send global transfer request.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param uc_mask Mask for mailboxes that are requested to transfer.
|
||||
*/
|
||||
void CANRaw::global_send_transfer_cmd(Can *p_can, uint8_t uc_mask)
|
||||
{
|
||||
uint32_t ul_reg;
|
||||
|
||||
ul_reg = p_can->CAN_TCR & ((uint32_t)~GLOBAL_MAILBOX_MASK);
|
||||
p_can->CAN_TCR = ul_reg | uc_mask;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Send global abort request.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param uc_mask Mask for mailboxes that are requested to abort.
|
||||
*/
|
||||
void CANRaw::global_send_abort_cmd(Can *p_can, uint8_t uc_mask)
|
||||
{
|
||||
uint32_t ul_reg;
|
||||
|
||||
ul_reg = p_can->CAN_ACR & ((uint32_t)~GLOBAL_MAILBOX_MASK);
|
||||
p_can->CAN_ACR = ul_reg | uc_mask;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Configure the timemark for the mailbox.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param uc_index Indicate which mailbox is to be configured.
|
||||
* \param us_cnt The timemark to be set.
|
||||
*
|
||||
* \note The timemark is active in Time Triggered mode only.
|
||||
*/
|
||||
void CANRaw::mailbox_set_timemark(Can *p_can, uint8_t uc_index, uint16_t us_cnt)
|
||||
{
|
||||
uint32_t ul_reg;
|
||||
|
||||
ul_reg = p_can->CAN_MB[uc_index].CAN_MMR & ((uint32_t)~TIMEMARK_MASK);
|
||||
p_can->CAN_MB[uc_index].CAN_MMR = ul_reg | us_cnt;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Get status of the mailbox.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param uc_index Indicate which mailbox is to be read.
|
||||
*
|
||||
* \retval The mailbox status.
|
||||
*/
|
||||
uint32_t CANRaw::mailbox_get_status(Can *p_can, uint8_t uc_index)
|
||||
{
|
||||
return (p_can->CAN_MB[uc_index].CAN_MSR);
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Send single mailbox transfer request.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param uc_index Indicate which mailbox is to be configured.
|
||||
*/
|
||||
void CANRaw::mailbox_send_transfer_cmd(Can *p_can, uint8_t uc_index)
|
||||
{
|
||||
p_can->CAN_MB[uc_index].CAN_MCR |= CAN_MCR_MTCR;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Send single mailbox abort request.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param uc_index Indicate which mailbox is to be configured.
|
||||
*/
|
||||
void CANRaw::mailbox_send_abort_cmd(Can *p_can, uint8_t uc_index)
|
||||
{
|
||||
p_can->CAN_MB[uc_index].CAN_MCR |= CAN_MCR_MACR;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Initialize the mailbox in different mode and set up related configuration.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param p_mailbox Pointer to a CAN mailbox instance.
|
||||
*/
|
||||
void CANRaw::mailbox_init(Can *p_can, can_mb_conf_t *p_mailbox)
|
||||
{
|
||||
uint8_t uc_index;
|
||||
|
||||
uc_index = (uint8_t)p_mailbox->ul_mb_idx;
|
||||
/* Check the object type of the mailbox. If it's used to disable the mailbox, reset the whole mailbox. */
|
||||
if (!p_mailbox->uc_obj_type) {
|
||||
p_can->CAN_MB[uc_index].CAN_MMR = 0;
|
||||
p_can->CAN_MB[uc_index].CAN_MAM = 0;
|
||||
p_can->CAN_MB[uc_index].CAN_MID = 0;
|
||||
p_can->CAN_MB[uc_index].CAN_MDL = 0;
|
||||
p_can->CAN_MB[uc_index].CAN_MDH = 0;
|
||||
p_can->CAN_MB[uc_index].CAN_MCR = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
/* Set the priority in Transmit mode. */
|
||||
p_can->CAN_MB[uc_index].CAN_MMR = (p_can->CAN_MB[uc_index].CAN_MMR &
|
||||
~CAN_MMR_PRIOR_Msk) | (p_mailbox-> uc_tx_prio << CAN_MMR_PRIOR_Pos);
|
||||
|
||||
/* Set the message ID and message acceptance mask for the mailbox in other modes. */
|
||||
if (p_mailbox->uc_id_ver) {
|
||||
p_can->CAN_MB[uc_index].CAN_MAM = p_mailbox->ul_id_msk | CAN_MAM_MIDE;
|
||||
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id | CAN_MAM_MIDE;
|
||||
} else {
|
||||
p_can->CAN_MB[uc_index].CAN_MAM = p_mailbox->ul_id_msk;
|
||||
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id;
|
||||
}
|
||||
|
||||
/* Set up mailbox in one of the five different modes. */
|
||||
p_can->CAN_MB[uc_index].CAN_MMR = (p_can->CAN_MB[uc_index].CAN_MMR &
|
||||
~CAN_MMR_MOT_Msk) | (p_mailbox-> uc_obj_type << CAN_MMR_MOT_Pos);
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Read receive information for the mailbox.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param p_mailbox Pointer to a CAN mailbox instance.
|
||||
*
|
||||
* \retval Different CAN mailbox transfer status.
|
||||
*
|
||||
* \note Read the mailbox status before calling this function.
|
||||
*/
|
||||
uint32_t CANRaw::mailbox_read(Can *p_can, can_mb_conf_t *p_mailbox)
|
||||
{
|
||||
uint32_t ul_status;
|
||||
uint8_t uc_index;
|
||||
uint32_t ul_retval;
|
||||
|
||||
ul_retval = 0;
|
||||
uc_index = (uint8_t)p_mailbox->ul_mb_idx;
|
||||
ul_status = p_mailbox->ul_status;
|
||||
|
||||
/* Check whether there is overwriting happening in Receive with Overwrite mode,
|
||||
or there're messages lost in Receive mode. */
|
||||
if ((ul_status & CAN_MSR_MRDY) && (ul_status & CAN_MSR_MMI)) {
|
||||
ul_retval = CAN_MAILBOX_RX_OVER;
|
||||
}
|
||||
|
||||
/* Read the message family ID. */
|
||||
p_mailbox->ul_fid = p_can->CAN_MB[uc_index].CAN_MFID & CAN_MFID_MFID_Msk;
|
||||
|
||||
/* Read received data length. */
|
||||
p_mailbox->uc_length = (ul_status & CAN_MSR_MDLC_Msk) >> CAN_MSR_MDLC_Pos;
|
||||
|
||||
/* Read received data. */
|
||||
p_mailbox->ul_datal = p_can->CAN_MB[uc_index].CAN_MDL;
|
||||
if (p_mailbox->uc_length > 4) {
|
||||
p_mailbox->ul_datah = p_can->CAN_MB[uc_index].CAN_MDH;
|
||||
}
|
||||
|
||||
/* Read the mailbox status again to check whether the software needs to re-read mailbox data register. */
|
||||
p_mailbox->ul_status = p_can->CAN_MB[uc_index].CAN_MSR;
|
||||
ul_status = p_mailbox->ul_status;
|
||||
if (ul_status & CAN_MSR_MMI) {
|
||||
ul_retval |= CAN_MAILBOX_RX_NEED_RD_AGAIN;
|
||||
} else {
|
||||
ul_retval |= CAN_MAILBOX_TRANSFER_OK;
|
||||
}
|
||||
|
||||
/* Enable next receive process. */
|
||||
can_mailbox_send_transfer_cmd(p_can, uc_index);
|
||||
|
||||
return ul_retval;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Prepare transmit information and write them into the mailbox.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param p_mailbox Pointer to a CAN mailbox instance.
|
||||
*
|
||||
* \retval CAN_MAILBOX_NOT_READY: Failed because mailbox isn't ready.
|
||||
* CAN_MAILBOX_TRANSFER_OK: Successfully write message into mailbox.
|
||||
*
|
||||
* \note After calling this function, the mailbox message won't be sent out until
|
||||
* can_mailbox_send_transfer_cmd() is called.
|
||||
*/
|
||||
uint32_t CANRaw::mailbox_write(Can *p_can, can_mb_conf_t *p_mailbox)
|
||||
{
|
||||
uint32_t ul_status;
|
||||
uint8_t uc_index;
|
||||
|
||||
uc_index = (uint8_t)p_mailbox->ul_mb_idx;
|
||||
/* Read the mailbox status firstly to check whether the mailbox is ready or not. */
|
||||
p_mailbox->ul_status = can_mailbox_get_status(p_can, uc_index);
|
||||
ul_status = p_mailbox->ul_status;
|
||||
if (!(ul_status & CAN_MSR_MRDY)) {
|
||||
return CAN_MAILBOX_NOT_READY;
|
||||
}
|
||||
|
||||
/* Write transmit identifier. */
|
||||
if (p_mailbox->uc_id_ver) {
|
||||
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id | CAN_MAM_MIDE;
|
||||
} else {
|
||||
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id;
|
||||
}
|
||||
|
||||
/* Write transmit data into mailbox data register. */
|
||||
p_can->CAN_MB[uc_index].CAN_MDL = p_mailbox->ul_datal;
|
||||
if (p_mailbox->uc_length > 4) {
|
||||
p_can->CAN_MB[uc_index].CAN_MDH = p_mailbox->ul_datah;
|
||||
}
|
||||
|
||||
/* Write transmit data length into mailbox control register. */
|
||||
p_can->CAN_MB[uc_index].CAN_MCR = (p_can->CAN_MB[uc_index].CAN_MCR &
|
||||
~CAN_MCR_MDLC_Msk) | CAN_MCR_MDLC(p_mailbox->uc_length);
|
||||
|
||||
return CAN_MAILBOX_TRANSFER_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Require to send out a remote frame.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
* \param p_mailbox Pointer to a CAN mailbox instance.
|
||||
*
|
||||
* \retval CAN_MAILBOX_NOT_READY: Failed because mailbox isn't ready for transmitting message.
|
||||
* CAN_MAILBOX_TRANSFER_OK: Successfully send out a remote frame.
|
||||
*/
|
||||
uint32_t CANRaw::mailbox_tx_remote_frame(Can *p_can, can_mb_conf_t *p_mailbox)
|
||||
{
|
||||
uint32_t ul_status;
|
||||
uint8_t uc_index;
|
||||
|
||||
uc_index = (uint8_t)p_mailbox->ul_mb_idx;
|
||||
/* Read the mailbox status firstly to check whether the mailbox is ready or not. */
|
||||
p_mailbox->ul_status = p_can->CAN_MB[uc_index].CAN_MSR;
|
||||
ul_status = p_mailbox->ul_status;
|
||||
if (!(ul_status & CAN_MSR_MRDY)) {
|
||||
return CAN_MAILBOX_NOT_READY;
|
||||
}
|
||||
|
||||
/* Write transmit identifier. */
|
||||
if (p_mailbox->uc_id_ver) {
|
||||
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id | CAN_MAM_MIDE;
|
||||
} else {
|
||||
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id;
|
||||
}
|
||||
|
||||
/* Set the RTR bit in the sent frame. */
|
||||
p_can->CAN_MB[uc_index].CAN_MCR |= CAN_MCR_MRTR;
|
||||
|
||||
/* Set the MBx bit in the Transfer Command Register to send out the remote frame. */
|
||||
can_global_send_transfer_cmd(p_can, (1 << uc_index));
|
||||
|
||||
return CAN_MAILBOX_TRANSFER_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Reset the eight mailboxes.
|
||||
*
|
||||
* \param p_can Pointer to a CAN peripheral instance.
|
||||
*/
|
||||
void CANRaw::reset_all_mailbox(Can *p_can)
|
||||
{
|
||||
can_mb_conf_t mb_config_t;
|
||||
|
||||
/* Set the mailbox object type parameter to disable the mailbox. */
|
||||
mb_config_t.uc_obj_type = CAN_MB_DISABLE_MODE;
|
||||
|
||||
for (uint8_t i = 0; i < CANMB_NUMBER; i++) {
|
||||
mb_config_t.ul_mb_idx = i;
|
||||
can_mailbox_init(p_can, &mb_config_t);
|
||||
}
|
||||
}
|
@ -1,131 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2013 Arduino. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
|
||||
#ifndef _CAN_LIBRARY_
|
||||
#define _CAN_LIBRARY_
|
||||
|
||||
#include "sn65hvd234.h"
|
||||
|
||||
|
||||
/** Define the Mailbox mask for eight mailboxes. */
|
||||
#define GLOBAL_MAILBOX_MASK 0x000000ff
|
||||
|
||||
/** Disable all interrupt mask */
|
||||
#define CAN_DISABLE_ALL_INTERRUPT_MASK 0xffffffff
|
||||
|
||||
/** Define the typical baudrate for CAN communication in KHz. */
|
||||
#define CAN_BPS_1000K 1000
|
||||
#define CAN_BPS_800K 800
|
||||
#define CAN_BPS_500K 500
|
||||
#define CAN_BPS_250K 250
|
||||
#define CAN_BPS_125K 125
|
||||
#define CAN_BPS_50K 50
|
||||
#define CAN_BPS_25K 25
|
||||
#define CAN_BPS_10K 10
|
||||
#define CAN_BPS_5K 5
|
||||
|
||||
/** Define the mailbox mode. */
|
||||
#define CAN_MB_DISABLE_MODE 0
|
||||
#define CAN_MB_RX_MODE 1
|
||||
#define CAN_MB_RX_OVER_WR_MODE 2
|
||||
#define CAN_MB_TX_MODE 3
|
||||
#define CAN_MB_CONSUMER_MODE 4
|
||||
#define CAN_MB_PRODUCER_MODE 5
|
||||
|
||||
/** Define CAN mailbox transfer status code. */
|
||||
#define CAN_MAILBOX_TRANSFER_OK 0 //! Read from or write into mailbox successfully.
|
||||
#define CAN_MAILBOX_NOT_READY 0x01 //! Receiver is empty or transmitter is busy.
|
||||
#define CAN_MAILBOX_RX_OVER 0x02 //! Message overwriting happens or there're messages lost in different receive modes.
|
||||
#define CAN_MAILBOX_RX_NEED_RD_AGAIN 0x04 //! Application needs to re-read the data register in Receive with Overwrite mode.
|
||||
|
||||
class CANRaw
|
||||
{
|
||||
protected:
|
||||
/* CAN peripheral, set by constructor */
|
||||
//Can* m_pCan ;
|
||||
|
||||
/* CAN Transceiver */
|
||||
SSN65HVD234_Data m_Transceiver ;
|
||||
|
||||
/** CAN Transfer */
|
||||
//can_mb_conf_t m_Mailbox;
|
||||
|
||||
private:
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
//CANRawClass( Can* pCan ) ;
|
||||
|
||||
/**
|
||||
* \defgroup sam_driver_can_group Controller Area Network (CAN) Driver
|
||||
*
|
||||
* See \ref sam_can_quickstart.
|
||||
*
|
||||
* \par Purpose
|
||||
*
|
||||
* The CAN controller provides all the features required to implement
|
||||
* the serial communication protocol CAN defined by Robert Bosch GmbH,
|
||||
* the CAN specification. This is a driver for configuration, enabling,
|
||||
* disabling and use of the CAN peripheral.
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
uint32_t set_baudrate(Can *p_can, uint32_t ul_mck, uint32_t ul_baudrate);
|
||||
uint32_t init(Can *p_can, uint32_t ul_mck, uint32_t ul_baudrate);
|
||||
void enable(Can *p_can);
|
||||
void disable(Can *p_can);
|
||||
void disable_low_power_mode(Can *p_can);
|
||||
void enable_low_power_mode(Can *p_can);
|
||||
void disable_autobaud_listen_mode(Can *p_can);
|
||||
void enable_autobaud_listen_mode(Can *p_can);
|
||||
void disable_overload_frame(Can *p_can);
|
||||
void enable_overload_frame(Can *p_can);
|
||||
void set_timestamp_capture_point(Can *p_can, uint32_t ul_flag);
|
||||
void disable_time_triggered_mode(Can *p_can);
|
||||
void enable_time_triggered_mode(Can *p_can);
|
||||
void disable_timer_freeze(Can *p_can);
|
||||
void enable_timer_freeze(Can *p_can);
|
||||
void disable_tx_repeat(Can *p_can);
|
||||
void enable_tx_repeat(Can *p_can);
|
||||
void set_rx_sync_stage(Can *p_can, uint32_t ul_stage);
|
||||
void enable_interrupt(Can *p_can, uint32_t dw_mask);
|
||||
void disable_interrupt(Can *p_can, uint32_t dw_mask);
|
||||
uint32_t get_interrupt_mask(Can *p_can);
|
||||
uint32_t get_status(Can *p_can);
|
||||
uint32_t get_internal_timer_value(Can *p_can);
|
||||
uint32_t get_timestamp_value(Can *p_can);
|
||||
uint8_t get_tx_error_cnt(Can *p_can);
|
||||
uint8_t get_rx_error_cnt(Can *p_can);
|
||||
void reset_internal_timer(Can *p_can);
|
||||
void global_send_transfer_cmd(Can *p_can, uint8_t uc_mask);
|
||||
void global_send_abort_cmd(Can *p_can, uint8_t uc_mask);
|
||||
void mailbox_set_timemark(Can *p_can, uint8_t uc_index, uint16_t us_cnt);
|
||||
uint32_t mailbox_get_status(Can *p_can, uint8_t uc_index);
|
||||
void mailbox_send_transfer_cmd(Can *p_can, uint8_t uc_index);
|
||||
void mailbox_send_abort_cmd(Can *p_can, uint8_t uc_index);
|
||||
void mailbox_init(Can *p_can, can_mb_conf_t *p_mailbox);
|
||||
uint32_t mailbox_read(Can *p_can, can_mb_conf_t *p_mailbox);
|
||||
uint32_t mailbox_write(Can *p_can, can_mb_conf_t *p_mailbox);
|
||||
uint32_t mailbox_tx_remote_frame(Can *p_can, can_mb_conf_t *p_mailbox);
|
||||
void reset_all_mailbox(Can *p_can);
|
||||
} ;
|
||||
|
||||
|
||||
#endif // _CAN_LIBRARY_
|
@ -1,37 +0,0 @@
|
||||
Controller Area network (CAN) API for Arduino Due
|
||||
|
||||
This is a beta release of the CAN API for Arduino Due. It contains the necessary classes and functions to configure, enable, disable and use of the CAN peripherals controllers embedded in the SAM3X8E core inside Arduino Due, and the two external SN65HVD234 transceivers.
|
||||
|
||||
This CAN API for Arduino Due is released together with a CAN sample1 sketch for the Arduino IDE 1.5.2 and it shows how to configure the CAN controllers and how to manage CAN message transfers. The two CAN controllers (CAN0 and CAN1) and two mailboxes (mailbox 0 and mailbox 1) are used: CAN0 mailbox 0 is configured as transmitter, and CAN1 mailbox 0 is configured as receiver. The communication baudrate is 1Mbit/s. The CAN0 controller tries to send on the bus messages through the mailbox 0 and waits for messages from mailbox 1 on CAN1 controller.
|
||||
|
||||
It is required to use the two CAN pins in Arduino Due, connected to the two external SN65HVD234transceivers in loop mode via a pair cable. The CAN message transaction can be monitored by a serial UART connection (115.2 Kbps, 8 data bits, no parity, 1 stop bit, no flux control) or serial monitor of the Arduino IDE 1.5.2 with autoscroll and newline modes activated.
|
||||
|
||||
Source files:
|
||||
- CAN.cpp
|
||||
- CAN.h
|
||||
- sn65hvd234.c
|
||||
- sn65hvd234.h
|
||||
- variant.cpp
|
||||
- variant.h
|
||||
|
||||
CAN files (.cpp .h) contain the CANRaw class with 38 functions.
|
||||
|
||||
sn65hvd234 files (.c .h) contain 7 driver functions.
|
||||
|
||||
The variant files (.cpp .h) are updates to the IDE 1.5.2 ones. Added initialization of the CAN pins in variant.cpp
|
||||
and CAN pins definition in variant.h.
|
||||
|
||||
Hardware requirements:
|
||||
- Arduino Due board
|
||||
- Dual CAN transceiver shield
|
||||
- Twisted shielded pair cable
|
||||
|
||||
Software requirements:
|
||||
- Arduino IDE 1.5.2
|
||||
- CAN API library
|
||||
|
||||
To perform the CAN sample 1 test, the pair cable needs to be connected between the two CAN ports as follows:
|
||||
CANRX0 <-> CANRX0
|
||||
CANRX1 <-> CANRX1
|
||||
|
||||
Once the CAN sample 1 and the CAN library are loaded in Arduino IDE 1.5.2, after serial monitor open or after a reset of the Arduino board, the following message should be displayed in the monitor terminal: Type CAN message to send. Then, an 8 digit message can be typed and after a return stroke of the keyboard, the following message should be displayed: Sent value=XXXXXXXX, where XXXXXXXX is the typed message. If the message was sent/received successfully, the following message should be displayed: CAN message received=XXXXXXX and End of test. Otherwise, there is a CAN communication error.
|
@ -1,128 +0,0 @@
|
||||
// Arduino Due - CAN Sample 1
|
||||
// Brief CAN example for Arduino Due
|
||||
// Test the transmission from CAN0 Mailbox 0 to CAN1 Mailbox 0
|
||||
// By Thibaut Viard/Wilfredo Molina 2012
|
||||
|
||||
// Required libraries
|
||||
#include "variant.h"
|
||||
#include <CAN.h>
|
||||
|
||||
#define TEST1_CAN_COMM_MB_IDX 0
|
||||
#define TEST1_CAN_TRANSFER_ID 0x07
|
||||
#define TEST1_CAN0_TX_PRIO 15
|
||||
#define CAN_MSG_DUMMY_DATA 0x55AAAA55
|
||||
|
||||
// CAN frame max data length
|
||||
#define MAX_CAN_FRAME_DATA_LEN 8
|
||||
|
||||
// CAN class
|
||||
CANRaw CAN;
|
||||
|
||||
// Message variable to be send
|
||||
uint32_t CAN_MSG_1 = 0;
|
||||
|
||||
// CAN0 Transceiver
|
||||
SSN65HVD234_Data can0_transceiver;
|
||||
|
||||
// CAN1 Transceiver
|
||||
SSN65HVD234_Data can1_transceiver;
|
||||
|
||||
// Define the struct for CAN message mailboxes needed
|
||||
can_mb_conf_t can0_mailbox;
|
||||
can_mb_conf_t can1_mailbox;
|
||||
|
||||
void setup()
|
||||
{
|
||||
// start serial port at 9600 bps:
|
||||
Serial.begin(9600);
|
||||
Serial.println("Type CAN message to send");
|
||||
while (Serial.available() == 0);
|
||||
}
|
||||
void loop(){
|
||||
|
||||
while (Serial.available() > 0) {
|
||||
CAN_MSG_1 = Serial.parseInt();
|
||||
if (Serial.read() == '\n') {
|
||||
Serial.print("Sent value= ");
|
||||
Serial.println(CAN_MSG_1);
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize CAN0 Transceiver
|
||||
SN65HVD234_Init(&can0_transceiver);
|
||||
SN65HVD234_SetRs(&can0_transceiver, 61);
|
||||
SN65HVD234_SetEN(&can0_transceiver, 62);
|
||||
// Enable CAN0 Transceiver
|
||||
SN65HVD234_DisableLowPower(&can0_transceiver);
|
||||
SN65HVD234_Enable(&can0_transceiver);
|
||||
|
||||
// Initialize CAN1 Transceiver
|
||||
SN65HVD234_Init(&can1_transceiver);
|
||||
SN65HVD234_SetRs(&can1_transceiver, 63);
|
||||
SN65HVD234_SetEN(&can1_transceiver, 64);
|
||||
// Enable CAN1 Transceiver
|
||||
SN65HVD234_DisableLowPower(&can1_transceiver);
|
||||
SN65HVD234_Enable(&can1_transceiver);
|
||||
|
||||
// Enable CAN0 & CAN1 clock
|
||||
pmc_enable_periph_clk(ID_CAN0);
|
||||
pmc_enable_periph_clk(ID_CAN1);
|
||||
|
||||
// Initialize CAN0 and CAN1, baudrate is 1Mb/s
|
||||
CAN.init(CAN0, SystemCoreClock, CAN_BPS_1000K);
|
||||
CAN.init(CAN1, SystemCoreClock, CAN_BPS_1000K);
|
||||
|
||||
// Initialize CAN1 mailbox 0 as receiver, frame ID is 0x07
|
||||
// can_reset_mailbox_data(&can1_mailbox);
|
||||
can1_mailbox.ul_mb_idx = TEST1_CAN_COMM_MB_IDX;
|
||||
can1_mailbox.uc_obj_type = CAN_MB_RX_MODE;
|
||||
can1_mailbox.ul_id_msk = CAN_MAM_MIDvA_Msk | CAN_MAM_MIDvB_Msk;
|
||||
can1_mailbox.ul_id = CAN_MID_MIDvA(TEST1_CAN_TRANSFER_ID);
|
||||
CAN.mailbox_init(CAN1, &can1_mailbox);
|
||||
|
||||
// Initialize CAN0 mailbox 0 as transmitter, transmit priority is 15
|
||||
// can_reset_mailbox_data(&can0_mailbox);
|
||||
can0_mailbox.ul_mb_idx = TEST1_CAN_COMM_MB_IDX;
|
||||
can0_mailbox.uc_obj_type = CAN_MB_TX_MODE;
|
||||
can0_mailbox.uc_tx_prio = TEST1_CAN0_TX_PRIO;
|
||||
can0_mailbox.uc_id_ver = 0;
|
||||
can0_mailbox.ul_id_msk = 0;
|
||||
CAN.mailbox_init(CAN0, &can0_mailbox);
|
||||
|
||||
// Prepare transmit ID, data and data length in CAN0 mailbox 0
|
||||
can0_mailbox.ul_id = CAN_MID_MIDvA(TEST1_CAN_TRANSFER_ID);
|
||||
can0_mailbox.ul_datal = CAN_MSG_1;
|
||||
can0_mailbox.ul_datah = CAN_MSG_DUMMY_DATA;
|
||||
can0_mailbox.uc_length = MAX_CAN_FRAME_DATA_LEN;
|
||||
CAN.mailbox_write(CAN0, &can0_mailbox);
|
||||
|
||||
// Send out the information in the mailbox
|
||||
CAN.global_send_transfer_cmd(CAN0, CAN_TCR_MB0);
|
||||
|
||||
// Wait for CAN1 mailbox 0 to receive the data
|
||||
while (!(CAN.mailbox_get_status(CAN1, 0) & CAN_MSR_MRDY)) {
|
||||
}
|
||||
|
||||
// Read the received data from CAN1 mailbox 0
|
||||
CAN.mailbox_read(CAN1, &can1_mailbox);
|
||||
Serial.print("CAN message received= ");
|
||||
Serial.println(can1_mailbox.ul_datal);
|
||||
|
||||
// Disable CAN0 Controller
|
||||
CAN.disable(CAN0);
|
||||
// Disable CAN0 Transceiver
|
||||
SN65HVD234_EnableLowPower(&can0_transceiver);
|
||||
SN65HVD234_Disable(&can0_transceiver);
|
||||
|
||||
// Disable CAN1 Controller
|
||||
CAN.disable(CAN1);
|
||||
// Disable CAN1 Transceiver
|
||||
SN65HVD234_EnableLowPower(&can1_transceiver);
|
||||
SN65HVD234_Disable(&can1_transceiver);
|
||||
|
||||
Serial.print("End of test");
|
||||
|
||||
while (1) {
|
||||
}
|
||||
}
|
||||
|
@ -1,142 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2013 Arduino. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
/**
|
||||
* \file
|
||||
*
|
||||
* Implementation of the SN65HVD234 drivers.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "sn65hvd234.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
/**
|
||||
* \brief Initialize SN65HVD234 component data
|
||||
*
|
||||
* \param pComponent pointer on SSN65HVD234_Data
|
||||
*
|
||||
* \return 0 if OK
|
||||
*/
|
||||
extern uint32_t SN65HVD234_Init( SSN65HVD234_Data* pComponent )
|
||||
{
|
||||
pComponent->dwPin_Rs=0u ;
|
||||
pComponent->dwPin_EN=0u ;
|
||||
|
||||
return 0u ;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Initialize Rs pin of transceiver
|
||||
*
|
||||
* \param pComponent pointer on SSN65HVD234_Data
|
||||
* \param pPIO_Rs pointer on PIOx base for transceiver Rs pin
|
||||
* \param dwPin_Rs PIO pin index for transceiver Rs pin
|
||||
*
|
||||
* \return 0 if OK
|
||||
*/
|
||||
extern uint32_t SN65HVD234_SetRs( SSN65HVD234_Data* pComponent, uint32_t dwPin_Rs )
|
||||
{
|
||||
pComponent->dwPin_Rs=dwPin_Rs ;
|
||||
|
||||
pinMode( dwPin_Rs, OUTPUT ) ;
|
||||
|
||||
return 0u ;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Initialize EN pin of transceiver
|
||||
*
|
||||
* \param pComponent pointer on SSN65HVD234_Data
|
||||
* \param pPIO_EN pointer on PIOx base for transceiver EN pin
|
||||
* \param dwPin_EN PIO pin index for transceiver EN pin
|
||||
*
|
||||
* \return 0 if OK
|
||||
*/
|
||||
extern uint32_t SN65HVD234_SetEN( SSN65HVD234_Data* pComponent, uint32_t dwPin_EN )
|
||||
{
|
||||
pComponent->dwPin_EN=dwPin_EN ;
|
||||
|
||||
pinMode( dwPin_EN, OUTPUT ) ;
|
||||
|
||||
return 0u ;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Enable transceiver
|
||||
*
|
||||
* \param pComponent pointer on SSN65HVD234_Data
|
||||
*
|
||||
* \return 0 if OK
|
||||
*/
|
||||
extern uint32_t SN65HVD234_Enable( SSN65HVD234_Data* pComponent )
|
||||
{
|
||||
// Raise EN of SN65HVD234 to High Level (Vcc)
|
||||
digitalWrite( pComponent->dwPin_EN, HIGH ) ;
|
||||
|
||||
return 0u ;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Disable transceiver
|
||||
*
|
||||
* \param pComponent pointer on SSN65HVD234_Data
|
||||
*
|
||||
* \return 0 if OK
|
||||
*/
|
||||
extern uint32_t SN65HVD234_Disable( SSN65HVD234_Data* pComponent )
|
||||
{
|
||||
// Lower EN of SN65HVD234 to Low Level (0.0v)
|
||||
digitalWrite( pComponent->dwPin_EN, LOW ) ;
|
||||
|
||||
return 0u ;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Turn component into lowpower mode
|
||||
*
|
||||
* \param pComponent pointer on SSN65HVD234_Data
|
||||
*
|
||||
* \return 0 if OK
|
||||
*/
|
||||
extern uint32_t SN65HVD234_EnableLowPower( SSN65HVD234_Data* pComponent )
|
||||
{
|
||||
// Raise Rs of SN65HVD234 to more than 0.75v
|
||||
digitalWrite( pComponent->dwPin_Rs, HIGH ) ;
|
||||
|
||||
// Now, SN65HVD234 is only listening
|
||||
|
||||
return 0u ;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Restore Normal mode by leaving lowpower mode
|
||||
*
|
||||
* \param pComponent pointer on SSN65HVD234_Data
|
||||
*
|
||||
* \return 0 if OK
|
||||
*/
|
||||
extern uint32_t SN65HVD234_DisableLowPower( SSN65HVD234_Data* pComponent )
|
||||
{
|
||||
// Lower Rs of SN65HVD234 to 0.0v < 0.33v
|
||||
digitalWrite( pComponent->dwPin_Rs, LOW ) ;
|
||||
|
||||
return 0u ;
|
||||
}
|
||||
|
@ -1,58 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2013 Arduino. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
/**
|
||||
* \file
|
||||
*
|
||||
* Include Defines & macros for the SN65HVD234.
|
||||
*/
|
||||
|
||||
#ifndef _CAN_SN65HVD234_
|
||||
#define _CAN_SN65HVD234_
|
||||
|
||||
#include "variant.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
|
||||
typedef struct _SSN65HVD234_Data
|
||||
{
|
||||
/** Rs Pin on PIO */
|
||||
uint32_t dwPin_Rs ;
|
||||
|
||||
/** EN Pin on PIO */
|
||||
uint32_t dwPin_EN ;
|
||||
} SSN65HVD234_Data ;
|
||||
|
||||
extern uint32_t SN65HVD234_Init( SSN65HVD234_Data* pComponent ) ;
|
||||
extern uint32_t SN65HVD234_SetRs( SSN65HVD234_Data* pComponent, uint32_t dwPin_Rs ) ;
|
||||
extern uint32_t SN65HVD234_SetEN( SSN65HVD234_Data* pComponent, uint32_t dwPin_EN ) ;
|
||||
|
||||
extern uint32_t SN65HVD234_Enable( SSN65HVD234_Data* pComponent ) ;
|
||||
extern uint32_t SN65HVD234_Disable( SSN65HVD234_Data* pComponent ) ;
|
||||
|
||||
extern uint32_t SN65HVD234_EnableLowPower( SSN65HVD234_Data* pComponent ) ;
|
||||
extern uint32_t SN65HVD234_DisableLowPower( SSN65HVD234_Data* pComponent ) ;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* _CAN_SN65HVD234_ */
|
@ -1,480 +0,0 @@
|
||||
// DHCP Library v0.3 - April 25, 2009
|
||||
// Author: Jordan Terrell - blog.jordanterrell.com
|
||||
|
||||
#include "w5100.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include "Dhcp.h"
|
||||
#include "Arduino.h"
|
||||
#include "util.h"
|
||||
|
||||
int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout)
|
||||
{
|
||||
_dhcpLeaseTime=0;
|
||||
_dhcpT1=0;
|
||||
_dhcpT2=0;
|
||||
_lastCheck=0;
|
||||
_timeout = timeout;
|
||||
_responseTimeout = responseTimeout;
|
||||
|
||||
// zero out _dhcpMacAddr
|
||||
memset(_dhcpMacAddr, 0, 6);
|
||||
reset_DHCP_lease();
|
||||
|
||||
memcpy((void*)_dhcpMacAddr, (void*)mac, 6);
|
||||
_dhcp_state = STATE_DHCP_START;
|
||||
return request_DHCP_lease();
|
||||
}
|
||||
|
||||
void DhcpClass::reset_DHCP_lease(){
|
||||
// zero out _dhcpSubnetMask, _dhcpGatewayIp, _dhcpLocalIp, _dhcpDhcpServerIp, _dhcpDnsServerIp
|
||||
memset(_dhcpLocalIp, 0, 20);
|
||||
}
|
||||
|
||||
//return:0 on error, 1 if request is sent and response is received
|
||||
int DhcpClass::request_DHCP_lease(){
|
||||
|
||||
uint8_t messageType = 0;
|
||||
|
||||
|
||||
|
||||
// Pick an initial transaction ID
|
||||
_dhcpTransactionId = random(1UL, 2000UL);
|
||||
_dhcpInitialTransactionId = _dhcpTransactionId;
|
||||
|
||||
_dhcpUdpSocket.stop();
|
||||
if (_dhcpUdpSocket.begin(DHCP_CLIENT_PORT) == 0)
|
||||
{
|
||||
// Couldn't get a socket
|
||||
return 0;
|
||||
}
|
||||
|
||||
presend_DHCP();
|
||||
|
||||
int result = 0;
|
||||
|
||||
unsigned long startTime = millis();
|
||||
|
||||
while(_dhcp_state != STATE_DHCP_LEASED)
|
||||
{
|
||||
if(_dhcp_state == STATE_DHCP_START)
|
||||
{
|
||||
_dhcpTransactionId++;
|
||||
|
||||
send_DHCP_MESSAGE(DHCP_DISCOVER, ((millis() - startTime) / 1000));
|
||||
_dhcp_state = STATE_DHCP_DISCOVER;
|
||||
}
|
||||
else if(_dhcp_state == STATE_DHCP_REREQUEST){
|
||||
_dhcpTransactionId++;
|
||||
send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime)/1000));
|
||||
_dhcp_state = STATE_DHCP_REQUEST;
|
||||
}
|
||||
else if(_dhcp_state == STATE_DHCP_DISCOVER)
|
||||
{
|
||||
uint32_t respId;
|
||||
messageType = parseDHCPResponse(_responseTimeout, respId);
|
||||
if(messageType == DHCP_OFFER)
|
||||
{
|
||||
// We'll use the transaction ID that the offer came with,
|
||||
// rather than the one we were up to
|
||||
_dhcpTransactionId = respId;
|
||||
send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime) / 1000));
|
||||
_dhcp_state = STATE_DHCP_REQUEST;
|
||||
}
|
||||
}
|
||||
else if(_dhcp_state == STATE_DHCP_REQUEST)
|
||||
{
|
||||
uint32_t respId;
|
||||
messageType = parseDHCPResponse(_responseTimeout, respId);
|
||||
if(messageType == DHCP_ACK)
|
||||
{
|
||||
_dhcp_state = STATE_DHCP_LEASED;
|
||||
result = 1;
|
||||
//use default lease time if we didn't get it
|
||||
if(_dhcpLeaseTime == 0){
|
||||
_dhcpLeaseTime = DEFAULT_LEASE;
|
||||
}
|
||||
//calculate T1 & T2 if we didn't get it
|
||||
if(_dhcpT1 == 0){
|
||||
//T1 should be 50% of _dhcpLeaseTime
|
||||
_dhcpT1 = _dhcpLeaseTime >> 1;
|
||||
}
|
||||
if(_dhcpT2 == 0){
|
||||
//T2 should be 87.5% (7/8ths) of _dhcpLeaseTime
|
||||
_dhcpT2 = _dhcpT1 << 1;
|
||||
}
|
||||
_renewInSec = _dhcpT1;
|
||||
_rebindInSec = _dhcpT2;
|
||||
}
|
||||
else if(messageType == DHCP_NAK)
|
||||
_dhcp_state = STATE_DHCP_START;
|
||||
}
|
||||
|
||||
if(messageType == 255)
|
||||
{
|
||||
messageType = 0;
|
||||
_dhcp_state = STATE_DHCP_START;
|
||||
}
|
||||
|
||||
if(result != 1 && ((millis() - startTime) > _timeout))
|
||||
break;
|
||||
}
|
||||
|
||||
// We're done with the socket now
|
||||
_dhcpUdpSocket.stop();
|
||||
_dhcpTransactionId++;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void DhcpClass::presend_DHCP()
|
||||
{
|
||||
}
|
||||
|
||||
void DhcpClass::send_DHCP_MESSAGE(uint8_t messageType, uint16_t secondsElapsed)
|
||||
{
|
||||
uint8_t buffer[32];
|
||||
memset(buffer, 0, 32);
|
||||
IPAddress dest_addr( 255, 255, 255, 255 ); // Broadcast address
|
||||
|
||||
if (-1 == _dhcpUdpSocket.beginPacket(dest_addr, DHCP_SERVER_PORT))
|
||||
{
|
||||
// FIXME Need to return errors
|
||||
return;
|
||||
}
|
||||
|
||||
buffer[0] = DHCP_BOOTREQUEST; // op
|
||||
buffer[1] = DHCP_HTYPE10MB; // htype
|
||||
buffer[2] = DHCP_HLENETHERNET; // hlen
|
||||
buffer[3] = DHCP_HOPS; // hops
|
||||
|
||||
// xid
|
||||
unsigned long xid = htonl(_dhcpTransactionId);
|
||||
memcpy(buffer + 4, &(xid), 4);
|
||||
|
||||
// 8, 9 - seconds elapsed
|
||||
buffer[8] = ((secondsElapsed & 0xff00) >> 8);
|
||||
buffer[9] = (secondsElapsed & 0x00ff);
|
||||
|
||||
// flags
|
||||
unsigned short flags = htons(DHCP_FLAGSBROADCAST);
|
||||
memcpy(buffer + 10, &(flags), 2);
|
||||
|
||||
// ciaddr: already zeroed
|
||||
// yiaddr: already zeroed
|
||||
// siaddr: already zeroed
|
||||
// giaddr: already zeroed
|
||||
|
||||
//put data in W5100 transmit buffer
|
||||
_dhcpUdpSocket.write(buffer, 28);
|
||||
|
||||
memset(buffer, 0, 32); // clear local buffer
|
||||
|
||||
memcpy(buffer, _dhcpMacAddr, 6); // chaddr
|
||||
|
||||
//put data in W5100 transmit buffer
|
||||
_dhcpUdpSocket.write(buffer, 16);
|
||||
|
||||
memset(buffer, 0, 32); // clear local buffer
|
||||
|
||||
// leave zeroed out for sname && file
|
||||
// put in W5100 transmit buffer x 6 (192 bytes)
|
||||
|
||||
for(int i = 0; i < 6; i++) {
|
||||
_dhcpUdpSocket.write(buffer, 32);
|
||||
}
|
||||
|
||||
// OPT - Magic Cookie
|
||||
buffer[0] = (uint8_t)((MAGIC_COOKIE >> 24)& 0xFF);
|
||||
buffer[1] = (uint8_t)((MAGIC_COOKIE >> 16)& 0xFF);
|
||||
buffer[2] = (uint8_t)((MAGIC_COOKIE >> 8)& 0xFF);
|
||||
buffer[3] = (uint8_t)(MAGIC_COOKIE& 0xFF);
|
||||
|
||||
// OPT - message type
|
||||
buffer[4] = dhcpMessageType;
|
||||
buffer[5] = 0x01;
|
||||
buffer[6] = messageType; //DHCP_REQUEST;
|
||||
|
||||
// OPT - client identifier
|
||||
buffer[7] = dhcpClientIdentifier;
|
||||
buffer[8] = 0x07;
|
||||
buffer[9] = 0x01;
|
||||
memcpy(buffer + 10, _dhcpMacAddr, 6);
|
||||
|
||||
// OPT - host name
|
||||
buffer[16] = hostName;
|
||||
buffer[17] = strlen(HOST_NAME) + 6; // length of hostname + last 3 bytes of mac address
|
||||
strcpy((char*)&(buffer[18]), HOST_NAME);
|
||||
|
||||
printByte((char*)&(buffer[24]), _dhcpMacAddr[3]);
|
||||
printByte((char*)&(buffer[26]), _dhcpMacAddr[4]);
|
||||
printByte((char*)&(buffer[28]), _dhcpMacAddr[5]);
|
||||
|
||||
//put data in W5100 transmit buffer
|
||||
_dhcpUdpSocket.write(buffer, 30);
|
||||
|
||||
if(messageType == DHCP_REQUEST)
|
||||
{
|
||||
buffer[0] = dhcpRequestedIPaddr;
|
||||
buffer[1] = 0x04;
|
||||
buffer[2] = _dhcpLocalIp[0];
|
||||
buffer[3] = _dhcpLocalIp[1];
|
||||
buffer[4] = _dhcpLocalIp[2];
|
||||
buffer[5] = _dhcpLocalIp[3];
|
||||
|
||||
buffer[6] = dhcpServerIdentifier;
|
||||
buffer[7] = 0x04;
|
||||
buffer[8] = _dhcpDhcpServerIp[0];
|
||||
buffer[9] = _dhcpDhcpServerIp[1];
|
||||
buffer[10] = _dhcpDhcpServerIp[2];
|
||||
buffer[11] = _dhcpDhcpServerIp[3];
|
||||
|
||||
//put data in W5100 transmit buffer
|
||||
_dhcpUdpSocket.write(buffer, 12);
|
||||
}
|
||||
|
||||
buffer[0] = dhcpParamRequest;
|
||||
buffer[1] = 0x06;
|
||||
buffer[2] = subnetMask;
|
||||
buffer[3] = routersOnSubnet;
|
||||
buffer[4] = dns;
|
||||
buffer[5] = domainName;
|
||||
buffer[6] = dhcpT1value;
|
||||
buffer[7] = dhcpT2value;
|
||||
buffer[8] = endOption;
|
||||
|
||||
//put data in W5100 transmit buffer
|
||||
_dhcpUdpSocket.write(buffer, 9);
|
||||
|
||||
_dhcpUdpSocket.endPacket();
|
||||
}
|
||||
|
||||
uint8_t DhcpClass::parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId)
|
||||
{
|
||||
uint8_t type = 0;
|
||||
uint8_t opt_len = 0;
|
||||
|
||||
unsigned long startTime = millis();
|
||||
|
||||
while(_dhcpUdpSocket.parsePacket() <= 0)
|
||||
{
|
||||
if((millis() - startTime) > responseTimeout)
|
||||
{
|
||||
return 255;
|
||||
}
|
||||
delay(50);
|
||||
}
|
||||
// start reading in the packet
|
||||
RIP_MSG_FIXED fixedMsg;
|
||||
_dhcpUdpSocket.read((uint8_t*)&fixedMsg, sizeof(RIP_MSG_FIXED));
|
||||
|
||||
if(fixedMsg.op == DHCP_BOOTREPLY && _dhcpUdpSocket.remotePort() == DHCP_SERVER_PORT)
|
||||
{
|
||||
transactionId = ntohl(fixedMsg.xid);
|
||||
if(memcmp(fixedMsg.chaddr, _dhcpMacAddr, 6) != 0 || (transactionId < _dhcpInitialTransactionId) || (transactionId > _dhcpTransactionId))
|
||||
{
|
||||
// Need to read the rest of the packet here regardless
|
||||
_dhcpUdpSocket.flush();
|
||||
return 0;
|
||||
}
|
||||
|
||||
memcpy(_dhcpLocalIp, fixedMsg.yiaddr, 4);
|
||||
|
||||
// Skip to the option part
|
||||
// Doing this a byte at a time so we don't have to put a big buffer
|
||||
// on the stack (as we don't have lots of memory lying around)
|
||||
for (int i =0; i < (240 - (int)sizeof(RIP_MSG_FIXED)); i++)
|
||||
{
|
||||
_dhcpUdpSocket.read(); // we don't care about the returned byte
|
||||
}
|
||||
|
||||
while (_dhcpUdpSocket.available() > 0)
|
||||
{
|
||||
switch (_dhcpUdpSocket.read())
|
||||
{
|
||||
case endOption :
|
||||
break;
|
||||
|
||||
case padOption :
|
||||
break;
|
||||
|
||||
case dhcpMessageType :
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
type = _dhcpUdpSocket.read();
|
||||
break;
|
||||
|
||||
case subnetMask :
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
_dhcpUdpSocket.read(_dhcpSubnetMask, 4);
|
||||
break;
|
||||
|
||||
case routersOnSubnet :
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
_dhcpUdpSocket.read(_dhcpGatewayIp, 4);
|
||||
for (int i = 0; i < opt_len-4; i++)
|
||||
{
|
||||
_dhcpUdpSocket.read();
|
||||
}
|
||||
break;
|
||||
|
||||
case dns :
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
_dhcpUdpSocket.read(_dhcpDnsServerIp, 4);
|
||||
for (int i = 0; i < opt_len-4; i++)
|
||||
{
|
||||
_dhcpUdpSocket.read();
|
||||
}
|
||||
break;
|
||||
|
||||
case dhcpServerIdentifier :
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
if( *((uint32_t*)_dhcpDhcpServerIp) == 0 ||
|
||||
IPAddress(_dhcpDhcpServerIp) == _dhcpUdpSocket.remoteIP() )
|
||||
{
|
||||
_dhcpUdpSocket.read(_dhcpDhcpServerIp, sizeof(_dhcpDhcpServerIp));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Skip over the rest of this option
|
||||
while (opt_len--)
|
||||
{
|
||||
_dhcpUdpSocket.read();
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case dhcpT1value :
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
_dhcpUdpSocket.read((uint8_t*)&_dhcpT1, sizeof(_dhcpT1));
|
||||
_dhcpT1 = ntohl(_dhcpT1);
|
||||
break;
|
||||
|
||||
case dhcpT2value :
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
_dhcpUdpSocket.read((uint8_t*)&_dhcpT2, sizeof(_dhcpT2));
|
||||
_dhcpT2 = ntohl(_dhcpT2);
|
||||
break;
|
||||
|
||||
case dhcpIPaddrLeaseTime :
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
_dhcpUdpSocket.read((uint8_t*)&_dhcpLeaseTime, sizeof(_dhcpLeaseTime));
|
||||
_dhcpLeaseTime = ntohl(_dhcpLeaseTime);
|
||||
_renewInSec = _dhcpLeaseTime;
|
||||
break;
|
||||
|
||||
default :
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
// Skip over the rest of this option
|
||||
while (opt_len--)
|
||||
{
|
||||
_dhcpUdpSocket.read();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Need to skip to end of the packet regardless here
|
||||
_dhcpUdpSocket.flush();
|
||||
|
||||
return type;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
returns:
|
||||
0/DHCP_CHECK_NONE: nothing happened
|
||||
1/DHCP_CHECK_RENEW_FAIL: renew failed
|
||||
2/DHCP_CHECK_RENEW_OK: renew success
|
||||
3/DHCP_CHECK_REBIND_FAIL: rebind fail
|
||||
4/DHCP_CHECK_REBIND_OK: rebind success
|
||||
*/
|
||||
int DhcpClass::checkLease(){
|
||||
//this uses a signed / unsigned trick to deal with millis overflow
|
||||
unsigned long now = millis();
|
||||
signed long snow = (long)now;
|
||||
int rc=DHCP_CHECK_NONE;
|
||||
if (_lastCheck != 0){
|
||||
signed long factor;
|
||||
//calc how many ms past the timeout we are
|
||||
factor = snow - (long)_secTimeout;
|
||||
//if on or passed the timeout, reduce the counters
|
||||
if ( factor >= 0 ){
|
||||
//next timeout should be now plus 1000 ms minus parts of second in factor
|
||||
_secTimeout = snow + 1000 - factor % 1000;
|
||||
//how many seconds late are we, minimum 1
|
||||
factor = factor / 1000 +1;
|
||||
|
||||
//reduce the counters by that mouch
|
||||
//if we can assume that the cycle time (factor) is fairly constant
|
||||
//and if the remainder is less than cycle time * 2
|
||||
//do it early instead of late
|
||||
if(_renewInSec < factor*2 )
|
||||
_renewInSec = 0;
|
||||
else
|
||||
_renewInSec -= factor;
|
||||
|
||||
if(_rebindInSec < factor*2 )
|
||||
_rebindInSec = 0;
|
||||
else
|
||||
_rebindInSec -= factor;
|
||||
}
|
||||
|
||||
//if we have a lease but should renew, do it
|
||||
if (_dhcp_state == STATE_DHCP_LEASED && _renewInSec <=0){
|
||||
_dhcp_state = STATE_DHCP_REREQUEST;
|
||||
rc = 1 + request_DHCP_lease();
|
||||
}
|
||||
|
||||
//if we have a lease or is renewing but should bind, do it
|
||||
if( (_dhcp_state == STATE_DHCP_LEASED || _dhcp_state == STATE_DHCP_START) && _rebindInSec <=0){
|
||||
//this should basically restart completely
|
||||
_dhcp_state = STATE_DHCP_START;
|
||||
reset_DHCP_lease();
|
||||
rc = 3 + request_DHCP_lease();
|
||||
}
|
||||
}
|
||||
else{
|
||||
_secTimeout = snow + 1000;
|
||||
}
|
||||
|
||||
_lastCheck = now;
|
||||
return rc;
|
||||
}
|
||||
|
||||
IPAddress DhcpClass::getLocalIp()
|
||||
{
|
||||
return IPAddress(_dhcpLocalIp);
|
||||
}
|
||||
|
||||
IPAddress DhcpClass::getSubnetMask()
|
||||
{
|
||||
return IPAddress(_dhcpSubnetMask);
|
||||
}
|
||||
|
||||
IPAddress DhcpClass::getGatewayIp()
|
||||
{
|
||||
return IPAddress(_dhcpGatewayIp);
|
||||
}
|
||||
|
||||
IPAddress DhcpClass::getDhcpServerIp()
|
||||
{
|
||||
return IPAddress(_dhcpDhcpServerIp);
|
||||
}
|
||||
|
||||
IPAddress DhcpClass::getDnsServerIp()
|
||||
{
|
||||
return IPAddress(_dhcpDnsServerIp);
|
||||
}
|
||||
|
||||
void DhcpClass::printByte(char * buf, uint8_t n ) {
|
||||
char *str = &buf[1];
|
||||
buf[0]='0';
|
||||
do {
|
||||
unsigned long m = n;
|
||||
n /= 16;
|
||||
char c = m - 16 * n;
|
||||
*str-- = c < 10 ? c + '0' : c + 'A' - 10;
|
||||
} while(n);
|
||||
}
|
@ -1,178 +0,0 @@
|
||||
// DHCP Library v0.3 - April 25, 2009
|
||||
// Author: Jordan Terrell - blog.jordanterrell.com
|
||||
|
||||
#ifndef Dhcp_h
|
||||
#define Dhcp_h
|
||||
|
||||
#include "EthernetUdp.h"
|
||||
|
||||
/* DHCP state machine. */
|
||||
#define STATE_DHCP_START 0
|
||||
#define STATE_DHCP_DISCOVER 1
|
||||
#define STATE_DHCP_REQUEST 2
|
||||
#define STATE_DHCP_LEASED 3
|
||||
#define STATE_DHCP_REREQUEST 4
|
||||
#define STATE_DHCP_RELEASE 5
|
||||
|
||||
#define DHCP_FLAGSBROADCAST 0x8000
|
||||
|
||||
/* UDP port numbers for DHCP */
|
||||
#define DHCP_SERVER_PORT 67 /* from server to client */
|
||||
#define DHCP_CLIENT_PORT 68 /* from client to server */
|
||||
|
||||
/* DHCP message OP code */
|
||||
#define DHCP_BOOTREQUEST 1
|
||||
#define DHCP_BOOTREPLY 2
|
||||
|
||||
/* DHCP message type */
|
||||
#define DHCP_DISCOVER 1
|
||||
#define DHCP_OFFER 2
|
||||
#define DHCP_REQUEST 3
|
||||
#define DHCP_DECLINE 4
|
||||
#define DHCP_ACK 5
|
||||
#define DHCP_NAK 6
|
||||
#define DHCP_RELEASE 7
|
||||
#define DHCP_INFORM 8
|
||||
|
||||
#define DHCP_HTYPE10MB 1
|
||||
#define DHCP_HTYPE100MB 2
|
||||
|
||||
#define DHCP_HLENETHERNET 6
|
||||
#define DHCP_HOPS 0
|
||||
#define DHCP_SECS 0
|
||||
|
||||
#define MAGIC_COOKIE 0x63825363
|
||||
#define MAX_DHCP_OPT 16
|
||||
|
||||
#define HOST_NAME "WIZnet"
|
||||
#define DEFAULT_LEASE (900) //default lease time in seconds
|
||||
|
||||
#define DHCP_CHECK_NONE (0)
|
||||
#define DHCP_CHECK_RENEW_FAIL (1)
|
||||
#define DHCP_CHECK_RENEW_OK (2)
|
||||
#define DHCP_CHECK_REBIND_FAIL (3)
|
||||
#define DHCP_CHECK_REBIND_OK (4)
|
||||
|
||||
enum
|
||||
{
|
||||
padOption = 0,
|
||||
subnetMask = 1,
|
||||
timerOffset = 2,
|
||||
routersOnSubnet = 3,
|
||||
/* timeServer = 4,
|
||||
nameServer = 5,*/
|
||||
dns = 6,
|
||||
/*logServer = 7,
|
||||
cookieServer = 8,
|
||||
lprServer = 9,
|
||||
impressServer = 10,
|
||||
resourceLocationServer = 11,*/
|
||||
hostName = 12,
|
||||
/*bootFileSize = 13,
|
||||
meritDumpFile = 14,*/
|
||||
domainName = 15,
|
||||
/*swapServer = 16,
|
||||
rootPath = 17,
|
||||
extentionsPath = 18,
|
||||
IPforwarding = 19,
|
||||
nonLocalSourceRouting = 20,
|
||||
policyFilter = 21,
|
||||
maxDgramReasmSize = 22,
|
||||
defaultIPTTL = 23,
|
||||
pathMTUagingTimeout = 24,
|
||||
pathMTUplateauTable = 25,
|
||||
ifMTU = 26,
|
||||
allSubnetsLocal = 27,
|
||||
broadcastAddr = 28,
|
||||
performMaskDiscovery = 29,
|
||||
maskSupplier = 30,
|
||||
performRouterDiscovery = 31,
|
||||
routerSolicitationAddr = 32,
|
||||
staticRoute = 33,
|
||||
trailerEncapsulation = 34,
|
||||
arpCacheTimeout = 35,
|
||||
ethernetEncapsulation = 36,
|
||||
tcpDefaultTTL = 37,
|
||||
tcpKeepaliveInterval = 38,
|
||||
tcpKeepaliveGarbage = 39,
|
||||
nisDomainName = 40,
|
||||
nisServers = 41,
|
||||
ntpServers = 42,
|
||||
vendorSpecificInfo = 43,
|
||||
netBIOSnameServer = 44,
|
||||
netBIOSdgramDistServer = 45,
|
||||
netBIOSnodeType = 46,
|
||||
netBIOSscope = 47,
|
||||
xFontServer = 48,
|
||||
xDisplayManager = 49,*/
|
||||
dhcpRequestedIPaddr = 50,
|
||||
dhcpIPaddrLeaseTime = 51,
|
||||
/*dhcpOptionOverload = 52,*/
|
||||
dhcpMessageType = 53,
|
||||
dhcpServerIdentifier = 54,
|
||||
dhcpParamRequest = 55,
|
||||
/*dhcpMsg = 56,
|
||||
dhcpMaxMsgSize = 57,*/
|
||||
dhcpT1value = 58,
|
||||
dhcpT2value = 59,
|
||||
/*dhcpClassIdentifier = 60,*/
|
||||
dhcpClientIdentifier = 61,
|
||||
endOption = 255
|
||||
};
|
||||
|
||||
typedef struct _RIP_MSG_FIXED
|
||||
{
|
||||
uint8_t op;
|
||||
uint8_t htype;
|
||||
uint8_t hlen;
|
||||
uint8_t hops;
|
||||
uint32_t xid;
|
||||
uint16_t secs;
|
||||
uint16_t flags;
|
||||
uint8_t ciaddr[4];
|
||||
uint8_t yiaddr[4];
|
||||
uint8_t siaddr[4];
|
||||
uint8_t giaddr[4];
|
||||
uint8_t chaddr[6];
|
||||
}RIP_MSG_FIXED;
|
||||
|
||||
class DhcpClass {
|
||||
private:
|
||||
uint32_t _dhcpInitialTransactionId;
|
||||
uint32_t _dhcpTransactionId;
|
||||
uint8_t _dhcpMacAddr[6];
|
||||
uint8_t _dhcpLocalIp[4];
|
||||
uint8_t _dhcpSubnetMask[4];
|
||||
uint8_t _dhcpGatewayIp[4];
|
||||
uint8_t _dhcpDhcpServerIp[4];
|
||||
uint8_t _dhcpDnsServerIp[4];
|
||||
uint32_t _dhcpLeaseTime;
|
||||
uint32_t _dhcpT1, _dhcpT2;
|
||||
signed long _renewInSec;
|
||||
signed long _rebindInSec;
|
||||
signed long _lastCheck;
|
||||
unsigned long _timeout;
|
||||
unsigned long _responseTimeout;
|
||||
unsigned long _secTimeout;
|
||||
uint8_t _dhcp_state;
|
||||
EthernetUDP _dhcpUdpSocket;
|
||||
|
||||
int request_DHCP_lease();
|
||||
void reset_DHCP_lease();
|
||||
void presend_DHCP();
|
||||
void send_DHCP_MESSAGE(uint8_t, uint16_t);
|
||||
void printByte(char *, uint8_t);
|
||||
|
||||
uint8_t parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId);
|
||||
public:
|
||||
IPAddress getLocalIp();
|
||||
IPAddress getSubnetMask();
|
||||
IPAddress getGatewayIp();
|
||||
IPAddress getDhcpServerIp();
|
||||
IPAddress getDnsServerIp();
|
||||
|
||||
int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 4000);
|
||||
int checkLease();
|
||||
};
|
||||
|
||||
#endif
|
@ -1,423 +0,0 @@
|
||||
// Arduino DNS client for WizNet5100-based Ethernet shield
|
||||
// (c) Copyright 2009-2010 MCQN Ltd.
|
||||
// Released under Apache License, version 2.0
|
||||
|
||||
#include "w5100.h"
|
||||
#include "EthernetUdp.h"
|
||||
#include "util.h"
|
||||
|
||||
#include "Dns.h"
|
||||
#include <string.h>
|
||||
//#include <stdlib.h>
|
||||
#include "Arduino.h"
|
||||
|
||||
|
||||
#define SOCKET_NONE 255
|
||||
// Various flags and header field values for a DNS message
|
||||
#define UDP_HEADER_SIZE 8
|
||||
#define DNS_HEADER_SIZE 12
|
||||
#define TTL_SIZE 4
|
||||
#define QUERY_FLAG (0)
|
||||
#define RESPONSE_FLAG (1<<15)
|
||||
#define QUERY_RESPONSE_MASK (1<<15)
|
||||
#define OPCODE_STANDARD_QUERY (0)
|
||||
#define OPCODE_INVERSE_QUERY (1<<11)
|
||||
#define OPCODE_STATUS_REQUEST (2<<11)
|
||||
#define OPCODE_MASK (15<<11)
|
||||
#define AUTHORITATIVE_FLAG (1<<10)
|
||||
#define TRUNCATION_FLAG (1<<9)
|
||||
#define RECURSION_DESIRED_FLAG (1<<8)
|
||||
#define RECURSION_AVAILABLE_FLAG (1<<7)
|
||||
#define RESP_NO_ERROR (0)
|
||||
#define RESP_FORMAT_ERROR (1)
|
||||
#define RESP_SERVER_FAILURE (2)
|
||||
#define RESP_NAME_ERROR (3)
|
||||
#define RESP_NOT_IMPLEMENTED (4)
|
||||
#define RESP_REFUSED (5)
|
||||
#define RESP_MASK (15)
|
||||
#define TYPE_A (0x0001)
|
||||
#define CLASS_IN (0x0001)
|
||||
#define LABEL_COMPRESSION_MASK (0xC0)
|
||||
// Port number that DNS servers listen on
|
||||
#define DNS_PORT 53
|
||||
|
||||
// Possible return codes from ProcessResponse
|
||||
#define SUCCESS 1
|
||||
#define TIMED_OUT -1
|
||||
#define INVALID_SERVER -2
|
||||
#define TRUNCATED -3
|
||||
#define INVALID_RESPONSE -4
|
||||
|
||||
void DNSClient::begin(const IPAddress& aDNSServer)
|
||||
{
|
||||
iDNSServer = aDNSServer;
|
||||
iRequestId = 0;
|
||||
}
|
||||
|
||||
|
||||
int DNSClient::inet_aton(const char* aIPAddrString, IPAddress& aResult)
|
||||
{
|
||||
// See if we've been given a valid IP address
|
||||
const char* p =aIPAddrString;
|
||||
while (*p &&
|
||||
( (*p == '.') || (*p >= '0') || (*p <= '9') ))
|
||||
{
|
||||
p++;
|
||||
}
|
||||
|
||||
if (*p == '\0')
|
||||
{
|
||||
// It's looking promising, we haven't found any invalid characters
|
||||
p = aIPAddrString;
|
||||
int segment =0;
|
||||
int segmentValue =0;
|
||||
while (*p && (segment < 4))
|
||||
{
|
||||
if (*p == '.')
|
||||
{
|
||||
// We've reached the end of a segment
|
||||
if (segmentValue > 255)
|
||||
{
|
||||
// You can't have IP address segments that don't fit in a byte
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
aResult[segment] = (byte)segmentValue;
|
||||
segment++;
|
||||
segmentValue = 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Next digit
|
||||
segmentValue = (segmentValue*10)+(*p - '0');
|
||||
}
|
||||
p++;
|
||||
}
|
||||
// We've reached the end of address, but there'll still be the last
|
||||
// segment to deal with
|
||||
if ((segmentValue > 255) || (segment > 3))
|
||||
{
|
||||
// You can't have IP address segments that don't fit in a byte,
|
||||
// or more than four segments
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
aResult[segment] = (byte)segmentValue;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult)
|
||||
{
|
||||
int ret =0;
|
||||
|
||||
// See if it's a numeric IP address
|
||||
if (inet_aton(aHostname, aResult))
|
||||
{
|
||||
// It is, our work here is done
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Check we've got a valid DNS server to use
|
||||
if (iDNSServer == INADDR_NONE)
|
||||
{
|
||||
return INVALID_SERVER;
|
||||
}
|
||||
|
||||
// Find a socket to use
|
||||
if (iUdp.begin(1024+(millis() & 0xF)) == 1)
|
||||
{
|
||||
// Try up to three times
|
||||
int retries = 0;
|
||||
// while ((retries < 3) && (ret <= 0))
|
||||
{
|
||||
// Send DNS request
|
||||
ret = iUdp.beginPacket(iDNSServer, DNS_PORT);
|
||||
if (ret != 0)
|
||||
{
|
||||
// Now output the request data
|
||||
ret = BuildRequest(aHostname);
|
||||
if (ret != 0)
|
||||
{
|
||||
// And finally send the request
|
||||
ret = iUdp.endPacket();
|
||||
if (ret != 0)
|
||||
{
|
||||
// Now wait for a response
|
||||
int wait_retries = 0;
|
||||
ret = TIMED_OUT;
|
||||
while ((wait_retries < 3) && (ret == TIMED_OUT))
|
||||
{
|
||||
ret = ProcessResponse(5000, aResult);
|
||||
wait_retries++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
retries++;
|
||||
}
|
||||
|
||||
// We're done with the socket now
|
||||
iUdp.stop();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
uint16_t DNSClient::BuildRequest(const char* aName)
|
||||
{
|
||||
// Build header
|
||||
// 1 1 1 1 1 1
|
||||
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
|
||||
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|
||||
// | ID |
|
||||
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|
||||
// |QR| Opcode |AA|TC|RD|RA| Z | RCODE |
|
||||
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|
||||
// | QDCOUNT |
|
||||
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|
||||
// | ANCOUNT |
|
||||
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|
||||
// | NSCOUNT |
|
||||
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|
||||
// | ARCOUNT |
|
||||
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|
||||
// As we only support one request at a time at present, we can simplify
|
||||
// some of this header
|
||||
iRequestId = millis(); // generate a random ID
|
||||
uint16_t twoByteBuffer;
|
||||
|
||||
// FIXME We should also check that there's enough space available to write to, rather
|
||||
// FIXME than assume there's enough space (as the code does at present)
|
||||
iUdp.write((uint8_t*)&iRequestId, sizeof(iRequestId));
|
||||
|
||||
twoByteBuffer = htons(QUERY_FLAG | OPCODE_STANDARD_QUERY | RECURSION_DESIRED_FLAG);
|
||||
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
|
||||
|
||||
twoByteBuffer = htons(1); // One question record
|
||||
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
|
||||
|
||||
twoByteBuffer = 0; // Zero answer records
|
||||
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
|
||||
|
||||
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
|
||||
// and zero additional records
|
||||
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
|
||||
|
||||
// Build question
|
||||
const char* start =aName;
|
||||
const char* end =start;
|
||||
uint8_t len;
|
||||
// Run through the name being requested
|
||||
while (*end)
|
||||
{
|
||||
// Find out how long this section of the name is
|
||||
end = start;
|
||||
while (*end && (*end != '.') )
|
||||
{
|
||||
end++;
|
||||
}
|
||||
|
||||
if (end-start > 0)
|
||||
{
|
||||
// Write out the size of this section
|
||||
len = end-start;
|
||||
iUdp.write(&len, sizeof(len));
|
||||
// And then write out the section
|
||||
iUdp.write((uint8_t*)start, end-start);
|
||||
}
|
||||
start = end+1;
|
||||
}
|
||||
|
||||
// We've got to the end of the question name, so
|
||||
// terminate it with a zero-length section
|
||||
len = 0;
|
||||
iUdp.write(&len, sizeof(len));
|
||||
// Finally the type and class of question
|
||||
twoByteBuffer = htons(TYPE_A);
|
||||
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
|
||||
|
||||
twoByteBuffer = htons(CLASS_IN); // Internet class of question
|
||||
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
|
||||
// Success! Everything buffered okay
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
uint16_t DNSClient::ProcessResponse(uint16_t aTimeout, IPAddress& aAddress)
|
||||
{
|
||||
uint32_t startTime = millis();
|
||||
|
||||
// Wait for a response packet
|
||||
while(iUdp.parsePacket() <= 0)
|
||||
{
|
||||
if((millis() - startTime) > aTimeout)
|
||||
return TIMED_OUT;
|
||||
delay(50);
|
||||
}
|
||||
|
||||
// We've had a reply!
|
||||
// Read the UDP header
|
||||
uint8_t header[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header
|
||||
// Check that it's a response from the right server and the right port
|
||||
if ( (iDNSServer != iUdp.remoteIP()) ||
|
||||
(iUdp.remotePort() != DNS_PORT) )
|
||||
{
|
||||
// It's not from who we expected
|
||||
return INVALID_SERVER;
|
||||
}
|
||||
|
||||
// Read through the rest of the response
|
||||
if (iUdp.available() < DNS_HEADER_SIZE)
|
||||
{
|
||||
return TRUNCATED;
|
||||
}
|
||||
iUdp.read(header, DNS_HEADER_SIZE);
|
||||
|
||||
uint16_t header_flags = htons(*((uint16_t*)&header[2]));
|
||||
// Check that it's a response to this request
|
||||
if ( ( iRequestId != (*((uint16_t*)&header[0])) ) ||
|
||||
((header_flags & QUERY_RESPONSE_MASK) != (uint16_t)RESPONSE_FLAG) )
|
||||
{
|
||||
// Mark the entire packet as read
|
||||
iUdp.flush();
|
||||
return INVALID_RESPONSE;
|
||||
}
|
||||
// Check for any errors in the response (or in our request)
|
||||
// although we don't do anything to get round these
|
||||
if ( (header_flags & TRUNCATION_FLAG) || (header_flags & RESP_MASK) )
|
||||
{
|
||||
// Mark the entire packet as read
|
||||
iUdp.flush();
|
||||
return -5; //INVALID_RESPONSE;
|
||||
}
|
||||
|
||||
// And make sure we've got (at least) one answer
|
||||
uint16_t answerCount = htons(*((uint16_t*)&header[6]));
|
||||
if (answerCount == 0 )
|
||||
{
|
||||
// Mark the entire packet as read
|
||||
iUdp.flush();
|
||||
return -6; //INVALID_RESPONSE;
|
||||
}
|
||||
|
||||
// Skip over any questions
|
||||
for (uint16_t i =0; i < htons(*((uint16_t*)&header[4])); i++)
|
||||
{
|
||||
// Skip over the name
|
||||
uint8_t len;
|
||||
do
|
||||
{
|
||||
iUdp.read(&len, sizeof(len));
|
||||
if (len > 0)
|
||||
{
|
||||
// Don't need to actually read the data out for the string, just
|
||||
// advance ptr to beyond it
|
||||
while(len--)
|
||||
{
|
||||
iUdp.read(); // we don't care about the returned byte
|
||||
}
|
||||
}
|
||||
} while (len != 0);
|
||||
|
||||
// Now jump over the type and class
|
||||
for (int i =0; i < 4; i++)
|
||||
{
|
||||
iUdp.read(); // we don't care about the returned byte
|
||||
}
|
||||
}
|
||||
|
||||
// Now we're up to the bit we're interested in, the answer
|
||||
// There might be more than one answer (although we'll just use the first
|
||||
// type A answer) and some authority and additional resource records but
|
||||
// we're going to ignore all of them.
|
||||
|
||||
for (uint16_t i =0; i < answerCount; i++)
|
||||
{
|
||||
// Skip the name
|
||||
uint8_t len;
|
||||
do
|
||||
{
|
||||
iUdp.read(&len, sizeof(len));
|
||||
if ((len & LABEL_COMPRESSION_MASK) == 0)
|
||||
{
|
||||
// It's just a normal label
|
||||
if (len > 0)
|
||||
{
|
||||
// And it's got a length
|
||||
// Don't need to actually read the data out for the string,
|
||||
// just advance ptr to beyond it
|
||||
while(len--)
|
||||
{
|
||||
iUdp.read(); // we don't care about the returned byte
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// This is a pointer to a somewhere else in the message for the
|
||||
// rest of the name. We don't care about the name, and RFC1035
|
||||
// says that a name is either a sequence of labels ended with a
|
||||
// 0 length octet or a pointer or a sequence of labels ending in
|
||||
// a pointer. Either way, when we get here we're at the end of
|
||||
// the name
|
||||
// Skip over the pointer
|
||||
iUdp.read(); // we don't care about the returned byte
|
||||
// And set len so that we drop out of the name loop
|
||||
len = 0;
|
||||
}
|
||||
} while (len != 0);
|
||||
|
||||
// Check the type and class
|
||||
uint16_t answerType;
|
||||
uint16_t answerClass;
|
||||
iUdp.read((uint8_t*)&answerType, sizeof(answerType));
|
||||
iUdp.read((uint8_t*)&answerClass, sizeof(answerClass));
|
||||
|
||||
// Ignore the Time-To-Live as we don't do any caching
|
||||
for (int i =0; i < TTL_SIZE; i++)
|
||||
{
|
||||
iUdp.read(); // we don't care about the returned byte
|
||||
}
|
||||
|
||||
// And read out the length of this answer
|
||||
// Don't need header_flags anymore, so we can reuse it here
|
||||
iUdp.read((uint8_t*)&header_flags, sizeof(header_flags));
|
||||
|
||||
if ( (htons(answerType) == TYPE_A) && (htons(answerClass) == CLASS_IN) )
|
||||
{
|
||||
if (htons(header_flags) != 4)
|
||||
{
|
||||
// It's a weird size
|
||||
// Mark the entire packet as read
|
||||
iUdp.flush();
|
||||
return -9;//INVALID_RESPONSE;
|
||||
}
|
||||
iUdp.read(aAddress.raw_address(), 4);
|
||||
return SUCCESS;
|
||||
}
|
||||
else
|
||||
{
|
||||
// This isn't an answer type we're after, move onto the next one
|
||||
for (uint16_t i =0; i < htons(header_flags); i++)
|
||||
{
|
||||
iUdp.read(); // we don't care about the returned byte
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mark the entire packet as read
|
||||
iUdp.flush();
|
||||
|
||||
// If we get here then we haven't found an answer
|
||||
return -10;//INVALID_RESPONSE;
|
||||
}
|
||||
|
@ -1,41 +0,0 @@
|
||||
// Arduino DNS client for WizNet5100-based Ethernet shield
|
||||
// (c) Copyright 2009-2010 MCQN Ltd.
|
||||
// Released under Apache License, version 2.0
|
||||
|
||||
#ifndef DNSClient_h
|
||||
#define DNSClient_h
|
||||
|
||||
#include <EthernetUdp.h>
|
||||
|
||||
class DNSClient
|
||||
{
|
||||
public:
|
||||
// ctor
|
||||
void begin(const IPAddress& aDNSServer);
|
||||
|
||||
/** Convert a numeric IP address string into a four-byte IP address.
|
||||
@param aIPAddrString IP address to convert
|
||||
@param aResult IPAddress structure to store the returned IP address
|
||||
@result 1 if aIPAddrString was successfully converted to an IP address,
|
||||
else error code
|
||||
*/
|
||||
int inet_aton(const char *aIPAddrString, IPAddress& aResult);
|
||||
|
||||
/** Resolve the given hostname to an IP address.
|
||||
@param aHostname Name to be resolved
|
||||
@param aResult IPAddress structure to store the returned IP address
|
||||
@result 1 if aIPAddrString was successfully converted to an IP address,
|
||||
else error code
|
||||
*/
|
||||
int getHostByName(const char* aHostname, IPAddress& aResult);
|
||||
|
||||
protected:
|
||||
uint16_t BuildRequest(const char* aName);
|
||||
uint16_t ProcessResponse(uint16_t aTimeout, IPAddress& aAddress);
|
||||
|
||||
IPAddress iDNSServer;
|
||||
uint16_t iRequestId;
|
||||
EthernetUDP iUdp;
|
||||
};
|
||||
|
||||
#endif
|
@ -1,122 +0,0 @@
|
||||
#include "w5100.h"
|
||||
#include "Ethernet.h"
|
||||
#include "Dhcp.h"
|
||||
|
||||
// XXX: don't make assumptions about the value of MAX_SOCK_NUM.
|
||||
uint8_t EthernetClass::_state[MAX_SOCK_NUM] = {
|
||||
0, 0, 0, 0 };
|
||||
uint16_t EthernetClass::_server_port[MAX_SOCK_NUM] = {
|
||||
0, 0, 0, 0 };
|
||||
|
||||
int EthernetClass::begin(uint8_t *mac_address)
|
||||
{
|
||||
static DhcpClass s_dhcp;
|
||||
_dhcp = &s_dhcp;
|
||||
|
||||
|
||||
// Initialise the basic info
|
||||
W5100.init();
|
||||
W5100.setMACAddress(mac_address);
|
||||
W5100.setIPAddress(IPAddress(0,0,0,0).raw_address());
|
||||
|
||||
// Now try to get our config info from a DHCP server
|
||||
int ret = _dhcp->beginWithDHCP(mac_address);
|
||||
if(ret == 1)
|
||||
{
|
||||
// We've successfully found a DHCP server and got our configuration info, so set things
|
||||
// accordingly
|
||||
W5100.setIPAddress(_dhcp->getLocalIp().raw_address());
|
||||
W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address());
|
||||
W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address());
|
||||
_dnsServerAddress = _dhcp->getDnsServerIp();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip)
|
||||
{
|
||||
// Assume the DNS server will be the machine on the same network as the local IP
|
||||
// but with last octet being '1'
|
||||
IPAddress dns_server = local_ip;
|
||||
dns_server[3] = 1;
|
||||
begin(mac_address, local_ip, dns_server);
|
||||
}
|
||||
|
||||
void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server)
|
||||
{
|
||||
// Assume the gateway will be the machine on the same network as the local IP
|
||||
// but with last octet being '1'
|
||||
IPAddress gateway = local_ip;
|
||||
gateway[3] = 1;
|
||||
begin(mac_address, local_ip, dns_server, gateway);
|
||||
}
|
||||
|
||||
void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway)
|
||||
{
|
||||
IPAddress subnet(255, 255, 255, 0);
|
||||
begin(mac_address, local_ip, dns_server, gateway, subnet);
|
||||
}
|
||||
|
||||
void EthernetClass::begin(uint8_t *mac, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet)
|
||||
{
|
||||
W5100.init();
|
||||
W5100.setMACAddress(mac);
|
||||
W5100.setIPAddress(local_ip._address);
|
||||
W5100.setGatewayIp(gateway._address);
|
||||
W5100.setSubnetMask(subnet._address);
|
||||
_dnsServerAddress = dns_server;
|
||||
}
|
||||
|
||||
int EthernetClass::maintain(){
|
||||
int rc = DHCP_CHECK_NONE;
|
||||
if(_dhcp != NULL){
|
||||
//we have a pointer to dhcp, use it
|
||||
rc = _dhcp->checkLease();
|
||||
switch ( rc ){
|
||||
case DHCP_CHECK_NONE:
|
||||
//nothing done
|
||||
break;
|
||||
case DHCP_CHECK_RENEW_OK:
|
||||
case DHCP_CHECK_REBIND_OK:
|
||||
//we might have got a new IP.
|
||||
W5100.setIPAddress(_dhcp->getLocalIp().raw_address());
|
||||
W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address());
|
||||
W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address());
|
||||
_dnsServerAddress = _dhcp->getDnsServerIp();
|
||||
break;
|
||||
default:
|
||||
//this is actually a error, it will retry though
|
||||
break;
|
||||
}
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
IPAddress EthernetClass::localIP()
|
||||
{
|
||||
IPAddress ret;
|
||||
W5100.getIPAddress(ret.raw_address());
|
||||
return ret;
|
||||
}
|
||||
|
||||
IPAddress EthernetClass::subnetMask()
|
||||
{
|
||||
IPAddress ret;
|
||||
W5100.getSubnetMask(ret.raw_address());
|
||||
return ret;
|
||||
}
|
||||
|
||||
IPAddress EthernetClass::gatewayIP()
|
||||
{
|
||||
IPAddress ret;
|
||||
W5100.getGatewayIp(ret.raw_address());
|
||||
return ret;
|
||||
}
|
||||
|
||||
IPAddress EthernetClass::dnsServerIP()
|
||||
{
|
||||
return _dnsServerAddress;
|
||||
}
|
||||
|
||||
EthernetClass Ethernet;
|
@ -1,41 +0,0 @@
|
||||
#ifndef ethernet_h
|
||||
#define ethernet_h
|
||||
|
||||
#include <inttypes.h>
|
||||
//#include "w5100.h"
|
||||
#include "IPAddress.h"
|
||||
#include "EthernetClient.h"
|
||||
#include "EthernetServer.h"
|
||||
#include "Dhcp.h"
|
||||
|
||||
#define MAX_SOCK_NUM 4
|
||||
|
||||
class EthernetClass {
|
||||
private:
|
||||
IPAddress _dnsServerAddress;
|
||||
DhcpClass* _dhcp;
|
||||
public:
|
||||
static uint8_t _state[MAX_SOCK_NUM];
|
||||
static uint16_t _server_port[MAX_SOCK_NUM];
|
||||
// Initialise the Ethernet shield to use the provided MAC address and gain the rest of the
|
||||
// configuration through DHCP.
|
||||
// Returns 0 if the DHCP configuration failed, and 1 if it succeeded
|
||||
int begin(uint8_t *mac_address);
|
||||
void begin(uint8_t *mac_address, IPAddress local_ip);
|
||||
void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server);
|
||||
void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway);
|
||||
void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet);
|
||||
int maintain();
|
||||
|
||||
IPAddress localIP();
|
||||
IPAddress subnetMask();
|
||||
IPAddress gatewayIP();
|
||||
IPAddress dnsServerIP();
|
||||
|
||||
friend class EthernetClient;
|
||||
friend class EthernetServer;
|
||||
};
|
||||
|
||||
extern EthernetClass Ethernet;
|
||||
|
||||
#endif
|
@ -1,37 +0,0 @@
|
||||
#ifndef ethernetclient_h
|
||||
#define ethernetclient_h
|
||||
#include "Arduino.h"
|
||||
#include "Print.h"
|
||||
#include "Client.h"
|
||||
#include "IPAddress.h"
|
||||
|
||||
class EthernetClient : public Client {
|
||||
|
||||
public:
|
||||
EthernetClient();
|
||||
EthernetClient(uint8_t sock);
|
||||
|
||||
uint8_t status();
|
||||
virtual int connect(IPAddress ip, uint16_t port);
|
||||
virtual int connect(const char *host, uint16_t port);
|
||||
virtual size_t write(uint8_t);
|
||||
virtual size_t write(const uint8_t *buf, size_t size);
|
||||
virtual int available();
|
||||
virtual int read();
|
||||
virtual int read(uint8_t *buf, size_t size);
|
||||
virtual int peek();
|
||||
virtual void flush();
|
||||
virtual void stop();
|
||||
virtual uint8_t connected();
|
||||
virtual operator bool();
|
||||
|
||||
friend class EthernetServer;
|
||||
|
||||
using Print::write;
|
||||
|
||||
private:
|
||||
static uint16_t _srcport;
|
||||
uint8_t _sock;
|
||||
};
|
||||
|
||||
#endif
|
@ -1,91 +0,0 @@
|
||||
#include "w5100.h"
|
||||
#include "socket.h"
|
||||
extern "C" {
|
||||
#include "string.h"
|
||||
}
|
||||
|
||||
#include "Ethernet.h"
|
||||
#include "EthernetClient.h"
|
||||
#include "EthernetServer.h"
|
||||
|
||||
EthernetServer::EthernetServer(uint16_t port)
|
||||
{
|
||||
_port = port;
|
||||
}
|
||||
|
||||
void EthernetServer::begin()
|
||||
{
|
||||
for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
|
||||
EthernetClient client(sock);
|
||||
if (client.status() == SnSR::CLOSED) {
|
||||
socket(sock, SnMR::TCP, _port, 0);
|
||||
listen(sock);
|
||||
EthernetClass::_server_port[sock] = _port;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void EthernetServer::accept()
|
||||
{
|
||||
int listening = 0;
|
||||
|
||||
for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
|
||||
EthernetClient client(sock);
|
||||
|
||||
if (EthernetClass::_server_port[sock] == _port) {
|
||||
if (client.status() == SnSR::LISTEN) {
|
||||
listening = 1;
|
||||
}
|
||||
else if (client.status() == SnSR::CLOSE_WAIT && !client.available()) {
|
||||
client.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!listening) {
|
||||
begin();
|
||||
}
|
||||
}
|
||||
|
||||
EthernetClient EthernetServer::available()
|
||||
{
|
||||
accept();
|
||||
|
||||
for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
|
||||
EthernetClient client(sock);
|
||||
if (EthernetClass::_server_port[sock] == _port &&
|
||||
(client.status() == SnSR::ESTABLISHED ||
|
||||
client.status() == SnSR::CLOSE_WAIT)) {
|
||||
if (client.available()) {
|
||||
// XXX: don't always pick the lowest numbered socket.
|
||||
return client;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return EthernetClient(MAX_SOCK_NUM);
|
||||
}
|
||||
|
||||
size_t EthernetServer::write(uint8_t b)
|
||||
{
|
||||
return write(&b, 1);
|
||||
}
|
||||
|
||||
size_t EthernetServer::write(const uint8_t *buffer, size_t size)
|
||||
{
|
||||
size_t n = 0;
|
||||
|
||||
accept();
|
||||
|
||||
for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
|
||||
EthernetClient client(sock);
|
||||
|
||||
if (EthernetClass::_server_port[sock] == _port &&
|
||||
client.status() == SnSR::ESTABLISHED) {
|
||||
n += client.write(buffer, size);
|
||||
}
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
#ifndef ethernetserver_h
|
||||
#define ethernetserver_h
|
||||
|
||||
#include "Server.h"
|
||||
|
||||
class EthernetClient;
|
||||
|
||||
class EthernetServer :
|
||||
public Server {
|
||||
private:
|
||||
uint16_t _port;
|
||||
void accept();
|
||||
public:
|
||||
EthernetServer(uint16_t);
|
||||
EthernetClient available();
|
||||
virtual void begin();
|
||||
virtual size_t write(uint8_t);
|
||||
virtual size_t write(const uint8_t *buf, size_t size);
|
||||
using Print::write;
|
||||
};
|
||||
|
||||
#endif
|
@ -1,218 +0,0 @@
|
||||
/*
|
||||
* Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield.
|
||||
* This version only offers minimal wrapping of socket.c/socket.h
|
||||
* Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/
|
||||
*
|
||||
* MIT License:
|
||||
* Copyright (c) 2008 Bjoern Hartmann
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
* bjoern@cs.stanford.edu 12/30/2008
|
||||
*/
|
||||
|
||||
#include "w5100.h"
|
||||
#include "socket.h"
|
||||
#include "Ethernet.h"
|
||||
#include "Udp.h"
|
||||
#include "Dns.h"
|
||||
|
||||
/* Constructor */
|
||||
EthernetUDP::EthernetUDP() : _sock(MAX_SOCK_NUM) {}
|
||||
|
||||
/* Start EthernetUDP socket, listening at local port PORT */
|
||||
uint8_t EthernetUDP::begin(uint16_t port) {
|
||||
if (_sock != MAX_SOCK_NUM)
|
||||
return 0;
|
||||
|
||||
for (int i = 0; i < MAX_SOCK_NUM; i++) {
|
||||
uint8_t s = W5100.readSnSR(i);
|
||||
if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT) {
|
||||
_sock = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (_sock == MAX_SOCK_NUM)
|
||||
return 0;
|
||||
|
||||
_port = port;
|
||||
_remaining = 0;
|
||||
socket(_sock, SnMR::UDP, _port, 0);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* return number of bytes available in the current packet,
|
||||
will return zero if parsePacket hasn't been called yet */
|
||||
int EthernetUDP::available() {
|
||||
return _remaining;
|
||||
}
|
||||
|
||||
/* Release any resources being used by this EthernetUDP instance */
|
||||
void EthernetUDP::stop()
|
||||
{
|
||||
if (_sock == MAX_SOCK_NUM)
|
||||
return;
|
||||
|
||||
close(_sock);
|
||||
|
||||
EthernetClass::_server_port[_sock] = 0;
|
||||
_sock = MAX_SOCK_NUM;
|
||||
}
|
||||
|
||||
int EthernetUDP::beginPacket(const char *host, uint16_t port)
|
||||
{
|
||||
// Look up the host first
|
||||
int ret = 0;
|
||||
DNSClient dns;
|
||||
IPAddress remote_addr;
|
||||
|
||||
dns.begin(Ethernet.dnsServerIP());
|
||||
ret = dns.getHostByName(host, remote_addr);
|
||||
if (ret == 1) {
|
||||
return beginPacket(remote_addr, port);
|
||||
} else {
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
int EthernetUDP::beginPacket(IPAddress ip, uint16_t port)
|
||||
{
|
||||
_offset = 0;
|
||||
return startUDP(_sock, rawIPAddress(ip), port);
|
||||
}
|
||||
|
||||
int EthernetUDP::endPacket()
|
||||
{
|
||||
return sendUDP(_sock);
|
||||
}
|
||||
|
||||
size_t EthernetUDP::write(uint8_t byte)
|
||||
{
|
||||
return write(&byte, 1);
|
||||
}
|
||||
|
||||
size_t EthernetUDP::write(const uint8_t *buffer, size_t size)
|
||||
{
|
||||
uint16_t bytes_written = bufferData(_sock, _offset, buffer, size);
|
||||
_offset += bytes_written;
|
||||
return bytes_written;
|
||||
}
|
||||
|
||||
int EthernetUDP::parsePacket()
|
||||
{
|
||||
// discard any remaining bytes in the last packet
|
||||
flush();
|
||||
|
||||
if (W5100.getRXReceivedSize(_sock) > 0)
|
||||
{
|
||||
//HACK - hand-parse the UDP packet using TCP recv method
|
||||
uint8_t tmpBuf[8];
|
||||
int ret =0;
|
||||
//read 8 header bytes and get IP and port from it
|
||||
ret = recv(_sock,tmpBuf,8);
|
||||
if (ret > 0)
|
||||
{
|
||||
_remoteIP = tmpBuf;
|
||||
_remotePort = tmpBuf[4];
|
||||
_remotePort = (_remotePort << 8) + tmpBuf[5];
|
||||
_remaining = tmpBuf[6];
|
||||
_remaining = (_remaining << 8) + tmpBuf[7];
|
||||
|
||||
// When we get here, any remaining bytes are the data
|
||||
ret = _remaining;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
// There aren't any packets available
|
||||
return 0;
|
||||
}
|
||||
|
||||
int EthernetUDP::read()
|
||||
{
|
||||
uint8_t byte;
|
||||
|
||||
if ((_remaining > 0) && (recv(_sock, &byte, 1) > 0))
|
||||
{
|
||||
// We read things without any problems
|
||||
_remaining--;
|
||||
return byte;
|
||||
}
|
||||
|
||||
// If we get here, there's no data available
|
||||
return -1;
|
||||
}
|
||||
|
||||
int EthernetUDP::read(unsigned char* buffer, size_t len)
|
||||
{
|
||||
|
||||
if (_remaining > 0)
|
||||
{
|
||||
|
||||
int got;
|
||||
|
||||
if (_remaining <= len)
|
||||
{
|
||||
// data should fit in the buffer
|
||||
got = recv(_sock, buffer, _remaining);
|
||||
}
|
||||
else
|
||||
{
|
||||
// too much data for the buffer,
|
||||
// grab as much as will fit
|
||||
got = recv(_sock, buffer, len);
|
||||
}
|
||||
|
||||
if (got > 0)
|
||||
{
|
||||
_remaining -= got;
|
||||
return got;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// If we get here, there's no data available or recv failed
|
||||
return -1;
|
||||
|
||||
}
|
||||
|
||||
int EthernetUDP::peek()
|
||||
{
|
||||
uint8_t b;
|
||||
// Unlike recv, peek doesn't check to see if there's any data available, so we must.
|
||||
// If the user hasn't called parsePacket yet then return nothing otherwise they
|
||||
// may get the UDP header
|
||||
if (!_remaining)
|
||||
return -1;
|
||||
::peek(_sock, &b);
|
||||
return b;
|
||||
}
|
||||
|
||||
void EthernetUDP::flush()
|
||||
{
|
||||
// could this fail (loop endlessly) if _remaining > 0 and recv in read fails?
|
||||
// should only occur if recv fails after telling us the data is there, lets
|
||||
// hope the w5100 always behaves :)
|
||||
|
||||
while (_remaining)
|
||||
{
|
||||
read();
|
||||
}
|
||||
}
|
||||
|
@ -1,99 +0,0 @@
|
||||
/*
|
||||
* Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield.
|
||||
* This version only offers minimal wrapping of socket.c/socket.h
|
||||
* Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/
|
||||
*
|
||||
* NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these)
|
||||
* 1) UDP does not guarantee the order in which assembled UDP packets are received. This
|
||||
* might not happen often in practice, but in larger network topologies, a UDP
|
||||
* packet can be received out of sequence.
|
||||
* 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being
|
||||
* aware of it. Again, this may not be a concern in practice on small local networks.
|
||||
* For more information, see http://www.cafeaulait.org/course/week12/35.html
|
||||
*
|
||||
* MIT License:
|
||||
* Copyright (c) 2008 Bjoern Hartmann
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
* bjoern@cs.stanford.edu 12/30/2008
|
||||
*/
|
||||
|
||||
#ifndef ethernetudp_h
|
||||
#define ethernetudp_h
|
||||
|
||||
#include <Udp.h>
|
||||
|
||||
#define UDP_TX_PACKET_MAX_SIZE 24
|
||||
|
||||
class EthernetUDP : public UDP {
|
||||
private:
|
||||
uint8_t _sock; // socket ID for Wiz5100
|
||||
uint16_t _port; // local port to listen on
|
||||
IPAddress _remoteIP; // remote IP address for the incoming packet whilst it's being processed
|
||||
uint16_t _remotePort; // remote port for the incoming packet whilst it's being processed
|
||||
uint16_t _offset; // offset into the packet being sent
|
||||
uint16_t _remaining; // remaining bytes of incoming packet yet to be processed
|
||||
|
||||
public:
|
||||
EthernetUDP(); // Constructor
|
||||
virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use
|
||||
virtual void stop(); // Finish with the UDP socket
|
||||
|
||||
// Sending UDP packets
|
||||
|
||||
// Start building up a packet to send to the remote host specific in ip and port
|
||||
// Returns 1 if successful, 0 if there was a problem with the supplied IP address or port
|
||||
virtual int beginPacket(IPAddress ip, uint16_t port);
|
||||
// Start building up a packet to send to the remote host specific in host and port
|
||||
// Returns 1 if successful, 0 if there was a problem resolving the hostname or port
|
||||
virtual int beginPacket(const char *host, uint16_t port);
|
||||
// Finish off this packet and send it
|
||||
// Returns 1 if the packet was sent successfully, 0 if there was an error
|
||||
virtual int endPacket();
|
||||
// Write a single byte into the packet
|
||||
virtual size_t write(uint8_t);
|
||||
// Write size bytes from buffer into the packet
|
||||
virtual size_t write(const uint8_t *buffer, size_t size);
|
||||
|
||||
using Print::write;
|
||||
|
||||
// Start processing the next available incoming packet
|
||||
// Returns the size of the packet in bytes, or 0 if no packets are available
|
||||
virtual int parsePacket();
|
||||
// Number of bytes remaining in the current packet
|
||||
virtual int available();
|
||||
// Read a single byte from the current packet
|
||||
virtual int read();
|
||||
// Read up to len bytes from the current packet and place them into buffer
|
||||
// Returns the number of bytes read, or 0 if none are available
|
||||
virtual int read(unsigned char* buffer, size_t len);
|
||||
// Read up to len characters from the current packet and place them into buffer
|
||||
// Returns the number of characters read, or 0 if none are available
|
||||
virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); };
|
||||
// Return the next byte from the current packet without moving on to the next byte
|
||||
virtual int peek();
|
||||
virtual void flush(); // Finish reading the current packet
|
||||
|
||||
// Return the IP address of the host who sent the current incoming packet
|
||||
virtual IPAddress remoteIP() { return _remoteIP; };
|
||||
// Return the port of the host who sent the current incoming packet
|
||||
virtual uint16_t remotePort() { return _remotePort; };
|
||||
};
|
||||
|
||||
#endif
|
@ -1,222 +0,0 @@
|
||||
/*
|
||||
SCP1000 Barometric Pressure Sensor Display
|
||||
|
||||
Serves the output of a Barometric Pressure Sensor as a web page.
|
||||
Uses the SPI library. For details on the sensor, see:
|
||||
http://www.sparkfun.com/commerce/product_info.php?products_id=8161
|
||||
http://www.vti.fi/en/support/obsolete_products/pressure_sensors/
|
||||
|
||||
This sketch adapted from Nathan Seidle's SCP1000 example for PIC:
|
||||
http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip
|
||||
|
||||
Circuit:
|
||||
SCP1000 sensor attached to pins 6,7, and 11 - 13:
|
||||
DRDY: pin 6
|
||||
CSB: pin 7
|
||||
MOSI: pin 11
|
||||
MISO: pin 12
|
||||
SCK: pin 13
|
||||
|
||||
created 31 July 2010
|
||||
by Tom Igoe
|
||||
*/
|
||||
|
||||
#include <Ethernet.h>
|
||||
// the sensor communicates using SPI, so include the library:
|
||||
#include <SPI.h>
|
||||
|
||||
|
||||
// assign a MAC address for the ethernet controller.
|
||||
// fill in your address here:
|
||||
byte mac[] = {
|
||||
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
|
||||
// assign an IP address for the controller:
|
||||
IPAddress ip(192,168,1,20);
|
||||
IPAddress gateway(192,168,1,1);
|
||||
IPAddress subnet(255, 255, 255, 0);
|
||||
|
||||
|
||||
// Initialize the Ethernet server library
|
||||
// with the IP address and port you want to use
|
||||
// (port 80 is default for HTTP):
|
||||
EthernetServer server(80);
|
||||
|
||||
|
||||
//Sensor's memory register addresses:
|
||||
const int PRESSURE = 0x1F; //3 most significant bits of pressure
|
||||
const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure
|
||||
const int TEMPERATURE = 0x21; //16 bit temperature reading
|
||||
|
||||
// pins used for the connection with the sensor
|
||||
// the others you need are controlled by the SPI library):
|
||||
const int dataReadyPin = 6;
|
||||
const int chipSelectPin = 7;
|
||||
|
||||
float temperature = 0.0;
|
||||
long pressure = 0;
|
||||
long lastReadingTime = 0;
|
||||
|
||||
void setup() {
|
||||
// start the SPI library:
|
||||
SPI.begin();
|
||||
|
||||
// start the Ethernet connection and the server:
|
||||
Ethernet.begin(mac, ip);
|
||||
server.begin();
|
||||
|
||||
// initalize the data ready and chip select pins:
|
||||
pinMode(dataReadyPin, INPUT);
|
||||
pinMode(chipSelectPin, OUTPUT);
|
||||
|
||||
Serial.begin(9600);
|
||||
|
||||
//Configure SCP1000 for low noise configuration:
|
||||
writeRegister(0x02, 0x2D);
|
||||
writeRegister(0x01, 0x03);
|
||||
writeRegister(0x03, 0x02);
|
||||
|
||||
// give the sensor and Ethernet shield time to set up:
|
||||
delay(1000);
|
||||
|
||||
//Set the sensor to high resolution mode tp start readings:
|
||||
writeRegister(0x03, 0x0A);
|
||||
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// check for a reading no more than once a second.
|
||||
if (millis() - lastReadingTime > 1000){
|
||||
// if there's a reading ready, read it:
|
||||
// don't do anything until the data ready pin is high:
|
||||
if (digitalRead(dataReadyPin) == HIGH) {
|
||||
getData();
|
||||
// timestamp the last time you got a reading:
|
||||
lastReadingTime = millis();
|
||||
}
|
||||
}
|
||||
|
||||
// listen for incoming Ethernet connections:
|
||||
listenForEthernetClients();
|
||||
}
|
||||
|
||||
|
||||
void getData() {
|
||||
Serial.println("Getting reading");
|
||||
//Read the temperature data
|
||||
int tempData = readRegister(0x21, 2);
|
||||
|
||||
// convert the temperature to celsius and display it:
|
||||
temperature = (float)tempData / 20.0;
|
||||
|
||||
//Read the pressure data highest 3 bits:
|
||||
byte pressureDataHigh = readRegister(0x1F, 1);
|
||||
pressureDataHigh &= 0b00000111; //you only needs bits 2 to 0
|
||||
|
||||
//Read the pressure data lower 16 bits:
|
||||
unsigned int pressureDataLow = readRegister(0x20, 2);
|
||||
//combine the two parts into one 19-bit number:
|
||||
pressure = ((pressureDataHigh << 16) | pressureDataLow)/4;
|
||||
|
||||
Serial.print("Temperature: ");
|
||||
Serial.print(temperature);
|
||||
Serial.println(" degrees C");
|
||||
Serial.print("Pressure: " + String(pressure));
|
||||
Serial.println(" Pa");
|
||||
}
|
||||
|
||||
void listenForEthernetClients() {
|
||||
// listen for incoming clients
|
||||
EthernetClient client = server.available();
|
||||
if (client) {
|
||||
Serial.println("Got a client");
|
||||
// an http request ends with a blank line
|
||||
boolean currentLineIsBlank = true;
|
||||
while (client.connected()) {
|
||||
if (client.available()) {
|
||||
char c = client.read();
|
||||
// if you've gotten to the end of the line (received a newline
|
||||
// character) and the line is blank, the http request has ended,
|
||||
// so you can send a reply
|
||||
if (c == '\n' && currentLineIsBlank) {
|
||||
// send a standard http response header
|
||||
client.println("HTTP/1.1 200 OK");
|
||||
client.println("Content-Type: text/html");
|
||||
client.println();
|
||||
// print the current readings, in HTML format:
|
||||
client.print("Temperature: ");
|
||||
client.print(temperature);
|
||||
client.print(" degrees C");
|
||||
client.println("<br />");
|
||||
client.print("Pressure: " + String(pressure));
|
||||
client.print(" Pa");
|
||||
client.println("<br />");
|
||||
break;
|
||||
}
|
||||
if (c == '\n') {
|
||||
// you're starting a new line
|
||||
currentLineIsBlank = true;
|
||||
}
|
||||
else if (c != '\r') {
|
||||
// you've gotten a character on the current line
|
||||
currentLineIsBlank = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
// give the web browser time to receive the data
|
||||
delay(1);
|
||||
// close the connection:
|
||||
client.stop();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//Send a write command to SCP1000
|
||||
void writeRegister(byte registerName, byte registerValue) {
|
||||
// SCP1000 expects the register name in the upper 6 bits
|
||||
// of the byte:
|
||||
registerName <<= 2;
|
||||
// command (read or write) goes in the lower two bits:
|
||||
registerName |= 0b00000010; //Write command
|
||||
|
||||
// take the chip select low to select the device:
|
||||
digitalWrite(chipSelectPin, LOW);
|
||||
|
||||
SPI.transfer(registerName); //Send register location
|
||||
SPI.transfer(registerValue); //Send value to record into register
|
||||
|
||||
// take the chip select high to de-select:
|
||||
digitalWrite(chipSelectPin, HIGH);
|
||||
}
|
||||
|
||||
|
||||
//Read register from the SCP1000:
|
||||
unsigned int readRegister(byte registerName, int numBytes) {
|
||||
byte inByte = 0; // incoming from the SPI read
|
||||
unsigned int result = 0; // result to return
|
||||
|
||||
// SCP1000 expects the register name in the upper 6 bits
|
||||
// of the byte:
|
||||
registerName <<= 2;
|
||||
// command (read or write) goes in the lower two bits:
|
||||
registerName &= 0b11111100; //Read command
|
||||
|
||||
// take the chip select low to select the device:
|
||||
digitalWrite(chipSelectPin, LOW);
|
||||
// send the device the register you want to read:
|
||||
int command = SPI.transfer(registerName);
|
||||
// send a value of 0 to read the first byte returned:
|
||||
inByte = SPI.transfer(0x00);
|
||||
|
||||
result = inByte;
|
||||
// if there's more than one byte returned,
|
||||
// shift the first byte then get the second byte:
|
||||
if (numBytes > 1){
|
||||
result = inByte << 8;
|
||||
inByte = SPI.transfer(0x00);
|
||||
result = result |inByte;
|
||||
}
|
||||
// take the chip select high to de-select:
|
||||
digitalWrite(chipSelectPin, HIGH);
|
||||
// return the result:
|
||||
return(result);
|
||||
}
|
@ -1,79 +0,0 @@
|
||||
/*
|
||||
Chat Server
|
||||
|
||||
A simple server that distributes any incoming messages to all
|
||||
connected clients. To use telnet to your device's IP address and type.
|
||||
You can see the client's input in the serial monitor as well.
|
||||
Using an Arduino Wiznet Ethernet shield.
|
||||
|
||||
Circuit:
|
||||
* Ethernet shield attached to pins 10, 11, 12, 13
|
||||
* Analog inputs attached to pins A0 through A5 (optional)
|
||||
|
||||
created 18 Dec 2009
|
||||
by David A. Mellis
|
||||
modified 9 Apr 2012
|
||||
by Tom Igoe
|
||||
|
||||
*/
|
||||
|
||||
#include <SPI.h>
|
||||
#include <Ethernet.h>
|
||||
|
||||
// Enter a MAC address and IP address for your controller below.
|
||||
// The IP address will be dependent on your local network.
|
||||
// gateway and subnet are optional:
|
||||
byte mac[] = {
|
||||
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
|
||||
IPAddress ip(192,168,1, 177);
|
||||
IPAddress gateway(192,168,1, 1);
|
||||
IPAddress subnet(255, 255, 0, 0);
|
||||
|
||||
|
||||
// telnet defaults to port 23
|
||||
EthernetServer server(23);
|
||||
boolean alreadyConnected = false; // whether or not the client was connected previously
|
||||
|
||||
void setup() {
|
||||
// initialize the ethernet device
|
||||
Ethernet.begin(mac, ip, gateway, subnet);
|
||||
// start listening for clients
|
||||
server.begin();
|
||||
// Open serial communications and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for Leonardo only
|
||||
}
|
||||
|
||||
|
||||
Serial.print("Chat server address:");
|
||||
Serial.println(Ethernet.localIP());
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// wait for a new client:
|
||||
EthernetClient client = server.available();
|
||||
|
||||
// when the client sends the first byte, say hello:
|
||||
if (client) {
|
||||
if (!alreadyConnected) {
|
||||
// clead out the input buffer:
|
||||
client.flush();
|
||||
Serial.println("We have a new client");
|
||||
client.println("Hello, client!");
|
||||
alreadyConnected = true;
|
||||
}
|
||||
|
||||
if (client.available() > 0) {
|
||||
// read the bytes incoming from the client:
|
||||
char thisChar = client.read();
|
||||
// echo the bytes back to the client:
|
||||
server.write(thisChar);
|
||||
// echo the bytes to the server as well:
|
||||
Serial.write(thisChar);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,160 +0,0 @@
|
||||
/*
|
||||
Cosm sensor client
|
||||
|
||||
This sketch connects an analog sensor to Cosm (http://www.cosm.com)
|
||||
using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or
|
||||
the Adafruit Ethernet shield, either one will work, as long as it's got
|
||||
a Wiznet Ethernet module on board.
|
||||
|
||||
This example has been updated to use version 2.0 of the cosm.com API.
|
||||
To make it work, create a feed with a datastream, and give it the ID
|
||||
sensor1. Or change the code below to match your feed.
|
||||
|
||||
|
||||
Circuit:
|
||||
* Analog sensor attached to analog in 0
|
||||
* Ethernet shield attached to pins 10, 11, 12, 13
|
||||
|
||||
created 15 March 2010
|
||||
updated 14 May 2012
|
||||
by Tom Igoe with input from Usman Haque and Joe Saavedra
|
||||
|
||||
http://arduino.cc/en/Tutorial/CosmClient
|
||||
This code is in the public domain.
|
||||
|
||||
*/
|
||||
|
||||
#include <SPI.h>
|
||||
#include <Ethernet.h>
|
||||
|
||||
#define APIKEY "YOUR API KEY GOES HERE" // replace your Cosm api key here
|
||||
#define FEEDID 00000 // replace your feed ID
|
||||
#define USERAGENT "My Project" // user agent is the project name
|
||||
|
||||
// assign a MAC address for the ethernet controller.
|
||||
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
|
||||
// fill in your address here:
|
||||
byte mac[] = {
|
||||
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
|
||||
|
||||
// fill in an available IP address on your network here,
|
||||
// for manual configuration:
|
||||
IPAddress ip(10,0,1,20);
|
||||
|
||||
// initialize the library instance:
|
||||
EthernetClient client;
|
||||
|
||||
// if you don't want to use DNS (and reduce your sketch size)
|
||||
// use the numeric IP instead of the name for the server:
|
||||
// IPAddress server(216,52,233,121); // numeric IP for api.cosm.com
|
||||
char server[] = "api.cosm.com"; // name address for cosm API
|
||||
|
||||
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
|
||||
boolean lastConnected = false; // state of the connection last time through the main loop
|
||||
const unsigned long postingInterval = 10L*1000L; // delay between updates to cosm.com
|
||||
// the "L" is needed to use long type numbers
|
||||
|
||||
void setup() {
|
||||
// start serial port:
|
||||
Serial.begin(9600);
|
||||
// start the Ethernet connection:
|
||||
if (Ethernet.begin(mac) == 0) {
|
||||
Serial.println("Failed to configure Ethernet using DHCP");
|
||||
// DHCP failed, so use a fixed IP address:
|
||||
Ethernet.begin(mac, ip);
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// read the analog sensor:
|
||||
int sensorReading = analogRead(A0);
|
||||
|
||||
// if there's incoming data from the net connection.
|
||||
// send it out the serial port. This is for debugging
|
||||
// purposes only:
|
||||
if (client.available()) {
|
||||
char c = client.read();
|
||||
Serial.print(c);
|
||||
}
|
||||
|
||||
// if there's no net connection, but there was one last time
|
||||
// through the loop, then stop the client:
|
||||
if (!client.connected() && lastConnected) {
|
||||
Serial.println();
|
||||
Serial.println("disconnecting.");
|
||||
client.stop();
|
||||
}
|
||||
|
||||
// if you're not connected, and ten seconds have passed since
|
||||
// your last connection, then connect again and send data:
|
||||
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
|
||||
sendData(sensorReading);
|
||||
}
|
||||
// store the state of the connection for next time through
|
||||
// the loop:
|
||||
lastConnected = client.connected();
|
||||
}
|
||||
|
||||
// this method makes a HTTP connection to the server:
|
||||
void sendData(int thisData) {
|
||||
// if there's a successful connection:
|
||||
if (client.connect(server, 80)) {
|
||||
Serial.println("connecting...");
|
||||
// send the HTTP PUT request:
|
||||
client.print("PUT /v2/feeds/");
|
||||
client.print(FEEDID);
|
||||
client.println(".csv HTTP/1.1");
|
||||
client.println("Host: api.cosm.com");
|
||||
client.print("X-ApiKey: ");
|
||||
client.println(APIKEY);
|
||||
client.print("User-Agent: ");
|
||||
client.println(USERAGENT);
|
||||
client.print("Content-Length: ");
|
||||
|
||||
// calculate the length of the sensor reading in bytes:
|
||||
// 8 bytes for "sensor1," + number of digits of the data:
|
||||
int thisLength = 8 + getLength(thisData);
|
||||
client.println(thisLength);
|
||||
|
||||
// last pieces of the HTTP PUT request:
|
||||
client.println("Content-Type: text/csv");
|
||||
client.println("Connection: close");
|
||||
client.println();
|
||||
|
||||
// here's the actual content of the PUT request:
|
||||
client.print("sensor1,");
|
||||
client.println(thisData);
|
||||
|
||||
}
|
||||
else {
|
||||
// if you couldn't make a connection:
|
||||
Serial.println("connection failed");
|
||||
Serial.println();
|
||||
Serial.println("disconnecting.");
|
||||
client.stop();
|
||||
}
|
||||
// note the time that the connection was made or attempted:
|
||||
lastConnectionTime = millis();
|
||||
}
|
||||
|
||||
|
||||
// This method calculates the number of digits in the
|
||||
// sensor reading. Since each digit of the ASCII decimal
|
||||
// representation is a byte, the number of digits equals
|
||||
// the number of bytes:
|
||||
|
||||
int getLength(int someValue) {
|
||||
// there's at least one byte:
|
||||
int digits = 1;
|
||||
// continually divide the value by ten,
|
||||
// adding one to the digit count for each
|
||||
// time you divide, until you're at 0:
|
||||
int dividend = someValue /10;
|
||||
while (dividend > 0) {
|
||||
dividend = dividend /10;
|
||||
digits++;
|
||||
}
|
||||
// return the number of digits:
|
||||
return digits;
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user