Quantcast
Channel: 未分类 –懒得折腾
Viewing all 759 articles
Browse latest View live

使用 JS 构建跨平台的原生应用 React Native for Android

$
0
0

使用 JS 构建跨平台的原生应用(一):React Native for Android 初探

2015-12-02 08:03 编辑: cocopeng 分类:Android相关 来源:淘宝FED
0 432

Facebook 于 2015 年 9 月 15 日推出 React Native for Android 版本。相比起 for iOS,for Android 跑 “Hello, World!” 折腾了不少。在这些复杂的环境、工具依赖里,我们可以看出 React Native for Android 的一些端倪。

本系列文章就以开发一个 “Hello, World!” 的 App 为线索,跟大家一起来了解 React Native for Andorid 的技术背景。

  • 本文以在 OS X 开发为例
  • React Native 的更新非常活跃,本文以 0.14.0 版本为例
  • 下文简称 React Native 为 RN
  • 下文部分链接访问需要翻墙

基础环境

  • 在开始 RN 开发之前,我们需要在自己的机器上准备基础的开发环境:Homebrew
  • OS X 不可或缺的套件管理器,待会我们会用到它来安装nvm。

nvm:$ brew install nvm

  • nvm 是 Node.js 的版本管理器,可以轻松安装各个版本的 Node.js

Node.js:$ nvm install node && nvm alias default node

需要 4.0 或以上。RN CLI 使用到了 ES6 的语法特性

TB1FBm9KpXXXXXCXVXXXXXXXXXX-1224-668.jpg

RN 官方还推荐我们安装 2 个工具包,这是可选的,它们分别是:

Facebook 出品的文件监控工具,如果你安装了它,RN 会用它来检测文件变化,以便重新编译。如果你没有安装,会默认使用 walker

TB1Qr5jKpXXXXbXXpXXXXXXXXXX-1574-963.jpg

flow:$ brew install flow

Facebook 出品的 JS 静态类型的检查器

如果你安装了 watchman 又版本太低,那么编译项目的时候可以能会报错 Cannot read property ‘root’ of null ,所以如果安装了 watchman 请运行 $ brew update && brew upgrade 确保使用最新版本。

Android 开发环境

Android 应用程序开发中,通过在 Android SDK(Android 软件开发包)中使用 Java 作为编程语言来开发应用程序(开发者亦可以通过在 Android NDK(Android Native 开发包)中使用 C 语言或者 C++ 语言来作为编程语言开发应用程序)。

此外,Google 还推出了 Android Studio ,是一个为 Android 平台开发程序的集成开发环境(对比 iOS 的 Xcode)。

现在就来开始准备 Android 的开发环境:

SDK 指 Software Development Kit,软件开发工具包

这里安装的是Stand-alone Android SDK Tools,基础的 SDK 工具。默认情况下,这个 SDK 并不包括着手开发所需的一切内容。Android SDK 将工具、平台和其他组件分成若干个软件包,可以通过 Android SDK 管理器根据需要下载这些软件包。因此需要先为 Android SDK 添加几个软件包,然后才能着手开发。

选择以下包进行添加安装:命令行下运行 $ android 来打开 SDK Manager

Android SDK Tools

  • Android SDK 扩展工具包,它与具体 Android 平台无关,包括一套完整的开发和调试工具。
  • 包位置:$ANDROID_HOME/tools
  • 主要工具:ant scripts (to build your APKs) and ddms (for debugging)
  • 更新历史:http://developer.android.com/tools/sdk/tools-notes.html

Android SDK Platform-tools

  • 平台相关性工具,支持最新 Android 版本功能的同时向下兼容。
  • 包位置:$ANDROID_HOME/platform-tools
  • 主要工具:adb (to manage the state of an emulator or an Android device)

Android SDK Build-tools

Android 6.0(API 23) – SDK Platform

Android Suppor Repository

安装包图示:

QQ截图20151201182310.jpg

  • 设置环境变量 ANDROID_HOME

RN 内使用该变量进行 Android SDK 查找,代码如下:

TB1pGG6KpXXXXayXVXXXXXXXXXX-1170-721.jpg

因此你需要设置此环境变量:

1. 打开一个 Terminal 窗口,运行 `export ANDROID_HOME=/usr/local/opt/android-sdk`

2. 把上面的命令粘贴到`~/.bashrc`,`~/.bash_profile` 这样每次 Terminal 启动都会自动赋值 ANDROID_HOME 了

运行环境

完成了开发环境的准备,接下来我们需要准备应用的运行环境(类似于我们进行前端开发时需要在本机安装一个浏览器来运行我们的代码),这里有 2 种方式:

模拟器

第一种方式是在本机安装 Android 模拟器,模拟一个 Android 系统。

这里推荐使用 Genymotion,个人用户免费的模拟器。

  • 下载 VirtualBox
  • 下载 Genymotion
  • 打开 Genymotion,点击 “Add” 创建一个模拟设备
  • 刚才我们安装了 Android 6.0(API 23) – SDK Platform ,所以请确保你创建的虚拟设备 Android 版本不会大于这个
  • 选择模拟设备,点击 “Start” 启动一个模拟设备

真机

除了模拟器,我们还可以在手机上使用 USB 调试模式把自己的应用运行在这个真机环境里。

  • 设置你的手机允许USB 调试
  • 使用 USB 连接你的手机和电脑
  • 运行命令 $ adb devices 查看当前可用设备,确认调试连接是否成功。如果成功在列表下将会出现你的设备

开始你的第一个 RN for Android 应用

万事具备,开始用 RN 新建一个 Android 应用并且让它在你准备的运行环境里跑起来吧。

安装 RN 脚手架

1
$ npm install -g react-native-cli

react-native-cli(0.1.7) 只是一个外壳,实际执行的代码是在:react-native/local-cli/cli.js

TB1BQnpKpXXXXbRXXXXXXXXXXXX-810-698.jpg

初始化一个 RN 项目

1
$ react-native init AwesomeProject
  • 打开 AwesomeProject/index.android.js ,修改 Text 标签内的文案为 Hello, World!

TB154ThKpXXXXXHXFXXXXXXXXXX-983-609.jpg

启动调试

在 AwesomeProject 项目目录运行 $ react-native run-android,如果你使用的运行环境是模拟器,如无意外,你将会在你的模拟器上看到这个画面:

QQ截图20151201182814.jpg

本篇文章跟大家一起“浅出”了 RN for Android ,下一篇将与大家一起“深入”:

react-native run-android 的背后到底发生了什么?

将涉及到 RN 的 JS 打包构建流程和 Android SDK 的 workflow。

使用 JS 构建跨平台的原生应用(二):React Native for Android 调试技术剖析

2015-12-03 09:39 编辑: cocopeng 分类:Android相关 来源:淘宝FED
0 204

react-native run-android 这个调试命令的背后涉及到 RN 的整个执行流程,值得进行剖析。

  • React Native 的更新非常活跃,本文以 0.14.0 版本为例
  • 下文简称 React Native 为 RN
  • 下文部分链接访问可能需要翻墙

run-android

react-native run-android 命令启动后你能看到:

  • 当前窗口编译打包了一个 Android apk 并且把它安装、运行在了虚拟机环境里
  • 新开一个命令行窗口起了一个 HTTP 服务在监听 8081 端口

前者好理解,后者是为什么呢?

还记得我们上文修改的 index.android.js 文件吗?它是应用的 JS 入口文件。为方便调试,RN 将编译打包一个 debug 版本的 APK 把它安装到虚拟机环境,App 内是靠发送 HTTP 请求到开发机上获取这个 JS

文件来进行 UI 渲染的:

TB1Lp3NKpXXXXXbXFXXXXXXXXXX-844-559.jpg

那么这两步在 RN 内是如何实现的呢?

react-native 命令执行的是上文安装的 react-native-cli,但这个包没有做实际的事情,真正执行的代码是在 react-native 这个库的 local-cli 文件夹里。

就拿 react-native run-android 来说,它实际执行的代码是react-native/private-cli/src/runAndroid/runAndroid.js

执行后,命令行窗口的输出如下:

QQ截图20151201183644.jpg

这两个输出寓意着 RN 要执行的两个函数:

  • startServerInNewWindow
  • buildAndRun

TB1L0ZkKpXXXXbOXXXXXXXXXXXX-1009-206.jpg

启动 HTTP 服务在新窗口

startServerInNewWindow 的执行效果跟在项目根目录下运行 node start 是一样的,都会去调用 react-native/private-cli/src/server/server.js,其调用过程如下:

TB19rglKpXXXXbyXXXXXXXXXXXX-1019-450.jpg

我们真正需要关心的是 react-native/private-clil/src/server/runServer.js 这个文件里的内容:它将创建一个 HTTP 服务并默认监听 8081 端口:

1
2
3
4
5
6
7
8
9
//react-native/private-cli/src/server/runServer.js
const connect = require('connect');
const http = require('http');
function runServer(args, config, readyCallback) {
    const app = connect()
        //code...
      return http.createServer(app).listen(args.port, '::', readyCallback);
}
module.exports = runServer;

接下来,我们以 startServerInNewWindow 唤起的命令行窗口内的输出为线索,了解启动这个 HTTP 服务背后做了些什么:

TB11MfxKpXXXXbRXFXXXXXXXXXX-1000-890.jpg

窗口内有8个输出,它们分别是(见括号数字):

createServer

  • Building Dependency Graph(1)
  • Crawling File System(2)
  • Building in-memory fs for JavaScript(4)
  • Building Haste Map(5)
  • Loading bundles layout(3)

processRequest

request:/index.android.bundle?platform=android&dev=true(6)

  • find dependencies(7)
  • transform(8)

(1)-(5)是服务启动阶段中主动的 console ,(6)-(8)是 App 访问服务时触发的 console 。

创建一个响应对象

TB1IA3eKpXXXXXDXFXXXXXXXXXX-1007-239.jpg

(提示:通过上图我们可以得知,程序执行流程掉入了 /packager 这个文件夹里。这是一个重要的文件夹,它的职责是打包 JS 。它是独立于平台的,无论是 Android 还是 iOS ,都会调用它去进行打包 JS 的工作)

HTTP 服务启动过程中,将会创建多个响应中间件,其中有一个最重要的中间件就是 ReactPackagerMiddleware。这个中间件就是响应后面我们 buildAndRun 流程里创建并运行在虚拟环境内的 App 发送的 request:/index.android.bundle 请求的。

ReactPackagerMiddleware 将创建一个 Server 对象,Server 则会创建 Bundler 对象,它的作用如名字一样,负责具体的 JS 打包工作。

但在启动服务的这一步,Bundler 主要做的是准备工作:它会在内存建立 DependencyResolver,方便将来打包时可以快速地操作文件。

构建依赖树

DependencyResolver 的调用栈如下:

递归项目目录找出所有文件

在内存内文件系统,将项目目录下的 .js .json 文件以依赖树状结构存储到上面

快速索引文件系统,里面会排除掉 node_modules/

挂载响应

Server 对象创建完毕,程序将 Server 的 processRequest 方法作为一个响应中间件挂载到刚启动的 HTTP 服务上用于响应请求:

1
2
3
4
exports.middleware = function(options) {
  var server = createServer(options);
  return server.processRequest.bind(server);
};

自此,前期工作已经准备完毕。后面(6)-(8)输出,则是来自于 App 请求 /index.android.bundle?platform=android&dev=true 的响应。

响应请求

安装和运行到虚拟机环境里的 App 在启动完成后会发送一个 HTTP 请求到 http://yourDevIP:port/index.android.bundle?platform=android&dev=true 以获取 bundle 资源。

Server.processRequest 捕获到这个请求,并且响应一个打包好的 JS 文件:

TB1ydg1KpXXXXXQXXXXXXXXXXXX-678-822.gif

前面介绍过,Server 在初始化时会创建一个 Bundler 对象,而在收到请求后 Server 就是用这个 Bundler 进行打包 JS 文件的。

最后的控制台输出告诉了我们 Bundler 的打包过程:

  • find dependencies(7):在 Bundler 创建时生成的 DependencyResolver 查找依赖关系树
  • transform(8):将查找到的 JS 模块进行编译

有关于 build 的全过程,我将在未来的文章中更深入地进行讲解,现在你只需要知道:

TB1jpcVKpXXXXXXXpXXXXXXXXXX-1018-609.gif

热部署技术

Reload JS

TB1dAb1KpXXXXbGXXXXXXXXXXXX-550-743.gif

在虚拟机环境内,打开 App 的菜单,点击 Reload JS ,如果开发机脚本有被修改,则 App 内 UI 会重新渲染。这是怎么做到的呢?

原来,点击 Reload JS 后,App 会重新发送 HTTP 请求到开发机,开发机上的服务器收到请求后根据参数决定是否重新 build 返回 bundle 文件。

Auto reload on JS change

TB1ElvuKpXXXXXaapXXXXXXXXXX-550-743.gif

Reload JS 通过重新发送请求就能做到了,那在 Dev Settings 中设置 Auto reload on JS change 选项后,每次开发机 JS 代码有改动,App 内 UI 就会重新渲染,这又是怎么做到的呢?

Dev Settings 更新后将会触发 App 内的 reload 方法,reload 时将会去检查当前的 mDevSettings 内有无开启 Auto reload on JS change ,如果有,则开启轮询 startPollingOnChangeEndpoint:

TB1OXoGKpXXXXboXFXXXXXXXXXX-932-688.gif

startPollingOnChangeEndpoint 将启动一个 HTTP 客户端然后发送请求到http://yourDevIP:port/onchange

TB1iN7qKpXXXXaQaXXXXXXXXXXX-946-801.gif

无论请求成功还是失败,App 都会继续通过这个 HTTP 客户端发送同样的请求(轮询):

TB1QpwTKpXXXXcAXXXXXXXXXXXX-946-819.gif

而如果请求返回的状态码是 205,则调用 mOnServerContentChangeListener.onServerContentChanged 做出响应,onServerContentChanged 会做的动作则是 handleReloadJS, handleReloadJS 这一步则会如 App

初始化时的一样,发送一个 HTTP 请求到 http://yourDevIP:port/index.android .bundle?platform=android&dev=true 获取最新的 bundle 并且进行编译渲染。

TB1xx.gif

接下来看看开发机上的 HTTP 服务接收到 /onchange 请求将会做出怎样的响应:

  • 服务器接受到 /onchange 的请求后没有做成任何响应,而是默默地把请求通过 _processOnChangeRequest 方法存储在了 Server._changeWatchers 中。当请求太久没有响应而超时关闭时,就把 Server._changeWatchers 清空:

TB1V6QGKpXXXXcXXFXXXXXXXXXX-671-487.gif

TB1bi.gif

  • 在服务器收到 /onchange 请求时,直到关闭这个请求的过程前,如果服务器内的 JS 文件发生任何变更,服务器将会重新 build 并且响应这个 /onchange 。这里就涉及到 FileWatcher 模块的引入:在 Server 初始化时,引入了 FileWatcher 模块并把它传递给了 Bundler 。还记得上一节中我们讲过的吗?Bundler 会初始化 DependencyResolver ,在这一步里,Bundler 会使用 FileWatcher 监听依赖树里的每一个文件,当它们发生变化时,FileWatcher 会抛出相应的事件。

TB10fILKpXXXXcGXpXXXXXXXXXX-666-417.gif

  • Server 内,监听了 FileWatcher 的事件,接受到事件后,进行 rebuild ,响应 /onchange 请求:

TB1SGEsKpXXXXXYaXXXXXXXXXXX-747-832.gif

至此,用一张图来总结 startServerInNewWindow 的执行流程:

TB1nNQTKpXXXXXNXpXXXXXXXXXX-1018-596.gif

编译和运行应用

另外一边,RN CLI 编译打包了一个 APK 并且把它安装运行在了虚拟机内。观察 Shell 的输出:

QQ截图20151202113227.gif

定位到 buildAndRun 的源码:

TB1Gh.gif

由此可得知,编译打包安装、运行 App 是分 2 步来执行的,最终执行的命令是:

QQ截图20151202113341.gif

Gradle:编译、打包、安装

cd android && ./gradlew installDebug

最终执行的命令是:

1
2
3
java -Xdock:name=Gradle -Xdock:icon=
/android/media/gradle.icns -Dorg.gradle.appname=gradlew -classpath
/android/gradle/wrapper/gradle-wrapper.jar org.gradle.wrapper.GradleWrapperMain installDebug

原来,RN 中打包编译是由 Gradle Wrapper 来实现的。Gradle Wrapper 是一种方便的使用 Gradle 的方法,他包括了为支持 Windows 的批处理脚本和支持类 Unix 的 shell 脚本。这些脚本在不安装 Gradle 时候,也可以用 Gradle。

通过 /android/gradle/wrapper/gradle-wrapper.properties 我们还可以知道 RN 使用的是 2.4 版本的 Gradle 。

接下来针对 Gradle 做一个简单的介绍。

Gradle 是什么?

参考它官网的介绍:

Gradle is a build tool with a focus on build automation and support for multi-language development.

Gradle 遵循约定优于配置的原则,它的主要配置文件是 build.gradle 。打开/android/ 文件夹,就可以看到这个配置文件:

├── app

├── build

├── build.gradle

├── gradle

├── gradle.properties

├── gradlew

├── gradlew.bat

└── settings.gradle

Projects 和 tasks

Gradle 里的任何东西都是基于这两个基础概念:

  • projects(项目)
  • tasks(任务)

每一个构建都是由一个或多个 projects 构成的。一个 project 到底代表什么依赖于你想用 Gradle 做什么。举个例子,一个 project 可以代表一个 JAR 或者一个网页应用。它也可能代表一个发布的 ZIP 压缩包, 这个 ZIP 可能是由许多其他项目的 JARs 构成的。但是一个 project 不一定非要代表被构建的某个东西。它可以代表一件要做的事,比如部署你的应用。

每一个 project 是由一个或多个 tasks 构成的。一个 task 代表一些更加细化的构建。可能是编译一些 classes,创建一个 JAR, 生成 javadoc,或者生成某个目录的压缩文件。

我们来看一下 RN Andorid 下有多少个 project,运行 gralde projects (使用 brew install gralde 安装 gralde CLI)

TB1DQ3JKpXXXXX8XFXXXXXXXXXX-651-295.jpg

可见我们有 2 个 project ,一个是根项目 AwesomeProject,另一个是其子项目 app 。 这是在 /android/settings.gradle配置的。 Gradle 将会根据 project 文件夹内的 build.gradle 依次执行构建。

接下来看看我们有哪些 tasks,运行 gralde tasks:

TB1b2gzKpXXXXXtXVXXXXXXXXXX-654-820.gif

tasks 比较多,不一一展开,重点是,找到了我们此次运行的 task:installDebug

这个 tasks 来自于哪里?它是在哪里定义的?你会发现,你搜遍你的项目文件夹,也没有找到这个 task 定义的地方。

原来,Gradle 有一个插件机制,/android/app/build.gradle 中有这一行代码:

apply plugin: “com.android.application”

它加载了 Android Plugin for Gradle ,installDebug 正是它提供的一个 task。

build.gradle

gradle 命令会在当前目录中查找一个叫 build.gradle 的文件。我们称这个 build.gradle 文件为一个构建脚本 (build script), 但是严格来说它是一个构建配置脚本 (build configuration script)。这个脚本定义了一个 project 和它的 tasks。

我们的 android 项目有两个 build.gradle 对应着两个 project,分别是:

关于这 build.gradle 内配置项的介绍,请阅读:《Configuring Gradle Builds》 。这里我们需要了解的是,我们的 JS 资源打包时如何进行配置的。

/android/app/build.gradle 中加载了/android/app/react.gradle,正是这个文件内的配置把 bundleDebugJsAndAssets 的逻辑添加进了 android build process :

1
2
3
4
5
6
7
8
9
10
gradle.projectsEvaluated {
    // hook bundleDebugJsAndAssets into the android build process
    bundleDebugJsAndAssets.dependsOn mergeDebugResources
    bundleDebugJsAndAssets.dependsOn mergeDebugAssets
    processDebugResources.dependsOn bundleDebugJsAndAssets
    // hook bundleReleaseJsAndAssets into the android build process
    bundleReleaseJsAndAssets.dependsOn mergeReleaseResources
    bundleReleaseJsAndAssets.dependsOn mergeReleaseAssets
    processReleaseResources.dependsOn bundleReleaseJsAndAssets
}

由于我们执行的是 ./gradlew installDebug ,这是 debug 模式,所以 bundleDebugJsAndAssets 默认是不执行的

1
enabled config.bundleInDebug ?: false

所以说在 ./gradlew installDebug 时,默认不会打包 JS 。

RN android 的编译打包和普通 android 应用没有区别,Android 的开发体系非常庞大,在这篇文章中不再展开,编译打包的具体流程可通过下图概括:

TB1FqqHJVXXXXbnaXXXXXXXXXXX-536-882.gif

(图片来源:http://developer.android.com/sdk/installing/studio-build.html

打包成功后的 APK 文件在 /android/app/build/outputs/ ,然后 Gradle 会查找当前的虚拟设备,把该 APK 安装到上面。

Native 入口

./gradlew installDebug 没有打包 JS 资源,那我们的应用是怎样加载 JS 呢?

正像我们一开始说的那样,debug 版的 App 是通过去访问开发机上的服务器去获取 JS 资源的。RN Andorid 分为几步来实现:

  • App 程序主入口 MainActivity 在 debug 模式时开启 DeveloperSupport:
1
ReactInstanceManager.builder().setUseDeveloperSupport(BuildConfig.DEBUG)
  • ReactInstanceManager(构建 React 的运行环境,发送事件到 JS, 驱动整个 React 的运转。 通过 builder 可以创建不同的 React 环境:例如内置 JS 文件路径, 开发环境 dev 的 JS 名字,是否支持调试等):创建 DevSupportManager:
1
mDevSupportManager = new DevSupportManager(...);

ReactRootView(Android 标准的 FrameLayout 对象,另外一个功能是提供 React 入口):初始化 React 世界:

1
mReactInstanceManager.attachMeasuredRootView(this)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void createReactContextInBackground() {
    if (mUseDeveloperSupport) {
      if (mDevSupportManager.hasUpToDateJSBundleInCache()) {
        // If there is a up-to-date bundle downloaded from server, always use that
        onJSBundleLoadedFromServer();
        return;
      else if (mBundleAssetName == null ||
          !mDevSupportManager.hasBundleInAssets(mBundleAssetName)) {
        // Bundle not available in assets, fetch from the server
        mDevSupportManager.handleReloadJS();
        return;
      }
    }
    // Use JS file from assets
    recreateReactContextInBackground(
        new JSCJavaScriptExecutor(),
        JSBundleLoader.createAssetLoader(
            mApplicationContext.getAssets(),
            mBundleAssetName));
}

参考资料

Gradle User Guide

Gradle Plugin User Guide

Android Plugin for Gradle

总结

本篇文章跟大家一起深入了解了react-native、run-android背后的执行逻辑,通过对此的学习,我们基本了解了:

  • RN JS 层面的打包流程
  • RN android 应用的打包流程和技术背景

题图:不可阻挡的阳光。



Friends – Connecting Meteor and React Native by example

$
0
0

Friends – Connecting Meteor and React Native by example

Today we’ll take a closer look into the world of app development with React Native and Meteor.

Introducing “Friends”

“Friends” is a sample application which is available on GitHub and uses React Native in combination with Meteor to show you a list of friends which is reactive and updates automatically when friends are added, updated or removed.

kzxVHARI8p

How is this done?

I recommend you to take a look at the commits on GitHub where I’ve explained how to develop this application step by step.

Additionally here’s a rough explanation what these application do and how they interact with each other:

A basic Meteor application acts as a server and data store for your list of friends.
Some example friends are inserted when the Meteor application is started. A publication makes it possible for other clients to subscribe to a list of friends via DDP.

The React Native app subscribes to the friends publication through DDP and renders the friends on a ListView.

Why React Native?

React Native is a very young, but also promising technology. The main selling point of React Native is the JavaScript approach which makes it easy for you to develop Android and iOS application with the help of pure JavaScript. As a Meteor developer you don’t have to switch between JavaScript and Objective-C / Swift anymore. I’ve you’re experienced with React components it will be even easier as React Native uses React components as a view layer.

Conclusion

Meteor and React Native is a great fit. If you want to develop reactive apps in one language you should definitely give it a try and tinker around. It’s impressive how easy you can develop iOS or Android applications if you have a basic understanding of React!


C.H.I.P. vs Pi Zero: Which Sub-$10 Computer Is Better?

$
0
0

$5 Pi Zero and $9 C.H.I.P. with banana for scale. Photography by Hep Svadja

Now that there are two capable, sub-$10 computers for Makers — the $5 Pi Zero and the $9 C.H.I.P. — the debate will rage online over which board is faster, cheaper, and the right one to use in a project. These debates are often unproductive, but they don’t have to be. Let’s take a look at some of the pros and cons of each board.

SPECS COMPARISON

The main processor of the Pi and C.H.I.P. are fairly evenly matched, both operate at 1GHz with 512MB or RAM, but the C.H.I.P. uses the newer ARMv7 architecture (the Pi Zero uses an older ARMv6 architecture, which is confusingly also called ARM11). They each are powered using USB, but C.H.I.P. can also be powered using a Lithium Polymer battery and has built-in charging circuitry. Pi Zero requires a microSD card to act as storage space for an operating system and applications; the slot allows for swappable software and memory expansion at the same size. C.H.I.P. has onboard 4GB of NAND flash storage, and ships with an operating system preloaded in the memory. To go bigger, you have to use USB (a faster interface than the SD card) and an external drive or storage device.

piside1

Pi Zero provides an unpopulated 40-pin connector for input and output (I/O). Whereas C.H.I.P. offers two rows of 40-pin female headers — 80 total I/O — for easily accessible I/O. HDMI mini provides video output on the Pi, and composite video output is possible, but requires aftermarket soldering. C.H.I.P. lacks HDMI — though an HDMI accessory board is available — but has composite video output through the TRRS jack (it looks like a headphones jack).

CHIP , the $9 computer ships

The biggest difference between the two boards is with connectivity. C.H.I.P. has built-in Wi-Fi and BLE; the Pi Zero has no way to access the internet without additional accessories. Solving this lack of connectivity makes the cost of owning a Pi Zero increase greatly. It’s not just that you need a USB Wi-Fi dongle, you’d need a powered USB hub to have a Wi-Fi dongle, keyboard, and mouse (it only has one USB slot for peripherals; the other is for power).

Kiwi for scale, with Pi Zero and C.H.I.P. Photography by Hep Svadja

DIFFERING DESIGN APPROACHES

The debate is also about differing approaches to product design. Is it better to take an existing product and remove components to make it cheaper, or is it better to simply setup and build a cheap product with all the features you want?

On one side, the Pi Foundation has taken an existing design and removed components from it to make it cheaper. The Pi Zero is a smaller board with less connectors. The CPU is faster by 300MHz than the Raspberry Pi B+, but that is thanks to a software configuration setting, which could be done on the B+ too.

Next Thing Co., on the other hand, only has one computer in their product lineup. C.H.I.P. is inexpensive because NTC has leveraged economies of scale and developed close business relationships with suppliers and manufacturer in Shenzhen, China.

This is how we got here. Six months ago Next Thing Co. launched their $9 computer on Kickstarter, generating over $2 million in pledges. The board is now shipping to crowdfunding backers; they’ll begin taking proper preorders on Cyber Monday.

Meanwhile, on Thursday the Raspberry Pi Foundation announced and began to sell the $5 Pi Zero, and included the board in copies of their MagPi print magazine. It was immediately available, but sold out on all reseller sites by the next day.

Screen Shot 2015-11-25 at 6.35.43 PM

OWNERSHIP COSTS MORE THAN RETAIL PRICE

The cost of owning either a C.H.I.P. or a Pi is a bit more money than the retail cost of the boards. Peripherals such as a power cable, keyboard, mouse, and monitor are necessary to accomplish any computer task on either of the devices. But it turns out the $5 Raspberry Pi Zero costs significantly more to operate than the Next Thing Co. C.H.I.P..

C.H.I.P. Raspberry Pi Zero
Retail Cost $9 $5
Cable Cost $1 USB cable for power $13.35 (USB OTG, USB standard to micro, HDMI to HDMI mini)
Storage Cost None (built-in eMMC storage) $5.65 4GB microSD card
Total Cost $10.00 $24.00
Hardware Specs:
GPIO 80 26 of 40
CPU 1GHz Allwinner R8 1Ghz BCM2835 (same as all pre-Pi 2 boards, but overclocked)
RAM 512MB 512MB
Storage 4GB MicroSD card (not provided)
Wall Power USB 5V @ 300mA (peak) USB 5V
Battery Power Single cell 3.7V LiPo battery w/ 2-pin JST-PH 2.0mm None
WiFi 802.11b/g/n None
BLE Yes None
USB 1 standard & 1 micro with OTG 1 micro with OTG; 1 micro
HDMI No (addon $13 HDMI accessory board is available, cheaper if bought with C.H.I.P.) Yes
Composite Yes via ⅛” mini TRRS to RCA composite video output cable None (hardware hack enabled, requires soldering pins to TV holes)
License Open Hardware Closed
OS Custom Linux, soon to be mainline Linux Custom Linux, not mainline
IO Header type Female headers Through holes
Dimensions 40mm×60mm 65mm×30mm×5mm
Included Cables Composite none

ACTUAL OPERATIONAL COSTS

Regardless of how much it costs to operate a Pi or the fact that you have to buy an add-on board to get HDMI output on C.H.I.P., it’s fantastic that both of these products exist. Even seven months ago, the notion that 1GHz computers would cost under $10 would have seemed a bit crazy. And despite the fact that these boards require additional peripherals to operate in a constructive manner, the price is far less than ever before.

COMMUNITY

And lastly, there’s the community aspect. Raspberry Pi has been around since 2012, with millions of its boards in the wild, huge amounts of established software available, and a large community of users who are available to help with any issues.

C.H.I.P. is the new player in this field, and has created a tremendous buzz with their product. It is leveraging strong relationships in the massive Linux and open source software and hardware communities, which may help it gain a large following. But right now, only crowdfunding backers have their boards. It will take a bit of time for those legs to grow.

What do you think the outcome of these low-cost, powerful devices will be, and what projects do you want to make with them? Be sure to tell us in the comments below.


New SIM800 library aimed at HTTP communication & GSM location

$
0
0

New SIM800 library aimed at HTTP communication & GSM location (Read 1 time)Previous TopicNext Topic

Recently I obtained a cheap (under $8) teeny-tiny SIM800 breakout board. The serial UART interfaced SIM800 makes it very easy for any embedded system to add cellular network access and connect to the cloud.

After some efforts, I managed to make it work with an Arduino Leonardo. Basically 5 wires are needed to connect the module to Arduino and they connect pins of VCC/GND/Rx/Tx/Reset. This is quite straight-forward.

My target is continuously sending HTTP requests containing sensor data to a web server (data as URL argument) and retrieve the response containing command. To make it easier for myself and other people who use the same SIM800 based modules, I started to write an Arduino library for this purpose. It contains only what I need at the moment. That includes what is needed to perform HTTP request and retrieving GSM location data. I am expanding it graudually over the next a few weeks. The library is hosted on GitHub and an exmple sketch is also available. The sketch can be as simple as following.

Code: [Select]

#include "SIM800.h"

#define APN "connect"
#define con Serial
static const char* url = "http://arduinodev.com/datetime.php";

CGPRS_SIM800 gprs;

void setup()
{
con.begin(9600);
while (!con);

for (;;) {
con.print("Resetting...");
while (!gprs.init());
con.println("OK");

con.print("Setting up network...");
byte ret = gprs.setup(APN);
if (ret == 0)
break;
con.print("Error code:");
con.println(ret);
}
con.println("OK");

for (;;) {
if (gprs.httpInit()) break;
con.println(gprs.buffer);
gprs.httpUninit();
delay(1000);
}
}

void loop()
{
gprs.httpConnect(url);
while (gprs.httpIsConnected() == 0) {
// can do something here while waiting
}
if (gprs.httpState == HTTP_ERROR) {
con.println("Connect error");
return;
}
con.println();
gprs.httpRead();
int ret;
while ((ret = gprs.httpIsRead()) == 0) {
// can do something here while waiting
}
if (gprs.httpState == HTTP_ERROR) {
con.println("Read error");
return;
}

// now we have received payload
con.print("[Payload]");
con.println(gprs.buffer);

// show position
GSM_LOCATION loc;
if (gprs.getLocation(&loc)) {
con.print("LAT:");
con.print(loc.lat, 6);
con.print(" LON:");
con.print(loc.lon, 6);
con.print(" TIME:");
con.print(loc.hour);
con.print(':');
con.print(loc.minute);
con.print(':');
con.println(loc.second);
}
}

See here for updates about this library


Raspberry Pi Zero 4 Port USB Hub – Open Source PCB Design

$
0
0

Raspberry Pi Zero 4 Port USB Hub – Open Source PCB Design

pi hub.png

Github link: https://github.com/openhardwarecoza/Rpi-Zero-USB-Hub

In line with my other projects I need to make a USB hub attachment for the Pi Zero.
Seeing as the community figured out that the Raspberry Pi Design team was clever enough to leave us D+  and D- test points at the bottom, I came up with this design above.

See those pads for D+, D-, gnd and 5v?  Yip, the ide is that you can acually reflow this board onto the back of a Pi Zero!

Where’s the Gerbers?  I haven’t uploaded the gerbers to Github yet, since I only finished the Eagle drawing a few mins ago. Eagles are off to DirtyPCBs.com, and once I tested the board, I’ll upload.

This is a 4 Port USB2.0 hub designed around the TI TUSB2046B

  • Directly solderable to Pi Zero USB+PWR pads
  • Cutout for GPIO pin bottoms
  • Screw holes match Pi Zero

BOM:

Part     Value           Package

C2       0.01uF          C0603
C5       15pf            C0603
C6       15pF            C0603
C7       1uF             A/3216-18W
C9       22Pf            C0603
C10      22Pf            C0603
C11      22Pf            C0603
C12      22Pf            C0603
C13      22Pf            C0603
C14      22Pf            C0603
C15      1UF             A/3216-18W
C16      1uF             C/6032-28R
C32      22Pf            C0603
C33      22Pf            C0603
IC5      LD117AS33TR     SOT223
JP1      USB-JST-2MM-SMT S4B-PH
JP3      USB-JST-2MM-SMT S4B-PH
JP5      USB-JST-2MM-SMT S4B-PH
JP8      USB-JST-2MM-SMT S4B-PH
Q2       12MHz           CTS406
R1       15K             R0603
R2       15K             R0603
R3       10k             R0603
R4       22              R0603
R7       22              R0603
R12      15K             R0603
R13      15K             R0603
R14      15K             R0603
R15      15K             R0603
R16      15K             R0603
R17      15K             R0603
R18      15k             R0603
U$5      TUSB2046B     LQFP-32

As always, design’s yours to do as you please, if you do end up getting rich selling these, remember you owe me a few beers (;

If you like the work I do, please consider supporting me by donating to https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=45DXEXK9LJSWU


ENCRYPTION FOR ARDUINO WITH SPRITZ

$
0
0

ENCRYPTION FOR ARDUINO WITH SPRITZ

Hackaday.io user [Abderraouf] has written an implementation of the new(ish) Spritz cipher and hash for Arduino. While we’re not big enough crypto-nerds to assess the security of the code, it looks like it’s going to be pretty handy.

Spritz itself is a neat cipher. Instead of taking in fixed blocks of data and operating on them, it allows you to process it in (almost) whatever chunks it comes in naturally, and then extract out the encrypted results piecewise. It works both as a two-way cipher and as a one-way hash function. It looks like Spritz is a one-stop-shop for all of your encryption needs, and now you can run it on your Arduino.

In case you are afraid of new implementations of new ciphers (and you should be), Spritz’s pedigree should help to put you at ease: it was developed by [Ron Rivest] to be a successor to his RC4 algorithm, and it incorporates a lot of the lessons learned about that algorithm over the past. This doesn’t exclude subtle flaws in the implementation of the library (no offence, [Abderraouf]!) or your work downstream, but at least the underlying algorithm seems to be the real deal.

[Abderraouf] links it in his writeup, but just for completeness, here’s the Spritz paper (PDF). What crypto libraries do you currently use for Arduino or microcontroller projects? We’ve been fans of XXTEA for ages, but more because it’s simple and small than because it’s secure. Spritz may be simple enough to implement easily, and still more secure. Sweet.


Web Authentication Methods Explained

$
0
0

Web Authentication Methods Explained

We are keen on security – recently we have published the Node.js Security Checklist. As a sequel, let’s dive deep into the world of cookies, tokens and other web authentication methods.

We are going to start with the most basic one, the HTTP Basic authentication, continue withcookies and tokens, and finish up with signatures and one-time passwords.

HTTP Basic authentication

HTTP Basic authentication is a method for the client to provide a username and a password when making a request.

This is the simplest possible way to enforce access control as it doesn’t require cookies, sessions or anything else. To use this, the client has to send the Authorization header along with every request it makes. The username and password are not encrypted, but constructed this way:

  • username and password are concatenated into a single string: username:password
  • this string is encoded with Base64
  • the Basic keyword is put before this encoded value

Example for a user named john with password secret:

curl --header "Authorization: Basic am9objpzZWNyZXQ=" my-website.com

The same can be observed in Chrome as well:

Google Chrome basic web authentication method

Implementing it is pretty easy in Node.js as well – the following snippet shows how you can do an Express middleware to do so.

import basicAuth from basic-auth;
function unauthorized(res) {
res.set(WWW-Authenticate, Basic realm=Authorization Required);
return res.send(401);
};
export default function auth(req, res, next) {
const {name, pass} = basicAuth(req) || {};
if (!name || !pass) {
return unauthorized(res);
};
if (name === john && pass === secret) {
return next();
}
return unauthorized(res);
};
view rawbasicAuth.es6 hosted with ❤ by GitHub

Of course, you can do it on a higher level, like in nginx.

Looks simple, right? So what are the drawbacks of using HTTP Basic authentication?

The cons:

  • the username and password are sent with every request, potentially exposing them – even if sent via a secure connection
  • connected to SSL/TLS, if a website uses weak encryption, or an attacker can break it, the usernames and passwords will be exposed immediately
  • there is no way to log out the user using Basic auth
  • expiration of credentials is not trivial – you have to ask the user to change password to do so

Cookies

When a server receives an HTTP request in the response, it can send a Set-Cookie header. The browser puts it into a cookie jar, and the cookie will be sent along with every request made to the same origin in the Cookie HTTP header.

To use cookies for authentication purposes, there are a few key principles that one must follow.

Always use HttpOnly cookies

To mitigate the possibility of XSS attacks always use the HttpOnly flag when setting cookies. This way they won’t show up in document.cookies.

Always use signed cookies

With signed cookies, a server can tell if a cookie was modified by the client.

This can be observed in Chrome as well – first let’s take a look at how a server set cookies:

illustration of Chrome cookie set for web authentication purposes

Later on all the requests use the cookies set for the given domain:

web authentication method illustration Chrome cookie usage


The cons:

  • Need to make extra effort to mitigate CSRF attacks
  • Incompatibility with REST – as it introduces a state into a stateless protocol

Tokens

Nowadays JWT (JSON Web Token) is everywhere – still it is worth taking a look on potential security issues.

First let’s see what JWT is!

JWT consists of three parts:

  • Header, containing the type of the token and the hashing algorithm
  • Payload, containing the claims
  • Signature, which can be calculated as follows if you chose HMAC SHA256: HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)

Adding JWT to Koa applications is only a couple of lines of code:

var koa = require(koa);
var jwt = require(koa-jwt);
var app = koa();
app.use(jwt({
secret: very-secret
}));
// Protected middleware
app.use(function *(){
// content of the token will be available on this.state.user
this.body = {
secret: 42
};
});
view rawserver.js hosted with ❤ by GitHub

Example usage – (to check out the validity/content of the token, you can use jwt.io):

curl --header "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ" my-website.com

As the previous ones, the tokens can be observed in Chrome as well:

Google Chrome JSON Web Token as a web authentication method

If you are writing APIs for native mobile applications or SPAs, JWT can be a good fit. One thing to keep in mind: to use JWT in the browser you have to store it in either LocalStorage or SessionStorage, which can lead to XSS attacks.

The cons:

Signatures

Either using cookies or tokens, if the transport layer for whatever reason gets exposed your credentials are easy to access – and with a token or cookie the attacker can act like the real user.

A possible way to solve this – at least when we are talking about APIs and not the browser is to sign each request. How does that work?

When a consumer of an API makes a request it has to sign it, meaning it has to create a hash from the entire request using a private key. For that hash calculation you may use:

  • HTTP method
  • Path of the request
  • HTTP headers
  • Checksum of the HTTP payload
  • and a private key to create the hash

To make it work, both the consumer of the API and the provider have to have the same private key. Once you have the signature, you have to add it to the request, either in query strings or HTTP headers. Also, a date should be added as well, so you can define an expiration date.

AWS Request Signing: Flow of a Web Authentication MethodAWS Request Signing Flow – source

Why go through all these steps? Because even if the transport layer gets compromised, an attacker can only read your traffic, won’t be able to act as a user, as the attacker will not be able to sign requests – as the private key is not in his/her possession. Most AWS services are using this kind of authentication.

node-http-signature deals with HTTP Request Signing and worth checking out.

The cons:

  • cannot use in the browser / client, only between APIs

One-Time Passwords

One-Time passwords algorithms generate a one-time password with a shared secret and either the current time or a counter:

  • Time-based One-time Password Algorithm, based on the current time,
  • HMAC-based One-time Password Algorithm, based on a counter.

These methods are used in applications that leverage two-factor authentication: a user enters the username and password then both the server and the client generates a one-time password.

In Node.js, implementing this using notp is relatively easy.

Cons:

  • with the shared-secret (if stolen) user tokens can be emulated
  • because clients can be stolen / go wrong every real-time application have methods to bypass this, like an email reset that adds additional attack vectors to the application

Which web authentication method to pick when?

If you have to support a web application only, either cookies or tokens are fine – for cookies think about XSRF, for JWT take care of XSS.

If you have to support both a web application and a mobile client, go with an API that supports token-based authentication.

If you are building APIs that communicate with each other, go with request signing.

You have additional thoughts or insights on the topic? Share it in the comments.


How to run a Pi Zero (and other Pi’s) from a LiPo Including low battery @Raspberry_Pi #piday #raspberypi

$
0
0

How to run a Pi Zero (and other Pi’s) from a LiPo Including low battery @Raspberry_Pi #piday #raspberypi

Wiring

Super useful hack from Daniel Bull posted on Google Plus, via raspberrypipod.

Including low battery automatic shutdown (to stop your SD card from getting corrupted), push button start, and automatic power supply off when the Pi is shutdown to stop your LiPo from going flat.

I’ve included full instructions on how to do this including circuit diagrams here:
https://github.com/NeonHorizon/lipopi

Read more.


Featured Adafruit Products!

1944 00

PowerBoost 500 Charger – Rechargeable 5V Lipo USB Boost @ 500mA+: PowerBoost 500C is the perfect power supply for your portable project! With a built-in battery charger circuit, you’ll be able to keep your project running even while recharging the battery! This little DC/DC boost converter module can be powered by any 3.7V LiIon/LiPoly battery, and convert the battery output to 5.2V DC for running your 5V projects. (read more)



DES algorithm on Arduino

$
0
0

DES algorithm

Here is the arduino DES algorithm which implements a full DES encryption and decoding.
You can set the key and use any plaintext  and cipher text and take the algorithm any way you want.
It is very visual in that every step prints to screen all the details so you can see how it works. This way you will quickly grasp the DES algorithm.
You can find the arduino DES algorithm code to download in my example below which is based on the Daniel Otte version (See link below). If you want to see the detailed steps of how a DES algorithm is built up you can look at this page describing the data encryption standard.
Click on the link below to see what the program looks like on the page.

Hide «

/*

 * Title  DES algorithm for the Data Encryption Standard implementation
 * based on DES algorithm by  Daniel Ottee  email daniel.otte@rub.de 
 * date     14-02-2012
 */
#include <stdint.h>
#include <string.h>

const uint8_t sbox[256]  = {
  /* S-box 1 */
  0xE4, 0xD1, 0x2F, 0xB8, 0x3A, 0x6C, 0x59, 0x07,
  0x0F, 0x74, 0xE2, 0xD1, 0xA6, 0xCB, 0x95, 0x38,
  0x41, 0xE8, 0xD6, 0x2B, 0xFC, 0x97, 0x3A, 0x50,
  0xFC, 0x82, 0x49, 0x17, 0x5B, 0x3E, 0xA0, 0x6D,
  /* S-box 2 */
  0xF1, 0x8E, 0x6B, 0x34, 0x97, 0x2D, 0xC0, 0x5A,
  0x3D, 0x47, 0xF2, 0x8E, 0xC0, 0x1A, 0x69, 0xB5,
  0x0E, 0x7B, 0xA4, 0xD1, 0x58, 0xC6, 0x93, 0x2F,
  0xD8, 0xA1, 0x3F, 0x42, 0xB6, 0x7C, 0x05, 0xE9,
  /* S-box 3 */
  0xA0, 0x9E, 0x63, 0xF5, 0x1D, 0xC7, 0xB4, 0x28,
  0xD7, 0x09, 0x34, 0x6A, 0x28, 0x5E, 0xCB, 0xF1,
  0xD6, 0x49, 0x8F, 0x30, 0xB1, 0x2C, 0x5A, 0xE7,
  0x1A, 0xD0, 0x69, 0x87, 0x4F, 0xE3, 0xB5, 0x2C,
  /* S-box 4 */
  0x7D, 0xE3, 0x06, 0x9A, 0x12, 0x85, 0xBC, 0x4F,
  0xD8, 0xB5, 0x6F, 0x03, 0x47, 0x2C, 0x1A, 0xE9,
  0xA6, 0x90, 0xCB, 0x7D, 0xF1, 0x3E, 0x52, 0x84,
  0x3F, 0x06, 0xA1, 0xD8, 0x94, 0x5B, 0xC7, 0x2E,
  /* S-box 5 */
  0x2C, 0x41, 0x7A, 0xB6, 0x85, 0x3F, 0xD0, 0xE9,
  0xEB, 0x2C, 0x47, 0xD1, 0x50, 0xFA, 0x39, 0x86,
  0x42, 0x1B, 0xAD, 0x78, 0xF9, 0xC5, 0x63, 0x0E,
  0xB8, 0xC7, 0x1E, 0x2D, 0x6F, 0x09, 0xA4, 0x53,
  /* S-box 6 */
  0xC1, 0xAF, 0x92, 0x68, 0x0D, 0x34, 0xE7, 0x5B,
  0xAF, 0x42, 0x7C, 0x95, 0x61, 0xDE, 0x0B, 0x38,
  0x9E, 0xF5, 0x28, 0xC3, 0x70, 0x4A, 0x1D, 0xB6,
  0x43, 0x2C, 0x95, 0xFA, 0xBE, 0x17, 0x60, 0x8D,
  /* S-box 7 */
  0x4B, 0x2E, 0xF0, 0x8D, 0x3C, 0x97, 0x5A, 0x61,
  0xD0, 0xB7, 0x49, 0x1A, 0xE3, 0x5C, 0x2F, 0x86,
  0x14, 0xBD, 0xC3, 0x7E, 0xAF, 0x68, 0x05, 0x92,
  0x6B, 0xD8, 0x14, 0xA7, 0x95, 0x0F, 0xE2, 0x3C,
  /* S-box 8 */
  0xD2, 0x84, 0x6F, 0xB1, 0xA9, 0x3E, 0x50, 0xC7,
  0x1F, 0xD8, 0xA3, 0x74, 0xC5, 0x6B, 0x0E, 0x92,
  0x7B, 0x41, 0x9C, 0xE2, 0x06, 0xAD, 0xF3, 0x58,
  0x21, 0xE7, 0x4A, 0x8D, 0xFC, 0x90, 0x35, 0x6B
};

const uint8_t e_permtab[] ={
	 4,  6, 					/* 4 bytes in 6 bytes out*/
	32,  1,  2,  3,  4,  5,
	 4,  5,  6,  7,  8,  9,
	 8,  9, 10, 11, 12, 13,
	12, 13, 14, 15, 16, 17,
	16, 17, 18, 19, 20, 21,
	20, 21, 22, 23, 24, 25,
	24, 25, 26, 27, 28, 29,
	28, 29, 30, 31, 32,  1
};

const uint8_t p_permtab[] ={
	 4,  4,						/* 32 bit -> 32 bit */
	16,  7, 20, 21,
	29, 12, 28, 17,
	 1, 15, 23, 26,
	 5, 18, 31, 10,
	 2,  8, 24, 14,
	32, 27,  3,  9,
	19, 13, 30,  6,
	22, 11,  4, 25
};

const uint8_t ip_permtab[] ={
	 8,  8,						/* 64 bit -> 64 bit */
	58, 50, 42, 34, 26, 18, 10, 2,
	60, 52, 44, 36, 28, 20, 12, 4,
	62, 54, 46, 38, 30, 22, 14, 6,
	64, 56, 48, 40, 32, 24, 16, 8,
	57, 49, 41, 33, 25, 17,  9, 1,
	59, 51, 43, 35, 27, 19, 11, 3,
	61, 53, 45, 37, 29, 21, 13, 5,
	63, 55, 47, 39, 31, 23, 15, 7
};

const uint8_t inv_ip_permtab[] ={
	 8, 8,						/* 64 bit -> 64 bit */
	40, 8, 48, 16, 56, 24, 64, 32,
	39, 7, 47, 15, 55, 23, 63, 31,
	38, 6, 46, 14, 54, 22, 62, 30,
	37, 5, 45, 13, 53, 21, 61, 29,
	36, 4, 44, 12, 52, 20, 60, 28,
	35, 3, 43, 11, 51, 19, 59, 27,
	34, 2, 42, 10, 50, 18, 58, 26,
	33, 1, 41,  9, 49, 17, 57, 25
};

const uint8_t pc1_permtab[] ={
	 8,  7, 					/* 64 bit -> 56 bit*/
	57, 49, 41, 33, 25, 17,  9,
	 1, 58, 50, 42, 34, 26, 18,
	10,  2, 59, 51, 43, 35, 27,
	19, 11,  3, 60, 52, 44, 36,
	63, 55, 47, 39, 31, 23, 15,
	 7, 62, 54, 46, 38, 30, 22,
	14,  6, 61, 53, 45, 37, 29,
	21, 13,  5, 28, 20, 12,  4
};

const uint8_t pc2_permtab[] ={
	 7,	 6, 					/* 56 bit -> 48 bit */
	14, 17, 11, 24,  1,  5,
	 3, 28, 15,  6, 21, 10,
	23, 19, 12,  4, 26,  8,
	16,  7, 27, 20, 13,  2,
	41, 52, 31, 37, 47, 55,
	30, 40, 51, 45, 33, 48,
	44, 49, 39, 56, 34, 53,
	46, 42, 50, 36, 29, 32
};

const uint8_t splitin6bitword_permtab[] = {
	 8,  8, 					/* 64 bit -> 64 bit */
	64, 64,  1,  6,  2,  3,  4,  5, 
	64, 64,  7, 12,  8,  9, 10, 11, 
	64, 64, 13, 18, 14, 15, 16, 17, 
	64, 64, 19, 24, 20, 21, 22, 23, 
	64, 64, 25, 30, 26, 27, 28, 29, 
	64, 64, 31, 36, 32, 33, 34, 35, 
	64, 64, 37, 42, 38, 39, 40, 41, 
	64, 64, 43, 48, 44, 45, 46, 47 
};

const uint8_t shiftkey_permtab[] = {
	 7,  7, 					/* 56 bit -> 56 bit */
	 2,  3,  4,  5,  6,  7,  8,  9,
	10, 11, 12, 13, 14, 15, 16, 17,
	18, 19, 20, 21, 22, 23, 24, 25, 
	26, 27, 28,  1, 
	30, 31, 32, 33, 34, 35, 36, 37, 
	38, 39, 40, 41, 42, 43, 44, 45, 
	46, 47, 48, 49, 50, 51, 52, 53, 
	54, 55, 56, 29
};

/*
1 2 2 2   2 2 2 1   2 2 2 2   2 2 1 1
0 1 1 1   1 1 1 0   1 1 1 1   1 1 0 0
      7         E         F         C    Standard DES
2 1 1 1   1 1 1 1   2 2 1 1   1 2 1 1
1 0 0 0   0 0 0 0   1 1 0 0   0 1 0 0
      8         0         C         4    Meteotime DES
*/
#define ROTTABLE      0x7EFC 
byte crypt [8];
byte plaintext [] = { 00,01,02,03,04,05,06,07};
byte keyword [] = { 0x3b,0x38,0x98,0x37,0x15,0x20,0xf7,0x5e};
byte test[8];
boolean DEBUG = true;
int i,m;
int Dx =0;
uint32_t box=0,t;
String showprint = "";
uint8_t data[8];
/******************************************************************************/
void setup(){

Serial.begin(19200);
Serial.println("Start");
Serial.print ("Keyword       = ");
for (int j=0;j<8;j++){
if (keyword[j]<0x10) Serial.print("0"); 
Serial.print(keyword[j],HEX);Serial.print(" ");
}
Serial.println();
Serial.print ("Plaintext     = ");
for (int j=0;j<8;j++){
if (plaintext[j]<0x10) Serial.print("0"); 
Serial.print(plaintext[j],HEX);Serial.print(" ");
}
Serial.println();
Serial.println("Encrypting");
//void des_enc(void* out, const void* in, const void* key);
des_enc( crypt, plaintext, keyword);
Serial.print("Encrypted key  = ");
for (int j=0;j<8;j++){
if (crypt[j]<0x10) Serial.print("0"); 
Serial.print(crypt[j],HEX);Serial.print(" ");
}
Serial.println();
Serial.println("Decrypting");
//void des_dec(void* out, const void* in, const void* key);
des_dec( plaintext, crypt, keyword);
Serial.print("Decrypted key  = ");
for (int j=0;j<8;j++){
if (plaintext[j]<0x10) Serial.print("0"); 
Serial.print(plaintext[j],HEX);Serial.print(" ");
}
Serial.println();
Serial.println("Done");
}

void loop(){
}

void permute(const uint8_t *ptable, const uint8_t *in, uint8_t *out){
	uint8_t ob; /* in-bytes and out-bytes */
	uint8_t byte, bit; /* counter for bit and byte */
	ob = ptable[1];
	ptable = &(ptable[2]);
	for(byte=0; byte<ob; ++byte){
		uint8_t x,t=0;
		for(bit=0; bit<8; ++bit){
			x=*ptable++ -1 ;
				t<<=1;
			if((inyes) & (0x80>>(x%8)) ){
				t|=0x01;
			}
		}
		out[byte]=t;test[byte]=t;
	}
}

/******************************************************************************/

void changeendian32(uint32_t * a){
	*a = (*a & 0x000000FF) << 24 |
		 (*a & 0x0000FF00) <<  8 |
		 (*a & 0x00FF0000) >>  8 |
		 (*a & 0xFF000000) >> 24;
box=((*a & 0x000000FF) << 24)|
		 (*a & 0x0000FF00) <<  8 |
		 (*a & 0x00FF0000) >>  8 |
		 (*a & 0xFF000000) >> 24;
}

/******************************************************************************/
static inline
void shiftkey(uint8_t *key){
	uint8_t k[7];
	memcpy(k, key, 7);
	permute((uint8_t*)shiftkey_permtab, k, key);
        if (DEBUG == true) {
        Serial.print ("CD[");Serial.print(m);Serial.print ("]  56 xits = ");
        for (int j=0;j<7;j++){
        if (test[j]<0x10) Serial.print("0"); 
        Serial.print(test[j],HEX);Serial.print(" ");
        print_binary(test[j],8);Serial.print(" ");
        }
        Serial.println();
        }
}

/******************************************************************************/

/******************************************************************************/
static inline
uint64_t splitin6bitwords(uint64_t a){
	uint64_t ret=0;
	a &= 0x0000ffffffffffffLL;
	permute((uint8_t*)splitin6bitword_permtab, (uint8_t*)&a, (uint8_t*)&ret);
	return ret;
}

/******************************************************************************/

static inline
uint8_t substitute(uint8_t a, uint8_t * sbp){
	uint8_t x;
	x = sbp[a>>1];
	x = (a&1)?x&0x0F:x>>4;
	return x;

}

/******************************************************************************/

uint32_t des_f(uint32_t r, uint8_t* kr){
	uint8_t i;
	uint32_t ret;
	uint64_t data;
	uint8_t *sbp; /* sboxpointer */ 
	permute((uint8_t*)e_permtab, (uint8_t*)&r, (uint8_t*)&data);
        showprint ="E      48 bits = ";printout1(0,6);
	for(i=0; i<7; ++i) {((uint8_t*)&data)[i] ^= kr[i];}
        if (DEBUG == true) {
        Serial.print ("ExorKS 48 bits = ");
        for (int j=0;j<6;j++){
        if (((uint8_t*)&data)[j]<0x10) Serial.print("0"); 
        Serial.print(((uint8_t*)&data)[j],HEX);Serial.print(" ");
        print_binary(((uint8_t*)&data)[j],8);Serial.print(" ");
        }
        Serial.println();
        }

	/* Sbox substitution */
	data = splitin6bitwords(data);
	sbp=(uint8_t*)sbox;
	for(i=0; i<8; ++i){
		uint8_t x;
		x = substitute(((uint8_t*)&data)[i], sbp);
		t<<=4;
		t |= x;
		sbp += 32;
	}
	changeendian32(&t);
        if (DEBUG == true) { 
        Serial.print ("Sbox   32 bits = ");

        if (box/0x1000000<0x10) Serial.print("0"); 
        Serial.print(box/0x1000000,HEX);Serial.print(" ");
        print_binary(box/0x1000000,8);Serial.print(" ");

        if (box/0x10000&0xFF<0x10) Serial.print("0"); 
        Serial.print(box/0x10000&0xFF,HEX);Serial.print(" ");
        print_binary(box/0x10000&0xFF,8);Serial.print(" "); 

        if (((box/0x100)&0xFF)<0x10) Serial.print("0"); 
        Serial.print(box/0x100&0xFF,HEX);Serial.print(" ");        
        print_binary(box/0x100,8);Serial.print(" ");

        if (box&0xFF<0x10) Serial.print("0"); 
        Serial.print(box&0xFF,HEX);Serial.print(" ");        
        print_binary(box&0xFF,8);        
        Serial.println();
        }
	permute((uint8_t*)p_permtab,(uint8_t*)&t, (uint8_t*)&ret);
        showprint = "P      32 bits = "; printout1(0,4); 
	return ret;
}

/******************************************************************************/

void des_enc(void* out, const void* in, const void* key){
#define R *((uint32_t*)&(data[4]))
#define L *((uint32_t*)&(data[0]))
	uint8_t kr[6],k[7];
	permute((uint8_t*)ip_permtab, (uint8_t*)in, data); 
        showprint = "L[0]   32 bits = "; printout1(0,4);
        showprint = "R[0]   32 bits = "; printout1(4,8);
	permute((uint8_t*)pc1_permtab, (const uint8_t*)key, k);
        showprint = "CD[0]  56 bits = "; printout1(0,7);
	for(i=0; i<8; i++){

                Dx=i*2+1;
                if (DEBUG == true) { Serial.print("Round ");Serial.println(Dx); }
		shiftkey(k);
		if(ROTTABLE&((1<<((i<<1)+0))) ) shiftkey(k);
		permute((uint8_t*)pc2_permtab, k, kr);     
                showprint = "KS     48 bits = "; printout1(0,6);
		L ^= des_f(R, kr);
                showprint = "L[i]   32 bits = "; printout2(0,4);
                showprint = "R[i]   32 bits = "; printout2(4,8);

                Dx=i*2+2;
                if (DEBUG == true) { Serial.print("Round ");Serial.println(Dx); }              
		shiftkey(k);
		if(ROTTABLE&((1<<((i<<1)+1))) ) shiftkey(k);
		permute((uint8_t*)pc2_permtab, k, kr);
                showprint = "KS     48 bits = "; printout1(0,6);
		R ^= des_f(L, kr);
                showprint = "L[i]   32 bits = "; printout2(0,4);
                showprint = "R[i]   32 bits = "; printout2(4,8);
	}
	/* L <-> R*/
	R ^= L;
	L ^= R;
	R ^= L;
        showprint = "LR[16] 64 bits = "; printout2(0,8);
	permute((uint8_t*)inv_ip_permtab, data, (uint8_t*)out);
        showprint = "Crypt  64 bits = "; printout1(0,8);
}

/******************************************************************************/

void des_dec(void* out, const void* in, const uint8_t* key){
#define R *((uint32_t*)&(data[4]))
#define L *((uint32_t*)&(data[0]))
	uint8_t kr[6],k[7];
        Serial.print("crypt  64 bits = ");
        for (int j=0;j<8;j++){
        if (crypt[j]<0x10) Serial.print("0"); 
        Serial.print(crypt[j],HEX);Serial.print(" ");
        print_binary(crypt[j],8);Serial.print(" ");
        }
        Serial.println();
        Serial.print("key    64 bits = ");
        for (int j=0;j<8;j++){
        if (key[j]<0x10) Serial.print("0"); 
        Serial.print(key[j],HEX);Serial.print(" ");
        print_binary(key[j],8);Serial.print(" ");
        }
        Serial.println();        
	permute((uint8_t*)ip_permtab, (uint8_t*)in, data);
        showprint = "L[0]   32 bits = "; printout1(0,4);
        showprint = "R[0]   32 bits = "; printout1(4,8);
	permute((uint8_t*)pc1_permtab, (const uint8_t*)key, k);
        showprint = "CD[0]  56 bits = "; printout1(0,7);
	for(i=7; i>=0; i--){

                Dx=i*2+2;
                if (DEBUG == true) { Serial.print("Round ");Serial.println(Dx); }
                permute((uint8_t*)pc1_permtab, (const uint8_t*)key, k);
                for (m=1;m<Dx+1;m++){ 
                shiftkey(k);
                if(ROTTABLE&(1<<(m-1))) shiftkey(k);
                }              
		permute((uint8_t*)pc2_permtab, k, kr);
                showprint = "KS     48 bits = "; printout1(0,6);
		L ^= des_f(R, kr);
                showprint = "L[i]   32 bits = "; printout2(0,4);
                showprint = "R[i]   32 bits = "; printout2(4,8);

                Dx=i*2+1;
                if (DEBUG == true) { Serial.print("Round ");Serial.println(Dx); } 
                permute((uint8_t*)pc1_permtab, (const uint8_t*)key, k);
                for (m=1;m<Dx+1;m++){  
 		shiftkey(k);
                if(ROTTABLE&(1<<(m-1))) shiftkey(k); 
                }              
		permute((uint8_t*)pc2_permtab, k, kr);
                showprint = "KS     48 bits = "; printout1(0,6);
		R ^= des_f(L, kr);
                showprint = "L[i]   32 bits = "; printout2(0,4);
                showprint = "R[i]   32 bits = "; printout2(4,8);
	}
	/* L <-> R*/
	R ^= L;
	L ^= R;
	R ^= L;
        showprint = "LR[16] 64 bits = "; printout2(0,8);
	permute((uint8_t*)inv_ip_permtab, data, (uint8_t*)out);
        showprint = "Plain  64 bits = "; printout1(0,8);
}
void print_binary(uint64_t v, int num_places)
{
    uint64_t mask=0, n;
    for (n=1; n<=num_places; n++)
    {
        mask = (mask << 1) | 0x00000001;
    }
    v = v & mask;  // truncate v to specified number of places
    while(num_places)
    {
        if (v & (0x00000001 << num_places-1))
        {
             Serial.print("1");
        }
        else
        {
             Serial.print("0");
        }
        --num_places;
        if(((num_places%8) == 0) && (num_places != 0))
        {
            Serial.print(" ");
        }

    }
}
void printout1(int min,int max) {
        if (DEBUG == true) {
        Serial.print (showprint);
        for (int j=min;j<max;j++){
        if (test[j]<0x10) Serial.print("0");
        Serial.print(test[j],HEX);Serial.print(" ");
        print_binary(test[j],8);Serial.print(" ");
        }
        Serial.println();
        }
}
void printout2(int min,int max) {
        if (DEBUG == true) {
        Serial.print (showprint);
        for (int j=min;j<max;j++){
        if (data[j]<0x10) Serial.print("0");
        Serial.print(data[j],HEX);Serial.print(" ");
        print_binary(data[j],8);Serial.print(" ");
        }
        Serial.println();
        }
}

Other DES algorithm related stuff:

There are other encryption techniques such as AES etc used which can be seen here.
http://www.efgh.com/software/des.htm
http://dvd-copy-software-review.toptenreviews.com/the-dos-and-donts-of-decryption.html
There is a very good excel version of such a process which visualizes the whole process that can be downloaded from the bottom of the link above.
Other version non arduino of the DES algorithm by Daniel Otte.

Here you can find my other arduino projects.


ArduinoLibs Cryptographic Library

$
0
0
Cryptographic Library

Supported Algorithms

All cryptographic algorithms have been optimized for 8-bit Arduino platforms like the Uno. Memory usage is also reduced, particularly for SHA1, SHA256, and SHA512 which save 256, 192, and 512 bytes respectively over traditional implementations. For all algorithms, static sbox tables and the like are placed into program memory to further reduce data memory usage.

ChaCha with 20 rounds and 256-bit keys is the recommended symmetric encryption algorithm because it is twice as fast as AES128, constant-time, and much more secure. AES128, AES192, and AES256 are provided for use in applications where compatibility with other systems is desirable.

If code size is an issue for your application (for example on very low end Arduino variants), then Speck on AVR is less than half the code size of ChaCha, at the cost of more data memory for the state and longer key setup times. The SpeckLowMemory class is even smaller at the cost of some performance when encrypting.

BLAKE2s and BLAKE2b are variations on the ChaCha stream cipher, designed for hashing, with 256-bit and 512-bit hash outputs respectively. They are intended as high performance replacements for SHA256 and SHA512 for when speed is critical but exact bit-compatibility of hash values is not.

Examples and other topics

Performance

Performance on AVR

All figures are for the Arduino Uno running at 16 MHz. Figures for the Ardunino Mega 2560 running at 16 MHz are similar:

Encryption Algorithm Encryption (per byte) Decryption (per byte) Key Setup State Size (bytes)
AES128 (ECB mode) 36.90us 66.48us 160.00us 213
AES192 (ECB mode) 44.20us 80.35us 166.54us 245
AES256 (ECB mode) 51.50us 94.22us 227.97us 277
ChaCha (20 rounds) 14.87us 14.88us 43.74us 132
ChaCha (12 rounds) 10.38us 10.38us 43.74us 132
ChaCha (8 rounds) 8.13us 8.14us 43.74us 132
Speck (128-bit key, ECB mode) 10.72us 11.09us 287.02us 275
Speck (192-bit key, ECB mode) 11.03us 11.42us 298.21us 275
Speck (256-bit key, ECB mode) 11.35us 11.74us 309.66us 275
SpeckLowMemory (128-bit key, ECB mode) 35.25us 10.22us 35
SpeckLowMemory (192-bit key, ECB mode) 36.56us 13.62us 35
SpeckLowMemory (256-bit key, ECB mode) 37.87us 16.89us 35
AEAD Algorithm Encryption (per byte) Decryption (per byte) Key Setup State Size (bytes)
ChaChaPoly 41.23us 41.23us 902.55us 255
GCM<AES128> 186.47us 186.42us 1388.43us 316
GCM<AES192> 194.17us 193.72us 1628.67us 348
GCM<AES256> 201.47us 201.02us 1923.78us 380
Hash Algorithm Hashing (per byte) Finalization State Size (bytes)
SHA1 21.90us 1423.28us 95
SHA256 43.85us 2841.04us 107
SHA512 122.82us 15953.42us 211
SHA3_256 121.69us 16486.33us 405
SHA3_512 229.12us 16502.34us 405
BLAKE2s 18.54us 1200.06us 171
BLAKE2b 50.70us 6515.87us 339
Authentication Algorithm Hashing (per byte) Finalization Key Setup State Size (bytes)
SHA1 (HMAC mode) 21.90us 4296.33us 1420.24us 95
SHA256 (HMAC mode) 43.85us 8552.61us 2836.49us 107
BLAKE2s (HMAC mode) 18.54us 3649.98us 1214.81us 171
Poly1305 26.29us 486.15us 17.26us 87
GHASH 148.14us 17.09us 21.87us 33
Public Key Operation Time (per operation) Comment
Curve25519::eval() 3119ms Raw curve evaluation
Curve25519::dh1() 3121ms First half of Diffie-Hellman key agreement
Curve25519::dh2() 3120ms Second half of Diffie-Hellman key agreement
Ed25519::sign() 5688ms Digital signature generation
Ed25519::verify() 9030ms Digital signature verification
Ed25519::derivePublicKey() 5642ms Derive a public key from a private key

Where a cipher supports more than one key size (such as ChaCha), the values are typically almost identical for 128-bit and 256-bit keys so only the maximum is shown above.

Performance on ARM

All figures are for the Arduino Due running at 84 MHz:

Encryption Algorithm Encryption (per byte) Decryption (per byte) Key Setup State Size (bytes)
AES128 (ECB mode) 6.65us 11.00us 35.15us 220
AES192 (ECB mode) 8.02us 13.31us 36.59us 252
AES256 (ECB mode) 9.39us 15.63 50.19us 284
ChaCha (20 rounds) 0.87us 0.88us 4.96us 136
ChaCha (12 rounds) 0.70us 0.71us 4.96us 136
ChaCha (8 rounds) 0.62us 0.62us 4.96us 136
Speck (128-bit key, ECB mode) 0.97us 0.96us 36.80us 288
Speck (192-bit key, ECB mode) 1.00us 0.98us 38.14us 288
Speck (256-bit key, ECB mode) 1.03us 1.01us 39.31us 288
SpeckLowMemory (128-bit key, ECB mode) 2.72us 1.47us 48
SpeckLowMemory (192-bit key, ECB mode) 2.81us 1.54us 48
SpeckLowMemory (256-bit key, ECB mode) 2.90us 1.83us 48
AEAD Algorithm Encryption (per byte) Decryption (per byte) Key Setup State Size (bytes)
ChaChaPoly 1.66us 1.66us 45.02us 280
GCM<AES128> 11.01us 10.92us 247.90us 344
GCM<AES192> 12.40us 12.31us 294.07us 376
GCM<AES256> 13.73us 13.64us 347.40us 408
Hash Algorithm Hashing (per byte) Finalization State Size (bytes)
SHA1 0.94us 62.55us 112
SHA256 1.15us 76.60us 120
SHA512 2.87us 370.37us 224
SHA3_256 5.36us 697.65us 424
SHA3_512 9.89us 697.81us 424
BLAKE2s 0.76us 50.88us 184
BLAKE2b 1.33us 170.93us 352
Authentication Algorithm Hashing (per byte) Finalization Key Setup State Size (bytes)
SHA1 (HMAC mode) 0.94us 193.92us 65.09us 112
SHA256 (HMAC mode) 1.15us 238.98us 80.44us 120
BLAKE2s (HMAC mode) 0.76us 165.64us 59.92us 184
Poly1305 0.85us 19.25us 2.35us 96
GHASH 4.37us 1.50us 4.37us 36
Public Key Operation Time (per operation) Comment
Curve25519::eval() 103ms Raw curve evaluation
Curve25519::dh1() 103ms First half of Diffie-Hellman key agreement
Curve25519::dh2() 104ms Second half of Diffie-Hellman key agreement
Ed25519::sign() 195ms Digital signature generation
Ed25519::verify() 306ms Digital signature verification
Ed25519::derivePublicKey() 194ms Derive a public key from a private key

Introduction to EAGLE

$
0
0

Introduction to EAGLE – Part 1 – Control panel

This article is part of a tutorial dedicated to EAGLE. The reader may consult the other parts of the tutorial by following this link: Introduction to EAGLE
Eagle stands for Easily Applicable Graphical Layout Editor. It is an electronic CAD software manufactured by CadSoft Computer GmbH, a German company, since 1988. This software is provided with, among other, a schematic capture editor, a PCB (Printed Circuit Board) layout editor, an auto-router, a Computer-Aided Manufacturing (CAM)… It supports Windows, Linux and Mac OS X. This tutorial has been prepared under version 6.5.0 / Ubuntu 12.04 LTS

Control panel

When EAGLE is started, the following window appears on the screen,this is the control panel, the EAGLE starting window.ControlPanelOn the left hand side of the window the user manage existing and new projects and can get an overview about the libraries and settings :

  • Libraries: this entry lists libraries of components, each component is composed of a schematic and a footprint linked together.
  • Design Rules: the user can tune the parameters relevant to the board and its manufacture.
  • User Language Programs: this is C-like programs that can be used for a variety of tasks. It can be used, for example, to modify your project and automize certain tasks.
  • Scripts: the user can execute sequences of commands that are stored in a script file. It provides the ability to customize the program according to your own wishes (assign keys,
    load pc board shapes, change colors…)
  • CAM Jobs: CAM stands for Computer-Aided Manufacturing. It generates output data for the manufacturing tools (for exemple exporting Gerbers files which is the most used professional format).
  • Projects: this entry lists the examples and projets. When a new project is created, it is automaticaly added in the tree.

The Arduino MEGA2560 board has been designed with EAGLE. It is provided within the examples:

Arduino

Directories

Basicaly, EAGLE stores all the projects and necessary files in the same main folder and creates subfolders to differenciate each projet. In the main menu bar, select Option > Directories:

Menu_Directory

The following interface allows the user to configure directories. $EAGLEDIR represents the path to the main folder (on my installation it is located in /home/username/eagle-6.5.0/). When a new project is created, a new folder is automatically added in $EAGLEDIR/projects/ . The user can specify several folders. It is possible, for example, to have the default libraries available on a network server, and the personal projects in private local folders.

Directory

Before continuing check that the folder for libraries is configured with the following path: $EAGLEDIR\lbr.

Libraries

On the left hand side of the control panel, click on Libraries to develop the tree and select the library 74xx-eu.lbr. This library is dedicated to TTL Devices (74xx Series from Texas Instruments). Select a device, on the right side the symbol and footprint appear:

Library

New project

To create a new project, select File > New > Project :
NewProject

A new project is automatically added on the left hand side of the window under the branch Project/eagle. Enter you project name, for example FirstPCB :

ProjectNameRight click on the project and select New > Schematic.
NewSchematic

A new window is automatically open, this is the Schematic Editor:
SchematicEditor

Click here for the next step

Introduction to EAGLE – Part 2 – Schematic editor

This article is part of a tutorial dedicated to EAGLE. The reader may consult the other parts of the tutorial by following this link: Introduction to EAGLE
In this tutorial the reader will be guided to create a simple PCB, first lets start by creating the schematics.

Workspace

Before starting the schematic, lets insert a frame containing title, date, author … On the vertical tool bar located on the left side of the window, click on the ADD icon. The ADD action allows to add new item in the design. It is largely dedicated to the insertion of new components.

Add_Icon

A window pops up and display all the available libraries. In the search entry located at the bottom left of the window, type “frame” and confirm with the Enter key :
Add_Frame
The list of libraries is now limited to entries containing the string “frame” in there title or description. Select the A4L-LOC which is a DIN A4 Landscape frame and click OK. The frame is now attached to the cursor, place the frame in order to align the bottom-left corner of the frame at coordinates 0,0. Coordinates are displayed in the upper left corner of the working area. The origin is also display in the working area with a small dotted cross. When the frame is placed, left click with the mouse and hit twice the “Esc” key to exit.

Frame_Grid

Save your design and change the view by clicking on “Zoom to fit”. You should now have a general view of your future design.

ZoomToFit

Click on the grid icon:

Grid

The grid setting window appears, in this window, you can set the grid parameters (size, style, etc.). Set display “On” and click “OK”. Your workspace is prepared for the schematic and should look like this:

Workspace

Adding symbols

Click to the ADD icon as explained previously for adding the frame. EAGLE is provided with a large number of librairies, and the user can enter one or more search patterns in the search field by using special characters (wild cards) ‘?’ and ‘*’:

  • * is a search pattern that can be replaced by one or several characters. For example *555 will provide all the entries ending by 555. 555* will provide all the entries beginning by 555 and *555* will provide all the entries containing 555.
  • ? is a search pattern similar to ‘*’, excepted that it can only be replaced by a single character.

It is usefull to remember that when you add a device, right click rotate and left click place the symbol. Once a symbol is placed, several operations are still possible :

Move     Copy  RotateDelete

Search and add the following components in your design (the belonging library and package is mentioned in brackets) :

COMPONENT LIBRARY DEVICE PACKAGE
555 timer st-microelectronics NE555 DIL-08
Resistor rcl R-EU 0204/7
Polarized capacitor rcl CPOL-EU2,5-6E E2,5-6E
Capacitor rcl C-EUC1206 C1206
Screew terminal con-ptr500 AK500/2 AK500/2
5mm LED led LED5MM LED5MM
VCC supply symbol supply2 VCC
GND supply symbol supply2 GND
Note that, even if VCC and GND are provided for convience and are not real components, they can be found in the libraries. Add and place your components in order to get the following arrangement:

ComponentsPlacement

Adding connections

The electrical connections have to be drawn with the NET tool (or the bus tool for buses). The WIRE tool also draw lines, but it is not dedicated to electrical connections, it belongs to the drawing tools (text, circle, arcs…).

net

Once the NET tool is selected, add a connection by clicking on the first pin to connect. Place the cursor on the second pin or junction, and right click without moving the mouse : the wire bend style will automaticaly change. It can also be done by selecting one of the wire bend style icon:

WireBendStyle

Place the connection according to the following schematic. This is a very simple NE555-based LED blinker:

SchematicWiring

Component name and value

The following icon (NAME) allows the user to change a component name :

Name

In the same way, the VALUE icon allows the user to add or modify the component value (when applicable):

Value

Rename and set values of each symbol according to the following illustration:

Rename

Check errors

Once your schematic is finished, it is safe to use the ERC (Electric Rules Check) tool. It can detect many mistakes in the design (wrong connections, non compatible junctions …)

ERC.

A new window pops up, and displays four warnings:

ErrorList

The first one says that the pin 8 of the NE555 is called VCC+ and is connected to VCC. The three others say that the frame, the LED and the screw terminal don’t have values. As none of this four warning is an error, the four errors can be approved. The dialog box should now display zero error, zero warning and four approved:

ErrorApproved

Generating board

When the schematic is finished and checked, the board can be created. Click on the following icon to generate the board and launch the board editor.

GenerateBoard

EAGLE may ask you to confirm the creation of a new board from your schematic, answer yes and the PCB is automatically prepared for routing:

BoardEditor

Click here for the next step

Introduction to EAGLE – Part 3 – Board editor

This article is part of a tutorial dedicated to EAGLE. The reader may consult the other parts of the tutorial by following this link: Introduction to EAGLE
It is here assumed that the reader had studied the part 2 and that the schematic has been processed. The board editor should now look like this illustration:

BoardEditor

Forward and backward annotation

Check that the schematic editor and the board editors are open simultaneously. Save both designs and close the board editor. The schematic editor display the following message : “Forward and backward annotation has been severed !”:

FB_Annotation

A key element is that EAGLE maintains the link between the schematics and the PCB. When a modification is perfomed in the schematic, the PCB is immediatly updated (forward annotation). In the same way when the PCB is modified, the schematic is updated accordingly (backward annotation). It prevents the project from splitting into incompatible parts. The downside is that the designer have to consider it while working.

Workspace

The board editor environment is very similar to the schematic editor (user interface arrangement is almost the same). As it was done for the schematic editor, display a grid of 50 mils in the board editor. Now select the WIRE tool to draw the board outline. Above the working area an horizontal menu bar is displayed. This is the wire properties. Set the layer to 20 (Dimension) and select a width of 10 mils. Note that the unity of the editor is set by the unity of the grid.

WireProperties

Left-click on the origin of the working area (coordinates 0,0), now click at coordinates 1600,1000 and finaly double click anew on the origin (right click at each point while defining the outline changes the wire bend style). The board outline should now be visible in grey:

BoardOutline

It is convinient to remember that the mouse wheel allows you to zoom in and out and the middle button allows you to drag your design to another place (middle button has to be maintained pressed while moving the mouse).

Placement

As for the schematic editor, the MOVE tool is used for moving components. The view displayed in the board editor is a top view of the PCB. Item drawn with the red color are located on the top side (component side) and item drawn in blue are located on the bottom side (copper side). To transfer a component on the other side, use the MIRROR tool. Select the tool, and click close to the origin (white cross) of the component to transfert. Place C2 on the bottom side, and C3 on the top side.

Mirror

As for the schematic editor, when moving a component left-click places the component, right-click perfoms a rotation. While placing the components, it is possible to update the ratsnets (i.e. calculate the shortest airwire for each connection) by clicking on this icon:

Ratsnets

Place the components according to the following arrangement and update the ratsnet.

ComponentArrangement

Routing

Routing consists now in transforming the airwires into routed copper-made tracks. It is done with the help of the tool ROUTE:

Route

To create a new track, select the routing tool and click on the airwire you want to route. The track appears while moving the cursor. Right-click change the wire bend style as for nets in the schematic editor. Double-click ends the operation. By changing the layer above the upper left corner of the working area while routing, it switchs the track from one side to another and automaticaly add a via if necessary. You can save a lot of time using the middle button of the mouse to switch from ont to another layer.
The inverse tranformation (from tracked route to airwire) is not done with the DELETE tool. This action removes the connection. While forward and backward annotation is enable, deleting a connection is not possible from the board editor; it must be done in the schematic editor. To unroute a track, use the RIPUP tool:

Ripup

It is usefull to remember that selecting an airwire with RIPUP converts all adjacent routed wires and vias into airwires, up to the next pad, smd or airwire. Thus, by left-clicking twice on a track it quickly unroutes the connection. Tracks and vias can be moved with the MOVE command. Selecting a wire segment near an end point will move the end point of the track. Selecting the wire in the middle will move it in parallel. Note that to move components there origins have to be displayed (layer 23 (tOrigins) and 24 (bOrigins) for components respectively on top and bottom layers).
With the SPLIT command you add a bend in a wire. It is usefull to push or modify an existing track:

Split

Route the board according to the following illustration (track width is 50 mils):

Routed

Modifying the board

The CHANGE tool allows you to change any property of your design. When selecting the CHANGE tool, a contextual menu appears with the list of properties:

Change

Select WIDTH > 10 and click on any track of your design. The track width is modified. You can reverse the action with the UNDO command (Ctrl-Z). Note that modifying component names or values can’t be done with the CHANGE tool, it must necessary be done with the NAME and VALUE commands as in the schematic editor. Set the value of resistor R3 from 680 to 470 and check in the schematic that the value has been back annotated:

BackAnnotate

Perform the inverse action from the schematic editor and check that the board has been updated. Note that when you apply and action to an object that is too close from another, the software is enable to guess which is concern. In this situation, a single object is highlighted and a right-click allows to switch to the another potentially concerned object. Left-click finally applies the action to the current highlighted object.

Design rule check

Before manufacturing the PCB, it is safe to check the design thanks to the DRC (Design Rule Check). First click on the DRC icon.

DRC

The DRC configuration window appears. The designer can specify its own project design rules. Once the rules are configured, click the CHECK button to start the Design Rule Check. When there is no error, a message is simply display at the bottom of the board editor. If existing errors are found, a window appears:

DRC_Errors

Here two errors are detected. The hole size of the vias is too small according to the design rules. By selecting one of the error, the problem is highlighted in the design:

Error_Hilighted

With the CHANGE command, change the drill diameter of the vias from 23.62205 to 27.55906. Check again your design, you should, at the bottom-left corner of the window, have the message : “DRC: No errors”. Your design is ready for manufacturing.

Click here to return to the main summary

Introduction to EAGLE – Adding mounting holes to a PCB

This article is part of a tutorial dedicated to EAGLE. The reader may consult the other parts of the tutorial by following this link: Introduction to EAGLE

VIA versus HOLE

There is two ways (via or hole) to add a mounting hole in a PCB and the difference between the VIA and the HOLE tools can be confusing.
via hole
A via is composed of a hole and a copper area surounding the hole. But the main différence between vias and holes is the electric connection made between layers by the via. The HOLE tool just place a hole in the design without copper or connection. Depending on what the mounting hole is made for, you may add a VIA or a HOLE. The following capture shows the difference between vias and holes. On the left side of the PCB, holes has been added, and on the right side of the board, two vias has been placed.

Board

As it is illustrated on the following figure, vias are isolated from copper pour:

BoardCopperPour

Hole diameters

Regardless the selected tool, the hole diameter has to be defined. The PCB editor is generaly configured in mils (or inchs) and the fastening specification is generaly provided in millimeters. The following table is a quick references of most used diameters.
[MIL] [MM]
19.68504 mils 0.5 mm
23.62205 mils 0.6 mm
27.55906 mils 0.7 mm
31.49606 mils 0.8 mm
35.43307 mils 0.9 mm
39.37008 mils 1.0 mm
43.30709 mils 1.1 mm
47.24409 mils 1.2 mm
51.1811 mils 1.3 mm
55.11811 mils 1.4 mm
59.05512 mils 1.5 mm
62.99213 mils 1.6 mm
78.74016 mils 2.0 mm
86.61417 mils 2.2 mm
110.23622 mils 2.8 mm
125.98425 mils 3.2 mm

If the value is not listed, check this link : Distance converter.

Click here to return to the main summary

Introduction to EAGLE – Adding copper pour

This article is part of a tutorial dedicated to EAGLE. The reader may consult the other parts of the tutorial by following this link: Introduction to EAGLE

Copper pour

The copper pour outline is drawn with the POLYGON command:

Polygon

Select the POLYGON tool. If the copper pour needs to be attached to a net, you can enter the net name straight after selecting the tool and validate with the Enter key:

AttachNet

It is still possible to modify the connection by right clicking on the edge of the polygon, in the contextual menu, select NAME. In the pop-up window, replace GND by the label of the new connection. This is also useful to check that the connection has been successfully done.
Left-click to draw polygon edges and double click to close the polygon. Once the outline is drawn, it appears in dotted lines:

DottedLine

Click the RATSNETS to calculate the copper pour:

Ratsnets

The board should be updated. When the board is modified, the copper pour is not always recalculated. It is usefull to remember that RATSNETS force the calculation of the copper pour.

CopperPour

Board outline conflict

According to your design check rules, the copper pour may sometime not reach the board outline:

CopperPourOutline

This can be solved by setting the distance between the copper pour and the dimension layer equal to zero. Click on DRC, select tab Distance and set the distance equal to 0:

DistanceCopperPour

Attaching a net

Before attaching a net to the copper pour, it is sometime usefull to unroute the existing tracks already routed. Use the command RIPUP, for example “RIPUP GND”, to unroute all the tracks named GND.
To add or change the copper pour net attachment, select the NAME command and click on the polygon. A window pop up and the user can modify or specify the name of the copper pour. When the name is the same as an existing track (for example GND), an electric connection is automaticaly created between the track and the copper pour. On the following board, the copper pour is connected to the groung:

CopperPour

Remove copper pour

To definitively delete the copper pour, since the polygon is attached to the copper pour, delete the polygon. To temporary remove or hide the copper pour, select the RIPUP tool and click on the polygon. It removes the copper pour while keeping the polygon (dotted lines). Click RATSNETS again to recalculate the copper pour.

Introduction to EAGLE – Understanding layers

This article is part of a tutorial dedicated to EAGLE. The reader may consult the other parts of the tutorial by following this link: Introduction to EAGLE
Each layer in EAGLE is dedicated to a given function. Placing each item in the appropritaed layer is highly recommanded. This article presents each layer and describes it functionality. The famous Arduino MEGA 2560 board is taken as example. Note that the picture is not exactly identical to the PCB, but is quite enough to understand each layer:
ArduinoMega2650Front All

Layer 1 – Top

The first layer contains the top side tracks and the top side copper pour (if used).

Layer_1

Layer 2 to 15 – Route

This is the inner layer tracks (only for multilayer PCB).

Layer 16 – Bottom

This layer contains the bottom side tracks and the bottom side copper pour (if used).

Layer_16

Layer 17 – Pads

This layer contains the through-hole pads.

Layer_17

Layer 18 – Vias

This layer contains the through-hole vias.

Layer_18

Layer 19 – Unrouted

This layer contains the unrouted tracks, i.e. the airwires (rubberbands). Here almost all the board is routed, there is just a few unrouted tracks:

Layer_19

Layer 20 – Dimension

This layer contains the board outlines and circle for holes.

Layer_20

Layer 21 – tPlace

This layer contains the top side silk screen. It usualy contains the component outlines. Care must be taken not to cover any ares that have to be soldered. It is also possible to create additional and rather better­looking silk screen for documentation purposes in layer 51, tDocu. This may indeed cover soldered areas, since it is not output along with the manufacturing data.

Layer_21

Layer 22 – bPlace

This layer contains the bottom side silk screen (see layer 21 for more details).

Layer 23 – tOrigins

This layer contains the top side component origins. It contains the origin cross for each component. Top side components can be moved or modifyed only if this layer is visible.

Layer_23

Layer 24 – bOrigins

This layer contains the bottom side component origins (see layer 22 for more details). Bottom side components can be moves only if this layer is visible.

Layer 25 – tNames

This layer contains the top side service print. It usualy contains the component names and may appear on the PCB as the silk screen.

Layer_25

Layer 26 – bNames

This layer contains the bottom side service print (see layer 25 for more details).

Layer 27 – tValues

This layer contains the top side component value. It usualy contains the component value and appears on the PCB as the silk screen and service print.

Layer_27

Layer 28 – bValues

This layer contains the bottom side component value (see layer 27 for more details).

Layer 29 – tStop

This layer contains the top side solder stop mask (solder mask). This is the nogo area for the green laque. Data is implicitly created for THT and SMD pads, and optionally VIAs (depending on settings).

Layer_29

Layer 30 – bStop

This layer contains the bottom side solder stop mask (see layer 29 for more details).

Layer 31 – tCream

This layer contains the top side solder paste data for SMD, normally used to make stencils for printing the paste to the board before assembly. Data is implicitly created with SMD pads. This area should be a little smaller that the solder stop mask because the green laque shouldn’t overlap solder areas.

Layer_31

Layer 32 – bCream

This layer contains the bottom side solder cream (see layer 31 for more details).

Layer 33 – tFinish

This layer is dedicate to special finishing process (plated gold, silver carbon. It may also be used if some of the pads need immersion gold plating. It is not automaticaly generated and it must be drawn by designer.

Layer 34 – bFinish

This layer contains the bottom side finish data (see layer 33 for more details).

Layer 35 – tGlue

This layer contains the top side glue mask. For wave soldering of SMD parts, they must be glued to the board first. Usually, one small dot in the center of chips, and several dots under IC packages are used. This layer must be drawn by the designer, normally when designing the libraries.

Layer_35

Layer 36 – bGlue

This layer contains the bottom side glue mask (see layer 35 for more details).

Layer 37 – tTest

This layer is the top side test and adjustment. It is dedicated to testpoint for ICT (In Circuit Test).

Layer 38 – bTest

This layer is the bottom side test and adjustment. It is dedicated to testpoint for ICT (In Circuit Test).

Layer 39 – tKeepout

This layer is the top side keepout area for components. Components should not be placed in this area (except for part ower of the area).

Layer_39

Layer 40 – bKeepout

This layer is the bottom side keepout area for components (see layer 39 for more details).

Layer 41 – tRestrict

This layer is the top side keepout area for tracks. Tracks should not be placed in this area.

Layer 42 – bRestrict

This layer is the bottom side keepout area for tracks (see layer 41 for more details).

Layer 43 – vRestrict

This layer is the keepout area for vias.

Layer 44 – Drills

This layer contains the conducting through holes. It is usually used for pads (of through hole components) and vias.

Layer_44

Layer 45 – Holes

This layer contains the non-conducting holes. It is usually used for s used for mounting holes.

Layer_45

Layer 46 – Milling

This layer is dedicated to milling. If the board manufacturer has to mill oblong holes, you have to draw the milling contour of oblong holes in this layer. Any other inner cut­outs in the board are drawn in the same way. Draw the milling contours in this layer. Note that the board outline is not concerned and must be designed in the layer 20 (Dimension).

Layer 47 – Measures

This layer contains the measurement. It is not used during the manufacturing process, it is just display for information.

Layer_47

Layer 48 – Document

This layer contains the general documentation. Had here comments, or any usefull information that help understanding the design of the PDB.

Layer_48

Layer 49 – Reference

This layer contains the reference marks and is typicaly used for placing the fiducial marks. Fiducials are little target registration marks that are printed on PCBs, they are placed on the top copper layer (and bottom if you’re doing 2-layers) and allow the vision system of the pick and place to recognize where the PCB is at. They are not placed on the mask or silk because they are not as precisely aligned to the parts as the copper itself.

Layer_49

Here is a picture from Lady Ada (Adafruit company) that illustrate the automatic localization process of the fiducial marks:

4mmoffset

Layer 51 – tDocu

This layer contains the top side part documentation. Place additional graphical information for the documentation here. This layer is not used to print onto the board itself, but is a supplement to the graphical presentation which might be used for printed documentation. Care must be taken in layer 21, tPlace, not to cover any areas that are to be soldered. A more realistic appearance can be given, however, in the tDocu layer, which is not subject to this limitation.

Layer_51

Layer 52 – bDocu

This layer contains the bottom side part documentation (see layer 51 for more details).

DIY Lithium Battery Charger Shield for Arduino

$
0
0

DIY Lithium Battery Charger Shield for Arduino

6 Comments
intrologo-lithium-battery-charger

In this project, we are building a programmable single/multi cell lithium battery charger shield for Arduino. The shield provides LCD and button interface which let the user set the battery cut-off voltage from 2V to 10V and charge current from 50mA to 1.1A. The charger also provides the ability to monitor the battery status before and during charge.

The charger is based on LT1510 Constant Current/Constant Voltage Battery charger IC and controlled by Arduino UNO. The display on the shield is Nokia 5110 LCD which is very simple to use and still available on the market. There are two different battery connectors available on the shield, a two contact screw terminal block and a right angle 2mm JST-PH connector.

Circuit Design

The schematic of the project is drawn in SoloCapture, the schematic editor of SoloPCB tools. SoloCapture makes the schematic drawing process very easy and fast. You can download SoloPCB tools at Fabstream.com for FREE.

You can download the SoloPCB design files of the project by using the link below.

Please check out this video to see how to import the project libraries, open and synchronize the schematic and PCB files.

schematic-620-lithium-battery-charger

The lithium battery charger circuit is designed as an Arduino Shield. But the battery charger IC on the board can also work without MCU control. R3 and R4 sets the charge cut-off voltage, R2 ,R24 and C5 adjusts the charge current limit. With those passive component configurations, LT1510 can charge the battery and know when to stop. But we want to build a user programmable charger. So we had to take control of these functions. Anyway, when no code is present on Arduino, the charger has default cut-off voltage of 4.2V and maximum charge current of 1.1A.

component-side-lithium-battery-charger

Pulling VC pin of LT1510 to ground stops charging immediately. The pin 5 of Arduino assigned to drive Q2 Mosfet to stop charging when required. The battery voltage is divided by ten over R7 and R8 resistors and read by the A1 analog input. By using these two features, we can read the battery voltage and stop charging when the battery reaches a pre-determined voltage level.

In LT1510 datasheet, in addition to fixed resistor configuration, controlling the charge current by PWM method is also explained. Pin 6 of Arduino has PWM function and it is used for this purpose. Adjusting the PWM duty cycle easily adjusts the charge current. The current flowing to the battery is sensed by ACS712-5A Hall Effect current sensor IC and the sensor output is read by A0 analog input of Arduino. ACS712-5A outputs 0.185mV per 1A in addition to 2.5V. For example when the battery draws 1A, the sensor outputs 2.685V. To read the current more accurately, the internal voltage reference 1.1V is used so 10 bit ADC reading will fit between 0V and 1.1V at 1024 step resolution.

The maximum sensor output difference will be 1.1A x 0.185V = 0.204V resulting an output of 2.704V. By using the LM258 op-amp, we subtracted 2.5V from the sensor output and multiply the result by 5. This maps the sensor output from 0V (@0A) to 1.02 (@1.1A) which fits nicely between the ADC limits of 0V and 1.1V. There is still 0.1V margin left which is meaningful when considering the op-amp offset voltage and current sensor noise and offset.

5110 LCD display uses SPI interface and requires 3.3V power supply. Since the Arduino I/O pins works at 5V, to protect the LCD module, it is recommendedto connect 10K or 1K resistors in series to the signal lines. The LCD module includes backlight LEDs. Those LEDs are driven by Pin 8 over 330R current limiting resistor.

There are four buttons (up, down, left, right) connected to Pin A2-A5 of Arduino. Those pins are set as inputs and the internal pull up resistors are activated. So simply pulling the pins to ground by using the buttons is enough to detect the button activity.

There are two SMD LEDs on the board reserved for any kind of indication. They are connected to Pin 3 and Pin 4. Those pins are set as outputs. Depending on the LED characteristics, current limiting resistors should be connected in series with the LEDs.

PCB Design

The PCB of the project is designed in SoloPCB. SoloPCB is a pack of powerful tools consisting of schematic capture, PCB layout, and integrated autorouting. You can download SoloPCB tools at Fabstream.com for FREE and start using immediately.

You can download the SoloPCB design files of the project by using the link below.

Please check out this video to see how to import the project libraries, open and synchronize the schematic and PCB files.

PCB-lithium-battery-charger

Since this is an Arduino shield, it should have similar dimensions with Arduino UNO. The expansion headers must be properly positioned. The LCD, buttons, LEDs and the battery connectors are placed on the top layer to make the interface usable. All the other components are placed on the bottom layer.

buttons-and-connectors-lithium-battery-charger

LT1510 requires PCB area which is connected to the GND pins to cool down the IC during operation. And there is a recommended PCB layout in its datasheet which maximizes the noise reduction performance.

Part List

parts-lithium-battery-charger

The Bill of Materials of the Lithium Battery Charger shield is given below.

Quantity Part Description Designator
1 LT1510 Constant Current/Constant Voltage Battery Charger SO-16 U1
1 REF03 2.5V Voltage Reference SO8 U2
1 ACS712-5A Hall Effect Based Current Sensor 8-SOIC U3
1 LM258 Low Noise Operational Amplifier SO-8 U4
1 5110 LCD Module LCD1
2 SS14 1A 40V Schottky Rectifier SMA D1 D2
1 1N4148 General Purpose Diode SOD80C D5
3 BSS138 Mosfet SOT-23 Q1 Q2 Q3
1 Red LED 0805 D3
1 Green LED 0805 D4
1 220nF 50V 0805 X7R SMD Ceramic Capacitor C1
5 100nF 50V 0805 X7R SMD Ceramic Capacitor C4 C8 C9 C10 C11
2 1nF 50V 0805 X7R SMD Ceramic Capacitor C6 C7
1 10uF 25V 1206 X7R SMD Ceramic Capacitor C3
1 1uF 25V 1206 X7R SMD Ceramic Capacitor C5
1 22uF 16V Tantalum Capacitor B-Case C2
1 MSS1260-333 330uH Coilcraft Power Inductor L1
3 100R 1% 0805 Resistor R5 R6 R23
3 20K 1% 0805 Resistor R7 R19 R22
2 1K 1% 0805 Resistor R1 R10
1 70.6K 1% 0805 Resistor R4
6 10K 1% 0805 Resistor R11 R12 R13 R14 R20 R21
2 0805 Resistor Value Depends on the LEDs R15 R16
1 3K8 1% 0805 Resistor R24
3 100K 1% 0805 Resistor R3 R17 R18
1 330R 1% 0805 Resistor R9
1 300R 1% 0805 Resistor R2
1 180K 1% 0805 Resistor R8
4 Tact Push Button SMD SW1 SW2 SW3 SW4
1 1×6 2.54mm pitch 15mm height Male Header J2
2 1×8 2.54mm pitch 15mm height Male Header J3 J4
1 1×10 2.54mm pitch 15mm height Male Header J1
1 JST-PH Connector 2 Pin Right Angle J5
1 1×2 5.2mm Pitch Screw Terminal Block J6

Software

Page based design is applied in the project. There are four pages that lets the user enter the charge parameters and monitor the battery status. Adafruit PCD8544 and GFX libraries are used to drive Nokia 5110 LCD.

The first page is the Set Parameters page. On this page the user can enter the battery cut-off voltage and the maximum charge current, go to battery status page, and start charging. Up and down buttons are used to travel between the options and right and left buttons are used to change values or select any option.

set-parameters-page-lithium-battery-charger

The second page is the Battery Status Page. While not charging, the user can enter this page from the Set Parameters page and see the current battery voltage. Pressing the left or the light button make the charger return to the Set Parameters page.

battery-status-page-lithium-battery-charger

The third page shows the charging state of the battery. It shows the voltage and current status of the battery during charge. When right or left button is pressed, the charger stops charging and returns to the Set Parameters page.

charging-page-lithium-battery-charger

When the battery voltage reaches to the set voltage, the charger stops charging and displays the Charge Complete page.To exit, pressing the left or the right button is required.

charge-complete-page-lithium-battery-charger

The charger keeps the last used parameters in the internal EEPROM. When charging process starts, the parameters are saved. At startup the charger reads the values from the EEPROM so the user don’t have to enter the values each time.

To read the battery voltage and the charge current, A0 and A1 pins are used as analog inputs. The details of the ADC steps are explained in the code. To change the charge current, PWM function is used via pin 6. Adjusting the duty cycle changes the charge current. A lookup table including the current vs. duty cycle is constructed manually and used. Since we can read the current, it is also possible to change the duty cycle dynamically.

At startup, the charger displays a bitmap logo. It was a bit challenging to display this bitmap so we wanted to explain the process for 5110 LCD users who want to use this feature.

How to Create and Use Bitmap Images on 5110 LCD

This example is prepared to be used with Adafruit PCD8544 and GFX Arduino libraries.

First of all, we need to create the image that will be displayed on the 5110 LCD. There are lots of graphics editors that can be used for this purpose but we will use the most basic one, MS Paint.

  1. Start paint and create a new file.
  2. Select “Resize” on the tool ribbon.
  3. Choose “Pixels” and uncheck “Maintain aspect ratio”
  4.  We will create a full screen logo so enter the dimensions horizontal: 88 and vertical: 48. Actually the width of the screen is 84px but we experienced that the width should be a multiple of 8. The excess four bits in each line won’t be displayed.
  5. Save the image in “Monochrome Bitmap” type.

Now the blank image is ready for the design. The last four vertical columns on the image will be lost so don’t include them. You can see the image created for the charger project below.

logo-page-lithium-battery-charger

To display this image on the LCD, we need to convert it to a bit matrix. LCD Assistant is a useful tool which will help us at this point.

  1. Open LCD Assistant and select “Load Image” from the ”File” menu.
  2. Choose the image you created.
  3. On the settings tab, choose “Horizontal” as byte orientation. The size of the picture will be automatically detected.
  4. Leave the other fields as they are.
  5. From the “File” menu, choose “Save Output” and type the file name such as Logo.txt.
  6. Open the .txt file and replace “const unsigned char” with “static const unsigned char PROGMEM”

The image bit matrix is ready to use in the Arduino sketch. Paste it before the “void Setup()” section. To display image on the screen, you can use the following code;

display.clearDisplay();

display.drawBitmap(0, 0,  logo, 84, 48, 1);

display.display();

Arduino Code


SIM900 GPRS/GSM Shield

$
0
0

SIM900 GPRS/GSM Shield

Introduction

The SIM900 GSM/GPRS Shield provides you a way to use the GSM cell phone network to receive data from a remote location. The shield allows you to achieve this via any of the three methods:

  • Short Message Service
  • Audio
  • GPRS Service

The GPRS Shield is compatible with all boards which have the same form factor (and pinout) as a standard Arduino Board. The GPRS Shield is configured and controlled via its UART using simple AT commands. Based on the SIM900 module from SIMCOM, the GPRS Shield is like a cell phone. Besides the communications features, the GPRS Shield has 12 GPIOs, 2 PWMs and an ADC.

N95DG WITHOUT PACKAGED FRONT2.jpg

N95DG WITHOUT PACKAGED BACK.jpg

Features

  • Based on SIMCom‘s SIM900 Module
  • Quad-Band 850 / 900/ 1800 / 1900 MHz – would work on GSM networks in all countries across the world.
  • Control via AT commands – Standard Commands: GSM 07.07 & 07.05 | Enhanced Commands: SIMCOM AT Commands.
  • Short Message Service – so that you can send small amounts of data over the network (ASCII or raw hexadecimal).
  • Embedded TCP/UDP stack – allows you to upload data to a web server.
  • Speaker and Headphone jacks – so that you can send DTMF signals or play recording like an answering machine.
  • SIM Card holder and GSM Antenna – present onboard.
  • 12 GPIOs, 2 PWMs and an ADC (all 2.8 volt logic) – to augment your Arduino.
  • Low power consumption – 1.5mA(sleep mode)
  • Industrial Temperature Range – -40°C to +85 °C

Application Ideas

  • M2M (Machine 2 Machine) Applicatoions – To transfer control data using SMS or GPRS between two machines located at two different factories.
  • Remote control of appliances – Send SMS while you are at your office to turn on or off your washing machine at home.
  • Remote Weather station or a Wireless Sensor Network : Create a sensor node capable of transferring sensor data (like from a weather station – temperature, humidity etc.) to a web server (like pachube.com).
  • Interactive Voice Response System – Couple the GPRS Shield with an MP3 Decoder and DTMF Decoder (besides an Arduino) to create an Interactive Vocice Response System (IVRS).
  • Vehicle Tracking System – Couple the GPRS Shield with an Arduino and GPS module and install it in your car and publish your location live on the internet. Can be used as a automotive burglar alarm.

Cautions

  • Make sure your SIM card is unlocked.
  • The product is provided as is without an insulating enclosure. Please observe ESD precautions specially in dry (low humidity) weather.
  • The factory default setting for the GPRS Shield UART is 19200 bps 8-N-1. (Can be changed using AT commands).

Specifications

Item Min Typical Max Unit
Voltage 4.8 5.0 5.2 VDC
Current / 50 450 mA
Dimension(with antenna) 110x58x19 mm
Net Weight 76±2 g

Interface Function

Power select – select the power supply for GPRS shield(external power or 5v of arduino)
Power jack – connected to external 4.8~5VDC power supply
Antenna interface – connected to external antenna
Serial port select – select either software serial port or hareware serial port to be connected to GPRS Shield
Hardware Serial – D0/D1 of Arduino/Seeeduino
Software serial – D7/D8 of Arduino/Seeeduino only
Status LED – tell whether the power of SIM900 is on
Net light – tell the status about SIM900 linking to the net
UART of SIM900 – UART pins breakout of SIM900
Microphone – to answer the phone call
Speaker – to answer the phone call
GPIO,PWM and ADC of SIM900 – GPIO,PWM and ADC pins breakout of SIM900
Power key – power up and down for SIM900

Pins usage on Arduino

D0 – Unused if you select software serial port to communicate with GPRS Shield
D1 – Unused if you select software serial port to communicate with GPRS Shield
D2 – Unused
D3 – Unused
D4 – Unused
D5 – Unused
D6 – Unused
D7 – Used if you select software serial port to communicate with GPRS Shield
D8 – Used if you select software serial port to communicate with GPRS Shield
D9 – Used for software control the power up or down of the SIM900
D10 – Unused
D11 – Unused
D12 – Unused
D13 – Unused
D14(A0) – Unused
D15(A1) – Unused
D16(A2) – Unused
D17(A3) – Unused
D18(A4) – Unused
D19(A5) – Unused
Note: A4 and A5 are connected to the I2C pins on the SIM900. The SIM900 however cannot be accessed via the I2C .

A Simple Source Code Example

The demo code below is for the Arduino to send SMS message/dial a voice call/submit a http request to a website and upload datas to the pachube. It has been tested on Arduino Duemilanove but will work on any compatible variant, plesse note that this sketch uses the sorfware UART of ATmega328P. please follow the following steps for running this sketch.

  • With the GPRS Shield removed, download this sketch into your Arduino.
  • Disconnect the Xduino from USB port to remove power source.
  • Set the Serial Port jumpers on the GPRS Shield in SWserial position, to use the Soft Serial port of Arduino.
  • Connect the antenna to the GPRS Shield and insert the SIM Card.
  • Mount the GPRS Shield on Arduino.
  • Connect the Arduino to the computer by USB, and fire up your favorite serial terminal software on computer, choose the COM port for Arduino, set it to operate at 19200 8-N-1.
  • Type command in the terminal to execute different function, threr are 4 functions in the demo:
    • If you input ‘t’, the demo will send a SMS message to another cellphone which you set(you need set the number in the code);
    • If you input ‘d’, the program will dial a call to the other cellphone that you set(it is also need you set in the code );
    • If you input ‘h’, it will submit a http request to a web that you want to access(it need you set the web adress in the code), it will return a string from the website if it goes correctly;
    • If you input ‘s’, it will upload the datas to the pachube(for detail you can refer to the explanation in the code). I strongly recommend you input ‘h’ before input ‘s’, because uploading data to the pachube need do some setting, after execute the function of submit a http request, the setting will be set.
  • If the program returns error in the terminal after you typed the command, don’t worry, just try input the command again.

Note:

(1) The GPRS/GSM shield need external power supply to guarantee reliable operations.

(2) After attaching the shield to Arduino board and adding power supply, you need press the power button on the shield for about 2 seconds to turn on the shield.

/*Note: this code is a demo for how to using gprs shield to send sms message, dial a voice call and
  send a http request to the website, upload data to pachube.com by TCP connection,
 
  The microcontrollers Digital Pin 7 and hence allow unhindered
  communication with GPRS Shield using SoftSerial Library.
  IDE: Arduino 1.0 or later
  Replace the following items in the code:
  1.Phone number, don't forget add the country code
  2.Replace the Access Point Name
  3. Replace the Pachube API Key with your personal ones assigned
  to your account at cosm.com
  */
 
 
#include <SoftwareSerial.h>
#include <String.h>
 
SoftwareSerial mySerial(7, 8);
 
void setup()
{
  mySerial.begin(19200);               // the GPRS baud rate   
  Serial.begin(19200);    // the GPRS baud rate 
  delay(500);
}
 
void loop()
{
  //after start up the program, you can using terminal to connect the serial of gprs shield,
  //if you input 't' in the terminal, the program will execute SendTextMessage(), it will show how to send a sms message,
  //if input 'd' in the terminal, it will execute DialVoiceCall(), etc.
 
  if (Serial.available())
    switch(Serial.read())
   {
     case 't':
       SendTextMessage();
       break;
     case 'd':
       DialVoiceCall();
       break;
     case 'h':
       SubmitHttpRequest();
       break;
     case 's':
       Send2Pachube();
       break;
   }
  if (mySerial.available())
    Serial.write(mySerial.read());
}
 
///SendTextMessage()
///this function is to send a sms message
void SendTextMessage()
{
  mySerial.print("AT+CMGF=1\r");    //Because we want to send the SMS in text mode
  delay(100);
  mySerial.println("AT + CMGS = \"+86138xxxxx615\"");//send sms message, be careful need to add a country code before the cellphone number
  delay(100);
  mySerial.println("A test message!");//the content of the message
  delay(100);
  mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
  delay(100);
  mySerial.println();
}
 
///DialVoiceCall
///this function is to dial a voice call
void DialVoiceCall()
{
  mySerial.println("ATD + +86138xxxxx615;");//dial the number
  delay(100);
  mySerial.println();
}
 
///SubmitHttpRequest()
///this function is submit a http request
///attention:the time of delay is very important, it must be set enough 
void SubmitHttpRequest()
{
  mySerial.println("AT+CSQ");
  delay(100);
 
  ShowSerialData();// this code is to show the data from gprs shield, in order to easily see the process of how the gprs shield submit a http request, and the following is for this purpose too.
 
  mySerial.println("AT+CGATT?");
  delay(100);
 
  ShowSerialData();
 
  mySerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR, the connection type is using gprs
  delay(1000);
 
  ShowSerialData();
 
  mySerial.println("AT+SAPBR=3,1,\"APN\",\"CMNET\"");//setting the APN, the second need you fill in your local apn server
  delay(4000);
 
  ShowSerialData();
 
  mySerial.println("AT+SAPBR=1,1");//setting the SAPBR, for detail you can refer to the AT command mamual
  delay(2000);
 
  ShowSerialData();
 
  mySerial.println("AT+HTTPINIT"); //init the HTTP request
 
  delay(2000);
  ShowSerialData();
 
  mySerial.println("AT+HTTPPARA=\"URL\",\"www.google.com.hk\"");// setting the httppara, the second parameter is the website you want to access
  delay(1000);
 
  ShowSerialData();
 
  mySerial.println("AT+HTTPACTION=0");//submit the request 
  delay(10000);//the delay is very important, the delay time is base on the return from the website, if the return datas are very large, the time required longer.
  //while(!mySerial.available());
 
  ShowSerialData();
 
  mySerial.println("AT+HTTPREAD");// read the data from the website you access
  delay(300);
 
  ShowSerialData();
 
  mySerial.println("");
  delay(100);
}
 
///send2Pachube()///
///this function is to send the sensor data to the pachube, you can see the new value in the pachube after execute this function///
void Send2Pachube()
{
  mySerial.println("AT+CGATT?");
  delay(1000);
 
  ShowSerialData();
 
  mySerial.println("AT+CSTT=\"CMNET\"");//start task and setting the APN,
  delay(1000);
 
  ShowSerialData();
 
  mySerial.println("AT+CIICR");//bring up wireless connection
  delay(3000);
 
  ShowSerialData();
 
  mySerial.println("AT+CIFSR");//get local IP adress
  delay(2000);
 
  ShowSerialData();
 
  mySerial.println("AT+CIPSPRT=0");
  delay(3000);
 
  ShowSerialData();
 
  mySerial.println("AT+CIPSTART=\"tcp\",\"api.cosm.com\",\"8081\"");//start up the connection
  delay(2000);
 
  ShowSerialData();
 
  mySerial.println("AT+CIPSEND");//begin send data to remote server
  delay(4000);
  ShowSerialData();
  String humidity = "1031";//these 4 line code are imitate the real sensor data, because the demo did't add other sensor, so using 4 string variable to replace.
  String moisture = "1242";//you can replace these four variable to the real sensor data in your project
  String temperature = "30";//
  String barometer = "60.56";//
  mySerial.print("{\"method\": \"put\",\"resource\": \"/feeds/42742/\",\"params\"");//here is the feed you apply from pachube
  delay(500);
  ShowSerialData();
  mySerial.print(": {},\"headers\": {\"X-PachubeApiKey\":");//in here, you should replace your pachubeapikey
  delay(500);
  ShowSerialData();
  mySerial.print(" \"_cXwr5LE8qW4a296O-cDwOUvfddFer5pGmaRigPsiO0");//pachubeapikey
  delay(500);
  ShowSerialData();
  mySerial.print("jEB9OjK-W6vej56j9ItaSlIac-hgbQjxExuveD95yc8BttXc");//pachubeapikey
  delay(500);
  ShowSerialData();
  mySerial.print("Z7_seZqLVjeCOmNbEXUva45t6FL8AxOcuNSsQS\"},\"body\":");
  delay(500);
  ShowSerialData();
  mySerial.print(" {\"version\": \"1.0.0\",\"datastreams\": ");
  delay(500);
  ShowSerialData();
  mySerial.println("[{\"id\": \"01\",\"current_value\": \"" + barometer + "\"},");
  delay(500);
  ShowSerialData();
  mySerial.println("{\"id\": \"02\",\"current_value\": \"" + humidity + "\"},");
  delay(500);
  ShowSerialData();
  mySerial.println("{\"id\": \"03\",\"current_value\": \"" + moisture + "\"},");
  delay(500);
  ShowSerialData();
  mySerial.println("{\"id\": \"04\",\"current_value\": \"" + temperature + "\"}]},\"token\": \"lee\"}");
 
 
  delay(500);
  ShowSerialData();
 
  mySerial.println((char)26);//sending
  delay(5000);//waitting for reply, important! the time is base on the condition of internet 
  mySerial.println();
 
  ShowSerialData();
 
  mySerial.println("AT+CIPCLOSE");//close the connection
  delay(100);
  ShowSerialData();
}
 
void ShowSerialData()
{
  while(mySerial.available()!=0)
    Serial.write(mySerial.read());
}

AT Command Tester Application

AT Command Tester is a free online tool test AT Commands and other modem functionalities of 2G modules (GPRS/EDGE) , 3G Modules (HSDPA/EVDO) and 4G Modules (LTE).AT Command Tester tool connects to the modem port of the device and can test various modem functions such as getting device information, gprs data call, voice call,http access, checking signal condition, network registration, SMS functions, SIM access, phonebook functions etc.

In the ‘Port Configuration’ section of the tool, users can search for available ports using the ‘Find Ports’ button. Then using the ‘Connect’ button, users can connect to the modem port of the device.

In the ‘Command Mode’ tab of AT Command Tester, single AT commands can be sent. The drop down list provides AT command description and examples. Users can modify the default command settings.

M2m img1.PNG
Under the ‘Script Mode’ tab, multiple AT commands can be sent at a time. Users can add descriptive comments and save the script on their local machine.

Script mode.PNG

Data Call

To make a data call with the modem, you need to connect to the APN of the carrier network. The carrier APN and other required information are stored in the SIM card and are referred as PDP contexts. Typically multiple PDP contexts are stored in the SIM for different call types. With the AT Command Tester you can edit/add/delete PDP contexts in a easy to use user interface.

Datacall.PNG

Typical call setup sequence,

AT+CGDCONT?

+CGDCONT: 1,”IP”,”epc.tmobile.com”,”0.0.0.0″,0,0
+CGDCONT: 2,”IP”,”test5″,”0.0.0.0″,0,0
+CGDCONT: 3,”IP”,””,”0.0.0.0″,0,0

OK
Checking registration status…

AT+CREG?

+CREG: 0,1

OK
The device is registered in home network.

Checking if device is already connected…

AT+CGACT?

+CGACT: 1,0
+CGACT: 2,0
+CGACT: 3,0

OK
AT+CMEE=1

OK
Attaching to network…
AT+CGATT=1

OK

Connecting…

AT+CGACT=1, 1

OK
Connect Sucessful
SMS

The SMS tab of the ‘AT Command Tester’ tool provides the interfaces to send SMS messages. You can also list/view/delete SMS messages stored on the SIM.

Sms.PNG
General sequence for sending SMS message,

Checking registration status…

AT+CREG?

+CREG: 0,1

OK
The device is registered in home network.

AT+CMGS=”858XXXXXXX”

> Test Message with AT Command Tester�

+CMGS: 19

OK
SMS Send successful

Network Selection – This tab allows the user to manually select available networks. Modems are typically set for automatic network selection. ‘Find Networks’ button will command the modem to scan for available networks.

Network selection.PNG

AT+COPS command will initiate network scan in the modem,

Finding Networks. Please wait..

AT+COPS=?

+COPS: (2,”T-Mobile”,”T-Mobile”,”310260″),(1,”AT&T”,”AT&T”,”310410″),,(0,1,4),(0,1,2)

OK
Networks found

Phonebook

With the ‘Phone Book’ tab, you can add/delete/read phone book entries stored on the SIM,

Phone book.PNG

Getting phonebook entries..

AT+CPBR=1,99

+CPBR: 1,”*233″,129,”Refill Now”

+CPBR: 2,”#999#”,255,”Check Balance”

+CPBR: 3,”8878878878″,129,”Test”

OK

SIM900 HTTP

With the ‘HTTP’ tab, you can read the bearer profiles and test HTTP GET and HTTP POST,

Http.PNG

Getting Bearer profiles..

AT+SAPBR=4,1

+SAPBR:
CONTYPE: GPRS
APN:
PHONENUM:
USER:
PWD:
RATE: 2

OK
AT+SAPBR=4,2

+SAPBR:
CONTYPE: GPRS
APN:
PHONENUM:
USER:
PWD:
RATE: 2

OK
AT+SAPBR=4,3

+SAPBR:
CONTYPE: GPRS
APN:
PHONENUM:
USER:
PWD:
RATE: 2

OK
Checking registration status…

AT+CREG?

+CREG: 0,1

OK
The device is registered in home network.

Querying bearer 1 .

AT+SAPBR=2,1

+SAPBR: 1,1,”162.184.222.162″

OK
Bearer 1 is Connected.IP address is “162.184.222.162”

Bearer 1 is Connected.

Initializing HTTP service…

AT+HTTPINIT

OK
Error initializing HTTP service.

Setting up HTTP parameters..

AT+HTTPPARA=”URL”,”http://www.m2msupport.net/m2msupport/http_get_test.php

OK
AT+HTTPPARA=”CID”,1[[|]]

OK
AT+HTTPACTION=0

OK

HTTP GET is sucessful

AT+HTTPREAD

+HTTPREAD:58
Sucessful HTTP GET test. Data received from m2msupport.net
OK
Terminating HTTP session..

AT+HTTPTERM

OK

SIM900 FTP

FTP Get and Put with SIM900 module can be tested as shown below,

Ftp.PNG

Checking registration status…

AT+CREG?

+CREG: 0,1

OK
The device is registered in home network.

Querying bearer 1 .

AT+SAPBR=2,1

+SAPBR: 1,1,”162.184.222.162″

OK
Bearer 1 is Connected.IP address is “162.184.222.162”

Bearer 1 is Connected.

Setting up FTP parameters..

AT+FTPCID=1

OK
AT+FTPSERV=”ftp.m2msupport.net”

OK
AT+FTPUN=”xxxxxx”

OK
AT+FTPPW=”xxxxxxx”

OK
AT+FTPGETNAME=”ftptest.txt”

OK
AT+FTPGETPATH=”/www/m2msupport/”

OK
AT+FTPGET=1

OK
+FTPGET:1,1
FTP session sucessfully started

AT+FTPGET=2,1024

+FTPGET:2,784
2-11-16 10:53:34.769 ———————————————–
eclipse.buildId=M20120914-1800
java.version=1.6.0_16
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US
Framework arguments: -product org.eclipse.epp.package.java.product
Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.m2e.logback.appender 4 0 2012-11-16 12:11:54.493
!MESSAGE Unable to update index for central|http://repo.maven.apache.org/maven2: C:\Users\sgobi\.m2\repository\.cache\m2e\1.2.0\26522e0d83a422eed93329ece7565cfc\nexus-maven-repository-index.zip (The system cannot find the file specified)

!ENTRY org.eclipse.jdt.ui 4 10001 2012-11-16 13:21:21.138
!MESSAGE Internal Error
!STACK 1
OK
AT+FTPGET=2,1024

+FTPGET:2,0

OK
FTP data transfer is complete
+FTPGET:1,0
FTP session end

How to buy

Here to buy SIM900 GPRS/GSM Shield on store

FAQ

Resources


GPRS Camera Project

$
0
0

GPRS Camera Project

About:
In short, this was a project I started working on out of necessity when vandals damaged a family member’s summer cabin. The crux of the project is a webcam of decent resolution (in this case 640×480) which can be located in a region with no WiFi, no internet connection, and no electricity. There are existing products on the market which satisfy these requirements, but they tend to be specialized (ie most shops don’t stock them) and expensive.

And so was born this project, in which a cheap LinkSprite camera is paired with an inexpensive solar powered Arduino controller and a GPRS interface.

Parts List:

PHASE 1

The first step in this project is to confirm that the camera and the arduino board can interface properly, and pass the image file on to a processing program running on the PC through its serial port.

Arduino Code:

Note: In this code, the LinkSprite camera is connected to pins 4 (RX) and 5 (TX), and the libraries used are available here. It is a modification of the example code given at that website. I provide the rough code here not just because it is useful, but because during this phase of development I had literally dozens of engineers and techies claim that an Arduino was too weak to ever transmit photos to a computer.

#include "JPEGCamera.h"
#include "NewSoftSerial.h"

//Create an instance of the camera
JPEGCamera camera;

const int buttonPin = 7;
const int ledPin = 13;

//Count is used to store the number of characters in the response string.
unsigned int count=0;
//Size will be set to the size of the jpeg image.
int size=0;
//This will keep track of the data address being read from the camera
int address=0;
//eof is a flag for the sketch to determine when the end of a file is detected
//while reading the file data from the camera.
int eof=0;

void setup(){
  camera.begin();
  Serial.begin(19200);
  pinMode(ledPin,OUTPUT);
  
  //Reset the camera
  count=camera.reset(response);
  delay(3000);
  
   //Take a picture
   count=camera.takePicture(response);
    
   //Get the size of the picture
   count = camera.getSize(response, &size);

  while(address<size){            <span="">//Read the data starting at the current address.
        count=camera.readData(response, address);
        //Store all of the data that we read to the SD card
        for(int i=0; i<count; i++){=""             <span="">//Check the response for the eof indicator (0xFF, 0xD9). If we find it, set the eof flag
            if((response[i] == (char)0xD9) && (response[i-1]==(char)0xFF))eof=1;
            //Save the data to the SD card
            Serial.print(response[i]);
            digitalWrite(ledPin,HIGH);
            //If we found the eof character, get out of this loop and stop reading data
            if(eof==1)break;
        }
        //Increment the current address by the number of bytes we read
        address+=count;
        digitalWrite(ledPin,LOW);
        //Make sure we stop reading data if the eof flag is set.
        if(eof==1)break;
  }
  return;
}

void loop(){
}

Processing Code:

import processing.serial.*;
   
 Serial myPort;  
 OutputStream output;  
   
   
 void setup() {
   
  size(320, 240);
   
  //println( Serial.list() );
  myPort = new Serial( this, Serial.list()[5], 19200);
  myPort.clear();  
   
  output = createOutput("pic.jpg");
 }  
   
   
 void draw() {
   
  try {
   while ( myPort.available () > 0 ) {
    output.write(myPort.read());  
    print("*");
   }  
  }   
  catch (IOException e) {  
   e.printStackTrace();  
  }  
 }  
   
   
 void keyPressed() {
   
  try {
   output.flush(); // Writes the remaining data to the file
   output.close(); // Finishes the file
  }   
   
  catch (IOException e) {  
   e.printStackTrace();  
  }  
 }    

PHASE 2

The second step in this project is to confirm that the Arduino board can send e-mail messages through the GPRS cell phone network. This requires an activated SIM card, a valid cell phone service (some providers require a data plan, others will work with a basic voice & text plan), and of course a GPRS shield for the Arduino. I am using the Seedstudio version, but others that use the AT protocals should work with this code as well.

Arduino code:

Note: In the following code, the APN, username, and password are specific to each service provider. However these can usually be found with a quick online search. Also, in my own testing it appears that the sender e-mail address needs to be a valid address but no password is required for it. The sender e-mail isn’t really important for this project since the code sends an e-mail to the user directly, but is included as the e-mail protocols require it.  The recipient address is the destination for the final photos and data. It should also be noted that the delays are the values that worked for me, but may need to be adjusted to give the server sufficient time to respond to each command.

#include <SoftwareSerial.h>
#include <String.h>


SoftwareSerial mySerial(7, 8);
 
void setup()
{
  mySerial.begin(19200);               // the GPRS baud rate
  Serial.begin(19200);    // the GPRS baud rate
  delay(500);
}
 
void loop()
{
  if (Serial.available())
    switch(Serial.read())
   {
      case 'e':
       SendEmail();
       break;
   } 
  if (mySerial.available())
    Serial.write(mySerial.read());
}
 
///Send EMail

void SendEmail()
{

  mySerial.println("AT+CIPSHUT");
  delay(100);
  mySerial.println("AT+CSTT=\"APN\",\"username\",\"password\"\r");
  delay(2200);
  ShowSerialData();
  mySerial.println("AT+CIPSHUT");
  delay(200);
  mySerial.println("AT+CIPSTART=\"TCP\",\"gprs.provider.com\",25");
  delay(2500);
   ShowSerialData();
  mySerial.println("AT+CIPSEND");
  delay(400);
  mySerial.println("HELO gprs.provider.com");
  delay(400);
     ShowSerialData();
  mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
  delay(400);
  mySerial.println("AT+CIPSEND");
  delay(400);
  mySerial.println("MAIL From: address@server.com");
  delay(400);
  mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
  delay(400);
     ShowSerialData();
  mySerial.println("AT+CIPSEND");
  delay(200);
  mySerial.println("RCPT To: address@server.com");
  delay(400);
  mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
  delay(400);
       ShowSerialData();
  mySerial.println("AT+CIPSEND");
  delay(300);
  mySerial.println("DATA");
  delay(400);
  mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
  delay(400);
  ShowSerialData();
  mySerial.println("AT+CIPSEND");
  delay(200);
  mySerial.println("From: \"SENDER\"<address@server.com>");
  delay(200);
    mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
  delay(400);
  ShowSerialData();
    mySerial.println("AT+CIPSEND");
  delay(200);
  mySerial.println("To: \"RECIPIENT\"<address@server.com>");
  delay(100);
    mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
  delay(400);
  ShowSerialData();
    mySerial.println("AT+CIPSEND");
  delay(200);
  mySerial.println("Subject: EMail Test");
  delay(200);
  mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
  delay(400);
  ShowSerialData();
    mySerial.println("AT+CIPSEND");
  delay(200);
  mySerial.println("This is a test of the cell phone email system");
  delay(200);
  ShowSerialData();
  mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
  delay(400);
      mySerial.println("AT+CIPSEND");
  delay(200);
  mySerial.println(".");
  delay(600);
  ShowSerialData();
  mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
  delay(400);
  mySerial.println("AT+CIPSHUT");
  delay(100);
}
 


void ShowSerialData()
{
  while(mySerial.available()!=0)
    Serial.write(mySerial.read());
}

3G + GPS shield over Arduino and Raspberry Pi

$
0
0

3G + GPS shield over Arduino and Raspberry Pi

Difficulty Level: Expert –

https://s7.addthis.com/static/tweet.html#href=https%3A%2F%2Fwww.cooking-hacks.com%2Fdocumentation%2Ftutorials%2F3g-gps-shield-arduino-raspberry-pi-tutorial%2F%23.Vn8VQGqJUWs.twitter&dr=https%3A%2F%2Fwww.cooking-hacks.com%2F3g-gprs-shield-for-arduino-3g-gps-audio-video-kit&conf=product%3Dtbx-300%26pubid%3Dra-550b04b6022f544d%26data_track_addressbar%3Dfalse&share=url_transforms%3Dshorten%253Dtwitter%25253Dbitly%2523%2540!defrag%253D1%2523%2540!remove%253D0%25253Dsms_ss%252523%252540!1%25253Dat_xt%252523%252540!2%25253Dat_pco%252523%252540!3%25253Dfb_ref%252523%252540!4%25253Dfb_source%23%40!shorteners%3Dbitly%253D%23%40!imp_url%3D1%23%40!url%3Dhttps%253A%252F%252Fwww.cooking-hacks.com%252Fdocumentation%252Ftutorials%252F3g-gps-shield-arduino-raspberry-pi-tutorial%252F%23%40!title%3D3G%2520%252B%2520GPS%2520shield%2520over%2520Arduino%2520and%2520Raspberry%2520Pi%23%40!smd%3Drsi%253D%2523%2540!rxi%253Dundefined%2523%2540!gen%253D0%2523%2540!rsc%253D%2523%2540!dr%253Dhttps%25253A%25252F%25252Fwww.cooking-hacks.com%25252F3g-gprs-shield-for-arduino-3g-gps-audio-video-kit%2523%2540!sta%253DAT-ra-550b04b6022f544d%25252F-%25252F-%25252F567f15402bc13f85%25252F1%23%40!passthrough%3D&tw=url%3Dhttps%253A%252F%252Fwww.cooking-hacks.com%252Fdocumentation%252Ftutorials%252F3g-gps-shield-arduino-raspberry-pi-tutorial%252F%2523.Vn8VQGqJUWs.twitter%23%40!counturl%3Dhttps%253A%252F%252Fwww.cooking-hacks.com%252Fdocumentation%252Ftutorials%252F3g-gps-shield-arduino-raspberry-pi-tutorial%252F%23%40!count%3Dhorizontal%23%40!text%3D%23%40!related%3D%23%40!hashtags%3D%23%40!width%3D110

The 3G shield for Arduino and Raspberry Pi enables the connectivity to high speed WCDMA and HSPA cellular networks in order to make possible the creation of the next level of worldwide interactivity projects inside the new “Internet of Things” era.

The module counts also with an internal GPS what enables the location of the device outdoors and indoors combining standard NMEA frames with mobile cell ID triangulation using both assisted-mobile (A-GPS) and mobile-based (S-GPS) modes.

Other interesting accessories which can be connected to the module are a 2MP high resolution camera (1600 x 1200) UXGA which enables take incredible photos and videos, an audio kit including microphone , speaker , hands free and headphones sets and a SD socket to save directly all the data coming from the 3G network or recorded from the video camera. You can even reproduce audio filesstored in the SD card (like a mp3 player!).

You can also use it as a standard 3G modem at full speed (~7.2Mbps download, ~5.5Mbps upload) just connecting it through its specific mini-USB socket to your laptop (Linux, Windows, MacOS).

The new communicating module is specially oriented to work with Internet servers implementing internally several application layer protocols which make easier to send the information to the cloud. We can make HTTP and HTTPS (secure mode) navigation, downloading and uploading content to a web server. In the same way FTP and FTPS (secure mode) protocols are also available which is really useful when your application requires handling files. You can even send and receive mails directly from Arduino using the SMTP and POP3 clients implemented internally.

With the SD Card socket so you can handle a complete FAT16 file systems and store up to 32GB of information. This specially useful as the 3G module can work at full speed (~7.2Mbps download, ~5.5Mbps upload) when working with the SD files directly without need of Arduino for data or files management.

The GPS module also makes possible perform geolocation services even in indoors as it can work in A-GPS and S-GPS modes, so the location given by the GPS through NMEA sentences is completed with the cell information provided by both the 3G module and external Internet Geoposition Servers which helps you to get the most accurate location in each case.

Features

  • WCDMA and HSPA 3G networks compatibility
  • Internal GPS for Assisted A-GPS and Supported S-GPS modes
  • High Resolution Camera (2MP) for photo and video recordings available
  • Audio Kit including microphone, speaker, hands free and headphones available
  • SD file system up to 32GB
  • Works as a standard 3G modem in Linux/Windows/MacOS (~7.2Mbps download, ~5.5Mbps upload)
  • Talk directly to web servers by HTTP/HTTPS (secure)
  • Upload and download files directly by FTP/FTPS (secure)
  • Send and receive mails by POP3/SMTP
  • Play compressed audio files

NOTE: The Arduino codes of the tutorial have developed to work on Arduino IDE v1.0.1

NOTE: All the code examples in this tutorial developed for Raspberry Pi use the arduPi library. You can see the documentation and download the library here.

Kits and Accessories

Kits

Accesories

NOTE: the accessories (antennas, camera, microphone, speakers, headset, SD) are not included in the basic package. They may be acquired in any of the multi kits or by separate.

NOTE: If you only need to send SMS or use a low bandwidth for data transfer you can use our cheaper GPRS/GSM Quadband SIM900 module for Arduino and Raspberry Pi.

Does make sense a 3G module for a low speed microcontroller device such as Arduino?

Definitively yes.

On the one hand you can use the Arduino UART at full speed ~ 115kbps, so the communication of data will be at the same bandwidth as if you had the Arduino connected directly to the USB directly (obviously with more initial latency). With the GPRS modules available in the market until now the speed limit was established by the GPRS network ~ 20kbps, so now we get 6 times more download performance than before. The upload speed the increment three times from 10kbps (GPRS) to 35kbps (3G).

On the other hand there is a bunch of actions can be made directly from the 3G module without having to go through the Arduino microcontroller. This means you will control all the action from the main program running in Arduino although the data may flow from the 3G module to the SD card or from the video camera to the 3G module without going through the UART avoiding a possible bottle neck and ensuring maximum speed performance given by your 3G carrier (~7.2Mbps download, ~5.5Mbps upload at max). Some of this independent actions include:

  • Uploading and downloading files to HTTP and FTP servers directly from or to the SD
  • Recording and uploading video and photos to the Internet using the video camera connected directly to the module
  • Recording ambient audio and sending to a web server

This files may be also stored in the SD card of the 3G and in order to manage them after.

As well as this, the module offers theoretically also the possibility of performing Video-Calls. We say “theoretically” as the tests performed in Cooking Hacks we got a carrier error, the same we got when trying to make a Video-Call with our Smartphones so, although everything points it is is a carrier problem we can not ensure the Video-Call functionality (if you get please let us know!).

As pointed before the 3G module can also be used as and standalone 3G/GPRS USB modem! It works in Linux, Windows and MacOS, just plug it through its specific USB connector to your laptop and follow the steps located in the current manual.

You can control also the kind of network service and the quality of the signal received (RSSI) from the surrounding cells you are using even change among them: GSM – GPRS – WCDMA – HSPA depending on the coverage of the zone. Get detailed information about the frequency band you are using to connect to the carrier and the quality of the signal.

Article Index

1. FeaturesGo to index

Electrical features

The 3G module used is the SIM5218 from SIMCOM. The power supply of SIM5218 is from a single voltage source of VBAT= 3.4v-4.2v. In some case, the ripple in a transmit burst may cause voltage drops when current consumption rise to typical peaks of 2A. So the power supply must be able to provide sufficient current up to 2A. The maximum rating are VBAT=4,4v and 3A peak. The maximum value of voltage for digital or analogy pins is 2.8v.

Radio features

SIM5218 is a quad-band GSM/GPRS/EDGE and UMTS engine that works on frequencies of GSM 850MHz, EGSM 900 MHz, DCS 1800 MHz, PCS1900 MHz, and WCDMA 2100M/1900M/850M.

Output power:

  • UMTS 850/900/1900/2100: 0.25W
  • GSM850/GSM900: 2W
  • DCS1800/PCS1900: 1W

NOTE: when flight mode is activated RF functions are closed. The mode can be changed by putting the jumper in position (see 3G shield diagram below).

NOTE FOR US USERS: We have tested the new 3G shield with the AT&T network which supports nativelly the GSM and 3G protocolos. With other carriers may also work although we haven’t tried and thus we can not ensure it. For this reason we recommend to use AT&T SIM cards.

Extra features

  • USIM interface: support SIM cards: 3V & 1.8V
  • High speed USB interface for modem
  • Three audio channels include two microphones inputs and three audio outputs.
  • A camera interface is provided in FPC connector and 2mm pitch holes.
  • I2C interface is provided.
  • 8-bit ADC input with an input voltage range between 2.65v and GND
  • 2.8v LDO power output
  • 4 bit microSD card interface
  • 3 modes of GPS (stand alone, S-GPS y A-GPS)
  • FTP and FTPS for managing files
  • TCP and UDP sockets
  • POP3 and SMTP for e-mail

2. HardwareGo to index

3G Shield diagram

Version 2 of the shield:

NOTE: The Arduino/Raspberry Pi jumper MUST be in Arduino position. The Raspberry Pi position should be used only if the shield is connected to a Raspberry Pi. A wrong position of this jumper can damage the 3G shield

Version 1 of the shield:

3G Shield PCB

Version 2 of the shield:

Version 1 of the shield:

3. AntennasGo to index

Connections

SIM5218 has 3 UFL connectors. Two for diversity of 3G mobile carriers and one for GPS antenna. The impedance of the RF interface is 50Ω. It is recommended use just the “main” antenna socket for the mobile connection unless you experience coverage or performance problems. In this case two antennas allowing diversity may be placed.

Also, the module allows to solder the antenna to the pad, or attach it via contact springs.

Antenna availability

We recommend the usage of the following antennas:

4. BandwidthGo to index

3G module connected with Arduino allows downlinks rates over 115200 bauds (~11.5KBps), the maximum UART’s speed and uplinks rates over 30000 bauds (~3KBps). Using the module as 3G USB modem we got speeds of 2Mbps (~222KBps) for downlink and 0.7Mbps (~77KBps) for uplink and. The connection speed may vary depending on the state of the network, the quality of the signal and the carrier.

5. Using 3G module with AT commandsGo to index

Important issues:

  • Use capital letters for AT commands.
  • Send CR (Carriage return) and LF (Line feed) after the AT command.
  • Place the serial communication jumpers in the right position.
  • Use an external power supply and place the power jumpers in the right position. If the shield is powered from the Arduino or Raspberry Pi, the power jumper must be in Arduino 5V position. If the shield is powered from the Vin input (in the shield), the power jumper must be in Vext position.

Important type commands in capital letters and with CR (carriage return) and LF (line feed)!!!

Command Response Description
AT OK If you get OK, the communication with the module is working
AT+CPIN=”****” OK If the SIM card is locked with PIN (**** is the pin number)
AT+COPS? Operator information

NOTE: If your 3G module doesn’t answer to AT commands, maybe it is configured in a different baudrate. The command for change it temporally is AT+IPR. Try differents baudrates (300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800,921600, 3200000,3686400,4000000 ) until you get to communicate. Once you can communicate, you can configure it in the baudrate you want.

Using 3G module with AT commands in Arduino

The first thing we are going to do with the module is to connect the module to a PC directly (using an Arduino as gateway) and check the basic AT commands. In this case, serial communication jumpers have to be set on USB gateway position.

Remember take out the ATmega microcontroller from the Arduino gateway.

Basic configuration:

Connect the shield to the Arduino gateway.

Then connect the SIM card and the USB cable.

Finally plug the USB cable to the computer and open a serial port terminal to communicate via the usb port (e.g: hyperterminal (win), cutecom / gtkterm (linux)).

If you use the Arduino IDE serial monitor for sending AT commands – Be sure that you are sending CR (Carriage return) and LF (Line Feed).

Set the baudrate to 115200 bps and open the serial port, then press the ON button for two seconds. Then if you type AT you’ll get OK, this means that the communication with the module is working fine. Now, with the module working you can check some AT commands to control the module.

NOTE: With some sketches, the buffer of the UART may be small, to increase the length of the buffer you need to change these lines in the file HardwareSerial.h in /arduino-1.0.X/hardware/arduino/avr/cores/arduino/ (or in file HardwareSerial.cpp in /arduino-1.0.X/hardware/arduino/cores/arduino/ depending on the Arduino IDE version)

#if (RAMEND < 1000)
#define SERIAL_TX_BUFFER_SIZE 16
#define SERIAL_RX_BUFFER_SIZE 16
#else
#define SERIAL_TX_BUFFER_SIZE 64
#define SERIAL_RX_BUFFER_SIZE 64
#endif
#endif

to

#if (RAMEND < 1000)
#define SERIAL_TX_BUFFER_SIZE 400
#define SERIAL_RX_BUFFER_SIZE 400
#else
#define SERIAL_TX_BUFFER_SIZE 400
#define SERIAL_RX_BUFFER_SIZE 400
#endif
#endif

Using 3G module with AT commands in Raspberry Pi

The first thing we are going to do with the module is to check the basic AT commands in gateway mode. Using gateway mode, commands can be sent from our Raspberry Pi directly to any serial module. To stablish UART connection with the module you can use several programs as cutecom in Raspbian graphical environment or minicom in a terminal window in order to use it via SSH . For using minicom follow these steps:

    1. Place the Arduino/RPI jumper in the 3G shield to the right, in RPI position.
    2. Place the two Serial com. jumpers in the 3G shield to the left, in Arduino position. These jumpers always have to be in this position, in gateway mode and when you run codes.
    3. We recommend to power externally the shield, but it’s not necessary in all cases.

      If you decide not to use an external power supply you must set the “Vin ext. Jumper” to the left, in “Arduino 5V position” and do not forget to place the switch in the Raspberry connection bridge to the right.

      If you choose to use an external power supply of 5V or 12V you must place it through the Vin pin, (in the shield, it is placed where Arduino has the Vin pin), the “Vin ext. jumper” must be set to the right, in “Vin position”. The power supply must be able to provide sufficient current up to 2A. Besides this, do not forget to place the switch in the Raspberry connection bridge to the left.

      You can check our FAQ about 3G/Sim900/Sim908 here.

    4. Connect the shield to the Raspberry Pi connection bridge and the antennas to the shield. Now press the ON button in the shield, you will see a green LED.

  1. Open a Terminal window on Raspberry Pi, or connect to Raspberry Pi through SSH. In order to enter via SSH change here the IP from your Raspberry Pi. The default user is pi.
    ssh -X pi@192.168.1.X

    Now you will have to type your password. The default password is “raspberry”.

  2. Install minicom (only if you haven’t done it before):
    sudo apt-get install minicom
  3. Open comunication with the module UART, the baudrate is 115200:
    minicom -b 115200 -o -D /dev/ttyAMA0
  4. Then if you type AT you’ll get OK, this means that the communication with the module is working fine. Now, with the module working you can check some AT commands to control the module.
  5. To exit minicom press CTRL+A, then press X and Yes.

6. Using 3G module like a modemGo to index

If you want to use the 3G module such a modem, please refer to the next link:

3G modem tutorial

7. AudioGo to index

Audio features

SIM5218 module provides two analogy inputs for microphone and three analogy outputs for two speakers and headphones. Depending of the selected audio channel (normal, headset and hands-free) a specific input and output are activated. The different channels are selected with the command AT+CSDVC.

Normal channel (AT+CSDVC=1) uses the main microphone and a speaker. Headset channel (AT+CSDVC=2) uses the jack connector. Hand-free channel (AT+CSDVC=3) uses the main microphone and the loudspeaker.

Both microphones don’t need an external power source because they are powered directly by the module. You can use some extra commands in your codes like noise suppression, echo canceller or the gain of the mic amps. Please, refer to the AT command document list at the end of this article for more information.

Audio connectors

Audio connectors are situated at the bottom of the board. The two speakers and the main microphone are connected to board using pin connectors.

3G/GPRS shield for Arduino (3G + GPS) + Audio/Video Kit

Headset connector are situated at the bottom too, between Arduino board and 3G board.

This connector has 4 terminals that correspond with the positive terminal of the microphone, left and rigth headphones and common ground. The order of connections show below.

Originating and receiving voice calls

The code example and the connection diagram shown below are used to originate a voice call and, pushing a button, end that voice call. The button is connected between digital pin 12 an ground. A 10kΩ pull-up resistor is needed at this pin.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

To make a lost call next code is used.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

To receive calls the used code are this and the connection diagram is the same that the used to originate calls. Don’t forget the pull-up resistor on pin 12.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

The channel may be changed during a call. Use the command AT+CSDVC to select the channel that you want.

Recording and playing sound

With the next code we can record a sound, stores it and before play it. You can select the place to store the sound clip: the local storage or a SD card. Once saved the sound can be sent to an FTP or FTPS as you’ll see later.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Also, you can use the 3G module like a mp3 player! First, you must save your music in mp3, amr or qcp format. You can use Audacity (linux) or Mobile Media Converter (Windows or Linux) to do this. Then, save the music in the Audio folder on microSD card. Now, put microSD card into the shield and enjoy the music!

NOTE: You will need to update your firmware to play mp3. The update is available here. Uncompress and run it in a PC with Windows (emulated Windows not supported).

A voice call can be recorded using these same commands too.

Command summary

Command Response Description
AT+CPTONE=** OK Plays a DTMF tone or complex tone on local voice channel device . ** is the number of the tone.
ATD*********; ********* is the number to call.
ATA OK Answer an incoming call.
AT+CHUP OK Cancel voice calls.
AT+CNSM OK Enable/disable noise suppression.
AT+CQCPREC=*,&&& Starts recording sound clips . Answers with the path and the name of the clip. * is the path and &&& is the format.
AT+CQCPPAUSE OK Pauses record sound.
AT+CQCPRESUME OK Resumes record sound.
AT+CQCPSTOP OK Stops record sound.
AT+CCMXPLAY=”*****” OK Plays an audio file . ***** is the name of the file.
AT+CCMXPAUSE OK Pauses playing audio file.
AT+CCMXRESUME OK Resumes playing audio file.
AT+CCMXSTOP OK Stops playing audio file.

8. CameraGo to index

We have modified the 3G Shield to make it work with a better camera. So instead of using the old 0’3MP Camera, now the shield supports a 2MP Camera, improving the resolution from 640 x 480 (VGA) to 1600 x 1200 (UXGA)!

Comparative:

Old Camera New Camera
Resolution 0.3 MP 2 MP
Sensor OV7725 OV2640
Max. resolution 640 x 480 (VGA) 1600 x 1200 (UXGA)
Image area 3984 µm x 2952 µm 3590 µm x 2684 µm
Sensitivity 3800 mV/Lux-sec 0.6 V/Lux-sec
Optical format 1/4″ 1/4″
Power 120 mW 140 mW

Click in the next photos to enlarge (left click):

Old photo

New photo

The new 2MP Camera is included in the Audio / Video 3G Kit. You can also get directly the 2MP Camera here.

NOTE: The new 2MP Camera can be used only in the last version of the 3G Shield. The old 0’3MP camera can not be used in the new version of the 3G Shield.

NOTE: The 2MP resolution of 1600 x 1200 is just for photos. Video recording is performed at 320 x 240 due to module restrictions.

How do I know if my 3G Shield is compatible with the new 2MP Camera?

  • Check your serial ID. The sticker included in the shield tells you the number of batch. The new 2MP Camera is compatible with batches xxxx-0010-xxx and above.

  • Date of Order. For orders starting in June 2014 all the 3G Shields sold are compatible with the new 2MP Camera.

Camera features

This module allows to connect a camera for video recording and taking photos. Once saved the video or image file can be sent to an FTP or FTPS as you’ll see later. The pin diagram shows below:

Pin nº Name Pin nº Name Pin nº Name
1 NC 9 HSYNC 17 PCLK
2 AGND 10 DVDD 18 DATA6
3 SDA 11 DOVDD 19 DATA2
4 AVDD 12 DATA9 20 DATA5
5 SCL 13 MCLK 21 DATA3
6 RESET 14 DATA8 22 DATA4
7 VSYNC 15 AGND 23 DATA1
8 PWDN 16 DATA7 24 DATA0

Mounting the camera

Follow these simple steps to mount the camera into the 3G Arduino board.

The first step is to open the socket. To do this, pull carefully out the sides of the connector.

Inserts the camera with metallic contacts facing up

At the final step, push in the laterals of the connector.

The camera may get hot if continuous usage is performed. Maximum operation temperature is 45ºC.

Video recording

To record video, and take images, you must start the camera in the first step. After you can configure some parameters like resolution, fps, rotation or zoom. The next code allows to record a video file in mp4 format. Remember, if you want to store the video file in a SD card, you must to use AT+FSLOCA command.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Taking photos

Take photos is very easy, here is the example code:

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Video call

The SIM5218 allows video calls, but to carry them out correctly the operator and the network must be able to allow it. The example code is below. Cooking Hacks not ensure that the video call functions correctly.

Please, be sure that your SIM card have activated the videocall feature, with your network operator and with the phone that you want to call, before to test the next sketch.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Command summary

Command Response Description
AT+CCAMS OK Starts camera.
AT+CCAME OK Stops camera.
AT+CCAMSETD=xxx,yyy OK Sets dimension of camera. xxx is the width and yyy is the height.
AT+CCAMSETF=* OK Sets the frames per second. * is the frame rate option.
AT+CCAMRS OK Starts video recording . Also responds with the path and name of the file.
AT+CCAMRP OK Pauses the record.
AT+CCAMRR OK Resumes video record.
AT+CCAMRE OK Stops video record.
AT+CCAMTP OK Takes a picture.
AT+CCAMEP OK Saves a picture taken by last AT+CCAMTP. Also responds with the path and name of the file.
AT+VPMAKE Makes a video call.
AT+VPEND Ends a video call.

9. GPSGo to index

SIM5218 supports both A-GPS and S-GPS and provides three operating modes: mobile-assisted mode, mobile-based mode and standalone mode. A-GPS is include mobile-assisted and mobile-based mode.

In mobile-assisted mode, when a request for position location is issued, available network information is provided to the location server (e.g., Cell-ID) and assistance is requested from the location server. The location server sends the assistance information to the handset. The handset/mobile unit measures the GPS observables and provides the GPS measurements along with available network data (that is appropriate for the given air interface technology) to the location server. The location server then calculates the position location and returns results to the requesting entity.

In mobile-based mode, the assistance data provided by the location server encompasses not only the information required to assist the handset in measuring the satellite signals, but also the information required to calculate the handset’s position. Therefore, rather than provide the GPS measurements and available network data back to the location server, the mobile calculates the location on the handset and passes the result to the requesting entity.

In standalone (autonomous) mode, the handset demodulates the data directly from the GPS satellites. This mode has some reduced cold-start sensitivity, and a longer time to first fix as compared to the assisted modes. However, it requires no server interaction and works out of network coverage.

This combination of GPS measurements and available network information provides:

  • High-sensitivity solution that works in all terrains: indoor, outdoor, urban, and rural
  • High availability that is enabled by using both satellite and network information

Therefore, while network solutions typically perform poorly in rural areas and areas of poor cell geometry/density, and while unassisted, GPS-only solutions typically perform poorly indoors, the SIM5218 GPS solution provides optimal time to fix, accuracy, sensitivity, availability, and reduced network utilization in both of these environments, depending on the given condition.

Stand-alone mode

In this mode, the GPS obtains position, altitude,… with only the signal of the satellites, making it the slowest of the three modes. If you use the AT+CGPSINFO command, the module bring directly latitud, logitude, date, UTC time, altitude and speed. Here is the example code:

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

If you want to get the NMEA sentences, you must to use the command AT+CGPSSWITCH=1 and configure the UART port at 57600 bauds. Supported NMEA sentences include GSV, GGA, RMC, GSA, and VTG.

S-GPS mode

For the S-GPS the module connects to a GPS server and the module calculates the position. Here is the example code:

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

A-GPS mode

For the A-GPS the module connects to a GPS server for calculate the position. Here is the example code:

MS-assisted Server Module
Location server sends aiding data that is valid for the current fix Sending data
Module sends code phases Code phases
Server calculates position Calculate position
MS-based Server Module
Location server sends aiding data that is valid for the current fix Send aiding data
Module calculates Calculate position
Stand alone Server Module
Module demodulates data form GPS satellite Demodulates GPS satellite data
Module calculates position Calculate position

GPS units

The command AT+CGPSINFO returns the GPS info in a string:

+CGPSINFO: [<latitude>],[<N/S>],[<longitude>],[<E/W>],[<date>],[<UTC_time>],[<altitude>],[<speedOG>],[<course>]

Values Format Example
latitude ddmm.mmmmmm

d: degree; m: minute

4140.831527
longitude dddmm.mmmmmm

d: degree; m: minute

00053.173495
date ddmmyy

d: day; m: month; y: year

020812
UTC_time hhmmss.s

h: hour; m: minute; s: seconds

083418.0
altitude meters 257.00
speedOG knots 2
course degrees 0

If UE-assisted mode, when fixed will report indication:

+CAGPSINFO:<latitude>,<longitude>,<altitude>,<date>,<UTC_time>

Values Format Example
latitude Unit is in 10^8 degree 4168050885
longitude Unit is in 10^8 degree 88618039
altitude meters 293
date ddmmyyyy
d: day; m: month; y: year
28092012
UTC_time hhmmss.s
h: hour; m: minute; s: seconds
081611.0

Command summary

Command Response Description
AT+CGSOCKCONT=**,&&& OK ** is the protocol and &&& Access Point Name.
AT+CGPS=*,& OK * sets on (1) or off (0) and & is the GPS mode.
AT+CGPSINFO Gets current position information.
AT+CGPSURL=”***” OK Sets AGPS default server URL . *** is the URL.
AT+CGPSSSL=* OK Select transport security, used certificate (*=1) or not (*=0).
AT+CGPSSWITCH OK Choose the output port for NMEA sentence.

10. SMSGo to index

Sending and receiving SMS

The first code is used to send a SMS, the second one reads the SIM message memory and shows the last SMS.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Command summary

Command Response Description
AT+CMGF= OK Specifies the input and output format of the short messages. 0 for PDU mode and 1 for text mode.
AT+CMGS Sends a message.
AT+CPMS=*** Selects memory storages. *** is the memory type.
AT+CMGR=* Reads a message. * is the number of the message.

11. E-mailsGo to index

Sending an e-mail

To send e-mail a SMTP server is used, so we need an e-mail account. The code example is the next:

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Receiving an e-mail

For read an e-mail from a POP3 server we need an e-mail account. The code example is here:

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Command summary

Command Response Description
AT+CGSOCKCONT=**,&&& OK ** is the protocol and &&& Access Point Name.
AT+SMTPSRV=”*****”,&&& OK Sets SMTP server address and server’s port . ***** is the sever address and &&& is the server’s port.
AT+SMTPAUTH=1,”***”,”&&&” OK Controls SMTP authentication. *** is the user name and &&& is the password.
AT+SMTPFROM=”***”,”&&&” OK Sets sender’s address and nam e. *** is the sender’s address and &&& is the sender’s name.
AT+SMTPRCPT=x,”***”,”&&&” OK Sets recipient address/name and kind . x is the kind (TO/CC/BCC), *** is the recipient address and &&& is the recipient name.
AT+SMTPSUB=”****” OK Sets the subject of e-mail . **** is the subject.
AT+SMTPBODY Sets e-mail body.
AT+SMTPSEND Initiates TCP session with SMTP server and sends an e-mail
AT+POP3SRV=”**”,”&&”,”xx”,yy OK Sets all parameters to get an e-mail from POP3 . ** is the server address, && is the user name, xx is the password and yy the server port
AT+POP3IN OK Logs in POP3 server
AT+POP3GET=*** Gets an e-mail from POP3 server , *** is the number of the e-mail.
AT+POP3OUT OK Logs out POP3 server
AT+POP3READ=”***”,”&&&” Reads an e-mail from file system . *** is the location and &&& is the name.

12. SD and system memoryGo to index

The file system is used to store files in a hierarchical (tree) structure. Local storage space is mapped to “C:”, and SD is mapped to “D:”. In both “C:” and “D:” directories, module creates four directories named “Picture”, “Audio”, “Video” and “VideoCall” automatically; “Picture” is used to store static image when taking picture by camera, “Audio” is used to store audio file, “Video” is used to store video file when recor ding by camera, and “VideoCall” is used to store media file which is recorded during a video call.

The maximum size of the microSD card is 32GB. Here are some AT commands to manage the file system:

AT command Response Description
AT+FSCD=**** OK Select a directory as current directory . **** is the directory.
AT+FSMKDIR=**** OK Create a new directory in current directory . **** is the name of the new directory.
AT+FSRMDIR=**** OK Delete existing directory in current directory . **** is the name of the directory to delete.
AT+FSLS Make a list with informations of directories and/or files in current directory.
AT+DEL=**** OK Delete a file in current directory. **** is the name of the file to delete.
AT+FSRENAME=****,&&& OK Rename a file in current directory. **** is the actual name and &&& is the new name.
AT+FSATTRI=**** Request the attributes of file which is existing in current directory. **** is the name of the file.
AT+FSMEM Check the size of available memory.
AT+FSFMT OK Format storage card which is plugged in.
AT+FSLOCA= OK Set the storage place , 0 for local and 1 for SD

13. FTP and FTPSGo to index

FTP

Creating a file into the FTP server, writing it and reading it.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Uploading a file from local storage or SD to FTP server.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Downloading a file from FTP server or SD to local storage.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

FTPS

Creating a file into the FTP server, writing it and reading it (likes FTP codes)

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Uploading a file from local storage or SD to FTP server

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Downloading a file from FTPS server or SD to local storage

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Command summary

AT command Response Description
AT+CGSOCKCONT=**,&&& OK ** is the protocol and &&& Access Point Name.
AT+CFTPSERV=”****” Sets FTP server domain name or IP address. **** is the domain name or the IP.
AT+CFTPPORT=*** OK Sets FTP server port. *** is the port.
AT+CFTPUN=”***” OK Sets user name for FTP server access. *** is the user name.
AT+CFTPPW=”***” OK Sets password for FTP server access. *** is the password.
AT+CFTPMODE= OK Sets FTP mode. 1 for passive or 0 for proactive.
AT+CFTPTYPE= OK Sets the transfer type on FTP server . A for ASCII or I for binary.
AT+CFTPPUT=”***”,&& Puts a file from FTP server to serial port . *** is the path with the name of the file and && is the length.
AT+CFTPGET=”***” Gets a file from FTP server to serial port . *** is the path with the name of the file.
AT+CFTPPUTFILE=”***”,& Uploads a file to FTP server from module . *** is the path and & is the storage directory.
AT+CFTPGETFILE”=***”,& Downloads a file from FTP server to module . *** is the path with the name and & is the storage directory.
AT+CFTPSSTART OK Acquires FTPS protocol stack.
AT+CFTPSLOGIN=”**”,&&&,”xxx”,”yyy” OK Logs in FTPS server. *** is the host address, &&& is the port, xxx is the user name and yyy is the password.
AT+CFTPSTYPE= OK Sets the transfer type on FTPS server . A for ASCII or I for binary.
AT+CFTPSPUT=”***”,&& Puts a file from FTPS server to serial port . *** is the path with the name of the file and && is the length.
AT+CFTPSGET=”***” Gets a file from FTPS server to serial port . *** is the path with the name of the file.
AT+CFTPSPUTFILE=”***”,& Uploads a file to FTPS server from module . *** is the path and & is the storage directory.
AT+CFTPSGETFILE=”***”,& Downloads a file from FTPS server to module . *** is the path with the name and & is the storage directory.

14. TCP and UDPGo to index

UDP client

Sending data to a UDP server:

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

TCP client

Sending data to a TCP server:

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Multiclient

SIM5218 allows to use ten connections simultaneously. Here is the example code with a UDP and TCP connections.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

TCP server

SIM5218 allows to create a TCP server with a maximum of ten TCP clients. In this example the server send a message every 5 seconds to all clients.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Command summary

AT command Response Description
AT+NETOPEN=”***”,&& Opens a socket . *** is the socket type and && is the port.
AT+NETCLOSE OK Closes socket.
AT+UPDSEND Sends UDP data.
AT+TCPCONNECT=”***”,&& Establishes TCP connection with TCP server. *** is the IP address and && is the port.
AT+TCPWRITE Sends TCP data when the TCP connection is established.
AT+SERVERSTART OK Starts up TCP server.
AT+LISTCLIENT Lists all of clients’ information.
AT+ACTCLIENT=* OK Activates the specified client. * is the number of the client.
AT+CLOSECLIENT=* OK Disconnects the specified client. * is the number of the client.
AT+CIPOPEN=*,”&&”,”xx”,yy Establish a connection with TCP server or UDP server. * is the number of the connection, && is the type of transmision protocol, xx is the server IP and yy is the server port.
AT+CIPSEND Sends some data to remote host in mult-client mode.
AT+CIPCLOSE=* OK Closes a specified connection in multi-client mode. * is the number of the connection.

15. HTTP AND HTTPSGo to index

HTTP

SIM5218 can launch a HTTP operation like GET or POST. Here is an example with GET operation. As you can read in the header of the code, you will need to increase the buffer size to 400 bytes.

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

HTTPS

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:

Command summary

AT command Response Description
AT+CHTTPACT=”***”,&& Launches a HTTP operation . *** is the server address and && is the port.
AT+CHTTPSSTART OK Acquires HTTPS protocol stack.
AT+CHTTPSSTOP OK Releases HTTPS protocol stack.
AT+CHTTPSOPSE OK Opens a new HTTPS session.
AT+CHTTPSCLSE OK Closes the opened HTTPS session.
AT+CHTTPSSEND=* Sends HTTPS request. * is the length of the data in the sending buffer.
AT+CHTTPSRECV=* Receives HTTPS response after sending HTTPS request.

16. Fritzing LibrariesGo to index

The new 3G shield for Arduino enables the connectivity to high speed WCDMA and HSPA cellular networks in order to make possible the creation of the next level of worldwide interactivity projects inside the new “Internet of Things” era.

You can download our Fritzing libraries from this area.

17. Video-TutorialGo to index

Here’s an explanatory video, which shows the whole process developed in this tutorial:

Check the GPS+PIC Code here:

Arduino:

Show code
Code:

Raspberry Pi:

Show code
Code:


永不消逝的电波

$
0
0

永不消逝的电波(一):无线电入门篇

2015-09-16157511人围观,发现39个不明物体无线安全极客

文/漏洞盒子安全团队-雪碧

0×00 无线电发展简史

· 1837年,摩斯发明了电报,创造了摩斯密码(Morse code),开始了通信的新纪元。
· 1865年,英国的麦克斯韦总结了前人的科学成果,提出电磁波学说。 
· 1876年,贝尔发明了电话,能够直接将语言信号变为电能沿导线传送。 
· 1887年,德国科学家赫兹(Hertz)用一个振荡偶子产生了电磁波,在历史上第一次直接验证了电磁波的存在。 
· 1897年,意大利科学家马可尼(Marconi)在赫兹实验的基础上,实现了远距离无线电信号的传送,这个距离在当时不过一百码,但一年后他就实现了船只与海岸的通信。 
· 1901年12月12日,马可尼做了跨越大西洋传送无线电信号的表演。这一次他把信号从英国的Cornwall发送到加拿大的Newfoundland。 马可尼因此获得1909年度诺贝尔奖。与他分享这一年度诺贝尔奖的是布劳恩(Braun),因为布氏发现金属硫化物具有单向导电性,这一成果可用于无线电接收装置。 
· 1904年,英国科学家弗莱明(Fleming)获得了一项专利,在专利说明书中描述了一个高频交变电流整流用的两极真空管,标志着进入无线电电子学时代。  
· 1906年,美国科学家弗雷斯特(Forest)发明了真空三极管,是电子技术发展史上第一个重要里程碑。同年,美国科学家费森登(Fessenden)在Massachusetts领导了第一次广播。 
· 1912年,英国科学家埃克尔斯(Eccles)提出了无线电波通过电离层传播的理论,这一理论使得一群业余爱好者在1921年实现了短波试验性广播; 同年,美国的费森登(Fessenden)和阿姆斯特朗(Armstrong)改进了接收机的工作方式,发明了外差式接受系统,这种形式仍是目前许多无线电接收机的主要工作方式。

在新中国成立后相当长的一个时期内,由于考虑国家安全等问题,国家对无线电台实行“少设严管”的政策,无线电台成为军队、邮电、广播、公安和交通等国家要害部门进行信息通信的重要工具。改革开放以后,各种无线电新技术、新业务在国民经济和社会生活的各个领域得到了越来越广泛的应用,我国逐步成为全球无线电应用大国。

近年来,国际电联划分的43 多种无线电业务,已在我国通信、广电、铁路、交通、航空、航天、气象、渔业、科研等行业和领域得到广泛应用,有力地推动了经济和社会发展的进程。

0×01 电磁波与无线电

1. 混为一谈OR完全割裂

有人会把电磁波、光、无线电波混为一谈,也有人会把它们完全割裂开来,这些都是不正确的。

在快速变化的电流周围会产生电磁波,为了描述电磁波的特征,科学家们引入了频率、波长、波速三个物理参数:

物理量       概念                          单位
频率(f)    电磁波1s振荡的次数             赫兹(Hz)
波长(λ)    电磁波每振荡一次向前传播的距离  米(m)
波速(c)    电磁波每1s向前传播的距离       米/秒(m/s)

公式    C=λf(波速=波长×频率)

2. 电磁波波段划分:

L波段、S波段、C波段、X波段、Ku波段、K波段、Ka波段。

这种划分方式是雷达业内的通俗叫法,没有一个严格、统一的标准。通常的划分是:

L波段 1~2GHz;
S波段 2~4GHz;
C波段 4~8GHz;
X波段 8~12GHz;
Ku波段 12~18GHz;
K波段 18~27GHz;
Ka波段 27~40GHz;
U波段 40~60GHz;
V波段 60~80GHz;
W波段 80~100GHz.

3. 电磁波的速度&分类:

电磁波产生之后,传播时不需要任何介质,在真空中也能传播,其在真空中传播速度为固定值,是宇宙中物质运动的最快速度,与光速相同,数值为3×10^8 (3乘10的八次方) m/s;

电磁波根据波长的大小,分为短波、中波、长波、微波、红外线、可见光、紫外线、Χ射线、γ射线等。

4. 无线电波传播途径:

无线电波广泛地应用于无线电通讯、广播、电视等方面,无线电波的发射和接受通过天线实现,其传播分为三种途径:天波、地波、微波。

地波:沿地球表面空间传播的无线电波叫做地波。由于地球是一个大导体,地球表面会因地波的传播引起感应电流,因此地波在传播过程中要损失能量,频率越高损失的能量也越多,所以地波主要适用于长波、中波和中短波。
天波:依靠电离层的反射来传播的无线电波叫做天波。电离层对于不同波长的电磁波的反射和吸收表现不同的特性,波长越长,吸收越强反射越弱,因此短波最适宜以天波的形式传播。
微波:微波是由于频率高、波长短,它既不能以地波的形式传播,又不能依靠天波的形式传播,和光一样,沿直线传播。

5. 无线电与电磁波

频率在数百千赫兹到数百兆赫兹之间的电磁波叫做无线电波,它包括短波、中波、长波、微波,无线电波也仅仅是电磁波的一部分,但电磁波不仅仅只有无线电波,仅仅只有频率相对较低的一部分电磁波才叫无线电波。

0×02 无线电信号调制

1. 什么叫调制,为什么要调制?

声音的频率是20HZ-20KHZ,转变成电磁波后也是这个频率,属于低频。电磁波的频率越高越容易传送得更远。所以音频需搭载在高频信号上才能传输得更远,音频搭载上高频信号的过程就叫调制。

调频波波形

无线电信号是原始信号和已调振荡信号的总称。声音、图像、文字、电码等欲传送的信息,通过转换设备后,转变成为相应变化的电压或电流,这种变化的电压或电流称为原始信号。在发射机中原始信号是用来调制高频振荡的,或者说是用来控制高频振荡的某一参数的,因此又称为调制信号或控制信号。经过调制的高频振荡,或者说参数按调制信号规律变化的高频振荡,称为已调振荡(已调波)。

调制的目的是为了把音频传送到更远的地方。目前常用的方法有调幅(AM)和调频(FM)两种方法。

AM(Amplitude Modulation 调幅):调制幅度,高频信号的幅度随着音频信号幅度的改变而改变,当音频信号的幅度高时高频信号的幅度也跟着高,反之跟着变低,形成音频信号的幅度包络,但高频信号的频率保持不变;调幅的特点是频宽宽,距离短。频宽宽的意思是对阻碍物的穿透能力强,但是传输距离较短
FM(Frequency Modulation 调频):调制频率,高频信号的频率随着音频信号幅度的改变而改变,当音频信号的幅度高时高频信号的频率也跟着高,反之跟着变低,但高频信号的幅度保持不变。调频的特点是频宽窄,距离长。频宽窄的意思是对阻碍物的穿透能力弱,但是传输距离长。

注:

频率:波在一定时间内震动次数
幅度:波在震动时候上下的幅度大小
调制器:    用于实现调制信号对高频载波信号的调制,产生已调波输出。
高频放大器:    对产生的已调波进行功率及幅度的放大后送至天线发射出去。
电源:    为电路各个部分提供电源。

数字信号波形

0×03 日常生活中的无线电

1. 收音机(无线广播)

在一般的收音机或收录音机上都有AM及FM波段,这两个波段是用于收听国内广播的,若收音机上还有SW波段时,那么除了国内短波电台之外,还可以收听到世界各国的广播电台节目。

一般中波广播(MW: Medium Wave)采用了调幅(AM)的方式,在不知不觉中,MW及AM之间就划上了等号。实际上MW只是诸多利用AM调制方式的一种广播,像在高频(3-30MHz)中的国际短波广播所使用的调制方式也是AM,甚至比调频广播更高频率的航空导航通讯(116-136MHz)也是采用AM的方式,只是我们日常所说的AM波段指的就是中波广播(MW)。

2. 遥控器

3. 路由器

频率:2.4GHz、5GHz

双频路由:2.4G&5GHz


4. 卫星天线

目前,卫星电视广播采用了三种方式:

一、通过普通的通信卫星将模拟或数字电视信号转发到本地电视台、有线电视网或集体接收站进入千家万户;
二、采用模拟技术,使用大功率电视直播卫星直接向家庭广播电视信号,由于这种电视信号未经数字压缩处理,每个转发器只能直播一路电视节目信号,每颗卫星一般只能直播几路电视节目;
三、采用Ku频段数字视频压缩卫星电视直播。每个卫星转发器可向装有约为0.5~0.8m左右的小口径卫星接收天线的家庭直播5~8路电视节目,一颗卫星可以直播100多路电视信号。这种业务亦称卫星数字电视直播(DVB-S);
随着航天技术、数字电视技术、微电子技术、码率压缩技术的突破性进展,使卫星电视由原来的C频段转播进入了数字Ku频段的直播卫星阶段。卫星数字电视直播的发展已成为全球热点。

C波段天线&Ku波段天线

c波段卫星 机顶盒的大锅 直径1.2米

户户通(村村通)直播星小锅 直径0.3米

卫星天线的一些小知识:

· 在卫星通信中,要先从地面站向卫星上发送通信信号,叫上行,经过卫星上的星载设备进行放大,再发送回地面的另一个接收站接收,叫下行。
· 为防止上行和下行频率重叠干扰,系统中上行和下行各采用一个频率进行发送,从地面向卫星发送上行信号的频率叫上行频率,从卫星向地面发送下行信号的频率叫下行频率。

· 卫星天线调试参数:本振频率、下行频率、符号率、极化方式,不过目前大多数机顶盒自带自动搜索功能,所以这些参数无需牢记。

亚洲七号卫星部分节目参数

近期FreeBuf报道也曾报道过,APT 组织 Turla 使用基于卫星的通信实现 C&C

上面提及的间谍组织使用使用了DVB-S调制器(下图):

这里我们稍微了解一下:DVB-S(ETS300421) 数字卫星广播系统标准。

特点:卫星传输具有覆盖面广、节目容量大等特点。数据流的调制采用四相相移键控调制(QPSK)方式,工作频率为11/12GHz。

FreeBuf也曾报道过,今年的BlackHat大会上也有个卫星相关的议题《利用卫星接收器扩展僵尸网络》。

5. 机场塔台与飞机

一般来说,降落的灰机高度在6K的时候会通过无线电与机场塔台联系,首次联系时会向机场塔台报告本次航班的编号、已经收到的机场通播编号等(起飞的时候灰机和塔台之间也会有通信联系)。

然后机场塔台会回复该航班,是否已经从雷达上看到该航班、该航班应继续进行的操作(例如保持目前航向等),然后该航班会重复一次机场塔台刚刚发布的指挥信息。这就完成了一次联系。

机场塔台&飞机

参考知乎:机场塔台的无线电环境有什么要求?在其周围私设电台会对塔台和飞机通讯造成哪些影响?

我国民航使用的无线电频率:1090MHz

民用对讲机使用的无线电频率:408-409MHz

警用频率:350-390MHz

0×04 使用软件无线电接收飞机信号

1. 接收飞机信号的常用设备

电视棒

优势:廉价(四五十元) 接地气

不足:只能接收、不能发射信号

HackRf

优势:开源、可以接收、发射信号

不足:USB2.0传输速率低于接收速率

其它设备:bladeRF 

优势:USB3.0;支持300MHz到3.8GHz

缺陷:最高只能支持 3.8GHz,不可能用bladeRF来实现5GHz频段的802.11n

电视棒的核心芯片:

淘宝搜索”电视棒”一词是被屏蔽的,想买的同学可以搜电视棒的芯片名:“RTL2832U”。

USB DVB-T & RTL-SDR Realtek RTL2832U & R820T,这是螃蟹( Realtek)的一个芯片型号,原本是做电视棒芯片的。

后来被人发现这个芯片具有非常广的频率接收范围,然后就被用来做sdr应用了,rtl的sdr应用。

其实,某宝两三百的无线电接收器也是根据电视棒芯片改装的。

(都是用的RTL2832U。左边价格三百,右边四十多,知道真相的我曾经哭晕在厕所)

2. 电视棒使用的一些软件

硬件有了,那么软件呢?

Linux:(Ubuntu)环境搭建

硬件驱动:rtl-sdr

接收信号&解码:dump 1090

sudo apt-get install git
sudo apt-get install cmake
git clone https://github.com/pinkavaj/rtl-sdr.git
cd rtl-sdr/ 
mkdir build 
cd build
cmake ../
make 
sudo make install 
sudo ldconfig

编译安装dump 1090:

git clone https://github.com/antirez/dump1090.git 
cd dump1090/ 
make

软件启动:

cd /home/$user/dump1090 #转到dump 1090的主目录
sudo ./ dump1090 --interactive --net

软件截图:

软件界面参数:

HEX:16进制数据
Flight:航班号
Altitude:灰行高度(海拔)
Speed:灰行速度
Lat/Lon:地理坐标(经纬度数)

dump启动时会开启自带的WEB服务器,并且WEB调用了谷歌地图的API 接收到飞机的一些信息后 会在页面地图上描绘出飞机的轨迹(谷歌地图目前需要翻墙):

Windows:

驱动-zadig:类似于驱动精灵。可以在win上安装电视棒、HackRf的驱动;

sdrsharp:可以用来听广播&录制无线电信号 并把信号保存为音频文件;

HDSDR:把音频转化为信号,可配合HackRF使用进行信号输出;

rtl1090:可以接收灰机信号;

Audacity:音频分析(信号分析);

另外,之前在网上查阅资料的时候看到一张图片,思路很Nice:(原文使用HACKRF巡视钓鱼岛(HACKRF ADS-B out) )

理论上来说,这种思路是可以实现的,但是法律上不可能允许民众私自占用无线频段,(一定要遵守无线电管理法规!一定要遵守无线电管理法规!一定要遵守无线电管理法规!重要的事情要说三遍),PS:通过无线电信号的“伪造”灰机,那么雷达那边如何才能瞒天过海?

第一篇先到这里,接下来的文章中我们将通过windows上一些软件(sdrsharp、HDSDR、Audacity)进行信号分析并使用HackRF进行简单的遥控信号重放。(其实,写完这句话的时候我的内心是崩溃的,牛皮吹大了,万一不能实现怎么破?!趴在厕所马桶上哭完,坚强地回到工位 o(╯□╰)o囧  然后终于顿悟:生命在于折腾,自己吹的牛逼流着泪也要实现!)

*参考资料:人民教育出版社 、无线电通信发展简史、新时期的无线电技术应用、维基百科、google、百度、知乎,雪碧整理发布,转载请注明来自FreeBuf黑客与极客(FreeBuf.COM)

【永不消逝的电波(二)】HackRF入门:家用无线门铃信号重放

2015-11-2275498人围观,发现19个不明物体专题无线安全

作者:雪碧 0xroot

0×00 前言

在第一篇文章:永不消逝的电波(一):无线电入门篇 我们了解了一下无线电的发展史以及无线电的一些物理知识,在第二篇里我们将用HackRF录制家用门铃的无线信号,然后重放门铃信号。

门铃从某宝买的,如图:

看到红色部分的时候,雪碧同学的表情是这样的:

好像买完什么,用不了多久就降价了,233….  我可以退货再买吗?

0×01 环境搭建:

MAC下可以用gqrx和hackrf (需要有Xcode、Mac Port的支持)

sudo port install gnuradio
sudo port install hackrf
sudo port install rtl-sdr
sudo port install gr-osmosdr
sudo port install hackrf

sudo port install gqrx

也可以参考:在Mac上安装HackRF环境

0×02 步入正题:

安装完成以后,插入HackRF,终端执行 hackrf_info:

hackrf_info 
Found HackRF board.
Board ID Number: 2 (HackRF One)
Firmware Version: git-815d1f6
Part ID Number: 0xa000cb3c 0x00664f49
Serial Number: 0x00000000 0x00000000 0x583064c0 0x2640ad4b
#通过终端启动gqrx
gqrx

按下遥控器,我们可以看到信号的频率在314.100000Mhz(读作:314.1兆赫兹)左右

1Mhz=1000000hz;
1Khz=1000hz

314.1Mhz=314100000hz;

关掉gqrx启动hackrf

hackrf_transfer Usage:

Usage:
    -<filename> # Receive data into file. 把接收到的信号、数据保存到文件中;(信号录制)
    -<filename> # Transmit data from file. 从文件中提取、发送射频信号;(信号播放)
    -# Receive data into file with WAV header and automatic name.
       # This is for SDR# compatibility and may not work with other software.
    [-f freq_hz] # Frequency in Hz [0MHz to 7250MHz].
    [-i if_freq_hz] # Intermediate Frequency (IF) in Hz [2150MHz to 2750MHz].
    [-o lo_freq_hz] # Front-end Local Oscillator (LO) frequency in Hz [84MHz to 5400MHz].
    [-m image_reject] # Image rejection filter selection, 0=bypass, 1=low pass, 2=high pass.
    [-a amp_enable] # RX/TX RF amplifier 1=Enable, 0=Disable.
    [-p antenna_enable] # Antenna port power, 1=Enable, 0=Disable.
    [-l gain_db] # RX LNA (IF) gain, 0-40dB, 8dB steps
    [-g gain_db] # RX VGA (baseband) gain, 0-62dB, 2dB steps
    [-x gain_db] # TX VGA (IF) gain, 0-47dB, 1dB steps
    [-s sample_rate_hz] # Sample rate in Hz (8/10/12.5/16/20MHz, default 10MHz).
    [-n num_samples] # Number of samples to transfer (default is unlimited).
    [-c amplitude] # CW signal source mode, amplitude 0-127 (DC value to DAC).
    [-b baseband_filter_bw_hz] # Set baseband filter bandwidth in MHz.
    Possible values: 1.75/2.5/3.5/5/5.5/6/7/8/9/10/12/14/15/20/24/28MHz, default < sample_rate_hz.
hackrf_transfer -/dev/stdout -314100000 -1 -16 -32 -8000000

没按遥控器

按下遥控器:

由于hackrf_transfer后面没带解码参数,so我们看到一堆乱码数据;

0×03 录制信号&信号分析

录制遥控的无线信号:

hackrf_transfer -r door.raw -314100000 -16 -32 -1 -8000000 -4000000

终端输出:

hackrf_transfer -r door.raw -314100000 -16 -32 -1 -8000000 -4000000
call hackrf_sample_rate_set(8000000 Hz/8.000 MHz)
call hackrf_baseband_filter_bandwidth_set(3500000 Hz/3.500 MHz)
call hackrf_set_freq(314100000 Hz/314.100 MHz)
call hackrf_set_amp_enable(1)
Stop with Ctrl-C
16.0 MiB / 1.005 sec = 15.9 MiB/second
16.0 MiB / 1.003 sec = 15.9 MiB/second
16.0 MiB / 1.004 sec = 15.9 MiB/second
16.3 MiB / 1.004 sec = 16.2 MiB/second
16.0 MiB / 1.002 sec = 16.0 MiB/second
16.0 MiB / 1.001 sec = 16.0 MiB/second
16.0 MiB / 1.004 sec = 15.9 MiB/second
16.0 MiB / 1.003 sec = 15.9 MiB/second
16.3 MiB / 1.003 sec = 16.2 MiB/second
16.0 MiB / 1.003 sec = 15.9 MiB/second
16.0 MiB / 1.005 sec = 15.9 MiB/second
^CCaught signal 2
 8.1 MiB / 0.510 sec = 15.9 MiB/second

User cancel, exiting...
Total time: 11.54724 s
hackrf_stop_rx() done
hackrf_close() done
hackrf_exit() done
fclose(fd) done
exit

—————————————萌萌的分割线—————————————题外话—————————————

信号波形分析:

这里用到的软件是Audacity,导入录制的音频信号(未压缩原始数据)

然后出现如下界面:

使用默认参数,直接导入:

中间的那部分就是按下遥控时录制到的无线信号,我们使用Audacity的放大镜放大来看:

继续放大我们可以看到:

继续放大:

再放大:

这时经验比较丰富的童鞋可以通过图形,把无线射频信号转换成二进制数据:01010101**** ,接着可以把二进制写到GRC(Gnu Radio Cpmpainon),制作一个框图,使用GNC项目重放无线信号,大致方法如下:

启动Gnu Radio Cpmpainon  :Kali Linux—->无线攻击—>Software defined Radio—>GnuRadio-Companion

源:在右侧Misc一栏找到Vector Source

通过搜索添加Repeat(old)、Moving Average、osmocom Sink

四个组件:

按照流程连线:

GNC用得不多,暂时还不上手,这种方法以后再试 :)

—————————————萌萌的分割线—————————————题外话结束—————————————

0×04 信号重放

使用hackrf_transfer重放信号:

hackrf_transfer -t door.raw -314100000 -47 -1 -8000000 -4000000

终端输出:

hackrf_transfer -t door.raw -314100000 -16 -32 -1 -8000000 -4000000
call hackrf_sample_rate_set(8000000 Hz/8.000 MHz)
call hackrf_baseband_filter_bandwidth_set(3500000 Hz/3.500 MHz)
call hackrf_set_freq(314100000 Hz/314.100 MHz)
call hackrf_set_amp_enable(1)
Stop with Ctrl-C
16.0 MiB / 1.004 sec = 15.9 MiB/second
16.0 MiB / 1.004 sec = 15.9 MiB/second
16.0 MiB / 1.003 sec = 15.9 MiB/second
16.0 MiB / 1.001 sec = 16.0 MiB/second
16.0 MiB / 1.000 sec = 16.0 MiB/second
16.3 MiB / 1.001 sec = 16.2 MiB/second
16.0 MiB / 1.003 sec = 16.0 MiB/second
16.0 MiB / 1.001 sec = 16.0 MiB/second
16.0 MiB / 1.005 sec = 15.9 MiB/second
16.0 MiB / 1.003 sec = 15.9 MiB/second
16.3 MiB / 1.003 sec = 16.2 MiB/second
 8.4 MiB / 1.004 sec =  8.4 MiB/second
 
 
Exiting... hackrf_is_streaming() result: HACKRF_ERROR_STREAMING_EXIT_CALLED (-1004)
Total time: 12.03184 s
hackrf_stop_tx() done
hackrf_close() done
hackrf_exit() done
fclose(fd) done
exit

0×05 演示视频

http://v.qq.com/iframe/player.html?vid=d0173868gnw&tiny=0&auto=0binggo

熊孩子的正确使用姿势是这样的:

for i in {1..999}; do hackrf_transfer -t door.raw -314100000 -16 -32 -1 -8000000 -4000000; done

嗯,你没看错,重复播放九百九十九次 :)

0×06 参考:

Hacking fixed key remotes

Exploring Bluetooth & iBeacons – from software to radio signals and back.

中文版:HackRF嗅探蓝牙重放iBeacons信号

GNU_Radio入门_V0.99

*本文原创作者:雪碧(0xroot),转载请注明来自FreeBuf黑客与极客(FreeBuf.COM)


Experiments with the RFM69 433MHz digital transceiver module

$
0
0

Experiments with the RFM69 433MHz digital transceiver module

Summary: 

This post is an overview of an board I’m developing which encapsulates the RFM69 radio module with a MCU to expose a simple UART API which can be tailored for specific applications. This simplifies embedding a radio into existing applications with very little additional expense in terms of hardware or power budget. The API is implemented by a light weight radio OS (currently just 5KiB) which is open source and the bill-of-materials for the board can be as little as $8 / €7.

Background to project:

WRSC2014 contestant Team FASt from University of Porto.

The World Robotic Sailing Championship 2014was held in Galway Ireland (my home town) in September this year. It was originally anticipated that each contestant would use a RFM69 radio module to relay real time positioning information back to a central hub for recording the race and scoring. It was also hoped that the race organizers could use the same radio network to broadcast race waypoints, starting times, obstacles etc. However given the short time available it became clear that race contestants would not have sufficient time to incorporate this module into their hardware and write the associated supporting firmware.

Based on the experience of WRSC 2014 I believe the best solution for such competitions is to develop a low cost ready made ‘black box’ which is given (ready made and programmed) to each contestant. The black box would expose a very simple API to the boat’s software which should not take long to integrate. Or if it’s a case the contestant simply does not have time to make any changes to their software the radio can be mated with a GPS module and it will send real time position, speed and heading back to the race organizers.

This project is the first step in such a system.  An entire race system will incorporate other elements such as base station software, real time visualization tools, race protocols etc. This blog post only discusses the radio board.

RFM69 family of modules:

The RFM range of modules are made by HopeRF and based on the Semtech radio ICs. The RFM69 comes in several varieties. The one I’ve been using is the higher power version: the RFM69HW [1] which is based on the Semtech SX1231H [2]  chip.

Feature highlights:

  • Digital SPI interface
  • Operates on 433MHz unlicensed ISM band
  • Continuous or packet mode (66 byte FIFO)
  • Built in AES encryption and CRC-16 engine
  • Configurable bit rates up to 300kbps
  • Configurable power settings
  • Line-of-sight ranges in excess of 1km
  • Sleep current < 1µA
  • Only $4 in small quantities

The radio board:

This is the general architecture of the board: a MCU acts as the go between the application hardware and software and the RFM69 radio module. The MCU takes care of all the complex register configuration of the RFM69 and takes of low level functions (such as responding to pings, remote configuration commands etc) without ever bothering the application. The application talks to the MCU thru a standard UART interface using a very simple protocol.

In addition to the core API there is also the option to compile in application specific functions (for example I’ve build in support for a rain tip-bucket and a temperature sensor: more on that later).

Prototype mk1:

Unfortunately these modules have a 2mm pad pitch making them difficult to use directly with standard 2.54mm spacing prototype board or breadboard. So for the first prototype I glued the module onto a prototype board and used thin 30AWG wire to link the module pads to pads on the protoboard.

Reasonably need looking from above…

The problem is on the underside…

Even though it’s only a hand full of wires, cutting, stripping and soldering these is very time consuming and error prone (well in excess of three hours per board).

For the first prototype I used a LPC810 ARM Cortex-M0+ MCU as the controller.  The ARM Cortex-M range is my MCU of preference these days due to the ease of 32 bit programming, open source and well supported tools and a wide range of vendors (NXP, TI, Freescale etc).

This 8 pin DIP, 4KiB program memory device was adequate for initial tests, but I quickly ran up against the 4KiB program limit. The 8 pin DIP package also had the advantage that I could socket it and try different versions of firmware just by swapping out the device.

With two of these modules I did some range tests. I soldered 17cm wire (quarter wave at 433MHz) to both sides of the board just at the RFM69 antenna output pad. I was able to achieve two way communication of about 1km along the (line-of-sight) length of the Doughiska Road in east Galway city.

Prototype mk2:

For the next prototype I moved to the LPC812: in many ways identical to the LPC810 but with more IO pins and more memory (16KiB program memory, 4KiB SRAM). Rather than use time consuming protoboard I decided it was worth spending some money on a PCB. I designed a two layer board using the free version of CadSoft Eagle and used Eurocircuit’s standard FR4 pool to fabricate. This job cost €80, but for that I got 20 boards. The turn around time was nominally 10 working days, but I had them in a week.

The board in the photo actually comprises two boards:  one for the RFM69 discussed here and another for a similar (better?) module the RFM98 which I’ll discuss in another blog post. The two halves are separated with a hacksaw.

One very handy feature of the LPC81x range of MCU is the switch matrix which allows many of the MCU functions to be mapped to an arbitrary pin.  This makes PCB layout a lot easier.

After populating with the MCU, module and 3 other components (LED, resistor and decoupling capacitor for MCU) this is what the board looks like. There is the option to use a wire as antenna, or alternatively splash out on a SMA connector (probably the most expensive component on the board!). This photo shows a SMA connector with a 433MHz stub antenna obtained from Farnell [3].

On the left is the UART connector for the radio API, pins for Serial Wire Debug (SWD) for debugging and reprogramming. Left top is the power connector (3.3V nominal, but will work down to 1.8V).

There is also a LED at the very top-left. This is a general purpose indicator that’s under control of the MCU. I use this to flash a sequence after boot up tests are complete and flash it each time a packet is sent or received.

In the center there is an option for another connector which will give direct access to the RFM69 SPI port for debugging, or simply using the PCB as a breakout board for the radio module (leaving the MCU pads unpopulated).

The bill of materials is PCB €2;  LPC812M101JD20 €1.50; RFM69HW €3 ; passives, pin headers €0.50; SMA connector (optional) €3.50 ; stub antenna (optional) €5. That’s a total of €7 without the SMA connector option. Those prices with the exception of the PCB are for single quantities from Element 14’s catalog.  Significant discounts are usually available when ordering 20+. Also components can often be sourced at a much lower cost from Chinese retailers (eg Alibaba and Deal Extreme). The PCB cost is more complex: many fabricators have a fixed job charge (it was about €50 for Eurocircuits) and they then charge per PCB after that. So if you make a lot of them the price per board goes down quickly. If you make just one it will be very expensive.

The radio OS firmware:

My firmware is written in C and currently uses the LPCXpresso IDE to build. This uses the GCC compiler under the hood. The main purpose of the firmware is to expose an simple UART API which the host application uses. The API protocol is simple: a single character command/response code followed by parameters separated by spaces followed by a carriage-return to end the command. All parameters are in hexadecimal. Example:

application to radio:
T 44 5232

‘T’ means transmit a packet. It takes two parameters: the to-address and the packet payload.

radio to application:
p FF 42 7A14051F003D AD

The ‘p’ response code is transmitted to the application whenever a packet is received. There are four parameters: the to-address (FF hex being the broadcast address),  from-address, the packet payload and the RSSI (received signal strength indicator).
Other commands include ‘R’ and ‘W’ to read/write RFM69 radio configuration registers. ‘M’ to switch operating mode from an active awake/listening (20mA current use) to a sleep-polling mode using an average of about 140µA.
Some advanced experimental commands are remote register read/write, allowing a remote radio to be reconfigured. Remote watchdog timer configuration which will reset the radio to default configuration should there be a prolonged loss of communication. Remote command execution (which can be used for remote configuration and to relay packets), remote battery voltage measurement.
Test application:
As mentioned earlier the intended application is for robot sailboat telemetry. But I’m conducting initial tests by using one of these radios with a rain tip-bucket and temperature sensor in my garden. I’ve got the radio board in an IP66 enclosure with a small PV panel and LiPo battery (and associated charger).
The tip-bucket causes a magnet to fly past a reed-switch each time the bucket tips. I use this in conjunction with one of the spare LPC812 pins and an interrupt channel to count each time this happens. I’ve also got a DS18B20 temperature sensor on another spare pin.
I run this in low power polling mode. Every 30 seconds the MCU comes out of deep sleep mode, makes a temperature measurement and fires up the transmitter and sends a status packet with the tip bucket counter, current temperature, and battery voltage [4]. It listens for about 100ms for a response packet. If none is received it goes back into deep sleep mode.
If I need to communicate to the out door unit I must wait for a poll packet and then immediately send my command. If multiple commands need to be issued, the first command is to switch the radio into active listen mode, issue all the necessary commands and then put back into low power mode.
So far tests have been successful with the only communications disruptions attributed to either running out of battery charge (it’s winter here and the days are short: unless  it’s a sunny day there is not enough stored charge to keep it going through the night) or a problem with the USB/Serial cable at the receiving end.
This is 48 hours of some sample data. The disruptions are due to problems with the USB/Serial cable at the receiving end: the radio worked flawlessly. Also note the elevated temperatures are due to the sun falling directly on the IP66 box.
Current and future work:
I’m currently working an a web browser based application/UI to interact with these radios. The application will allow configuration of the local and remote radios, performing experiments with various radio settings. Monitoring network performance etc.

Also I’m planning to make a third prototype. This will be smaller than the current board, perhaps putting the MCU on the underside of the board. I’m also considering moving to the recently announced LPC82x MCUs [ref] which feature more program flash, more SRAM, a full ADC and other new features.

Features for future firmware include mesh networking, encryption, remote program execution and over-the-air firmware upgrades.

Conclusions:

So far I’m very impressed with these radio modules. At only $4 they’re a steal. I’ve verified two way communication at over 1km distance line-of-sight and I’ve heard reports of success well in excess of 1.5km line-of-sight. With the addition of an LPC812 MCU with my radio OS and simple UART API, embedding this radio into an application is far simpler than building the radio driver directly into the application software. The entire bill of materials is about $7 with the option of a SMA connector which might bring it to $10. My PCB layout is available under the BSD licence on GitHub [5] and the firmware is also available on GitHub [6].

Footnotes:
[1] RFM69 Datasheet
http://www.hoperf.cn/upload/rf/RFM69-V1.3.pdf

[2] Semtech SX1231H product information and datasheet
http://www.semtech.com/wireless-rf/rf-transceivers/sx1231h/

[3] Farnell/Element 14 SKU 2305893, €4.86 in single quantities.

[4] One feature I miss in the LPC81x range of MCU is a full ADC. There is however a comparitor which can be used with a voltage ladder to make crude voltage measurements. I use this for battery voltage measurement (Vcc thru voltage ladder on one comparitor input, and the built in 0.9V voltage reference on the other). In my tests it can detect low battery voltage condition, but due to the coarse resolution I get a warning only about a hour before the voltage drops below the cutoff threshold.

[5] https://github.com/jdesbonnet/RFMxx_LPC812

[6] https://github.com/jdesbonnet/RFM69_LPC812_firmware

Updates:

11 Feb 2015: Added link to firmware repository on GitHub.


Use Nokia 5110 with Arduino

$
0
0

In Tutorial 4, we learnt interfacing an HD44780-based LCD to a chipKIT board for displaying alphanumeric output. Today, we will see how to connect a NOKIA 5110 graphical LCD (used in Nokia 5110 cell phones), which is a 84×48 pixel monochrome display of about 1.5″ diagonal in size. The display can be used for graphics, text, and bitmaps.

T7_Title

Theory

Nokia 5110 LCD was used in Nokia’s popular 5110 and 3310 model cell phones. It is a 48×84 pixels matrix LCD driven by the low-power PCD8544 controller chip. It is powered by 3.3V and includes on-chip generation of LCD supply and bias voltages, thus requiring minimum external components for its operation. The PCD8544 receives display data and commands from a microcontroller through a serial bus interface. There are multiple Nokia 5110 LCD modules in the market; they all come pre-mounted on a PCB and look similar but the pin arrangements might be different in some modules. This is a very popular display among the Arduino community because of its low cost (~$3 on eBay) and simplicity to use with easily available open-source libraries. The LCD requires 5 I/O pins for full control. The pins available in almost every Nokia 5110 LCD modules are listed below:

  1. RST: Display reset input
  2. CE: Chip enable input
  3. DC: Data or Command select signal
  4. DIN: Serial data input
  5. CLK: Clock input
  6. VCC: 3.3V power supply
  7. EL: Backlight LED anode (connect to 3.3V)
  8. GND: Power supply ground

Nokia 5510 LCD module

Circuit Setup

For this experiment, we are using chipKIT Uno32 pins 8 through 12 to drive the data and signal lines of the Nokia 5110 LCD module. The connections are made as follows:

chipKIT Nokia 5110 LCD connections

We will also connect a DHT22 temperature and humidity sensor to the chipKIT Uno32 to add more fun to our experiment. DHT22 is a low-cost temperature and humidity sensor that provides calibrated digital outputs through a single wire digital interface. The following figure shows the pin diagrams of the DHT22 sensor.

DHT22 pin diagram

A pull-up resistor (usually 4.7K) must be connected between the Data and VCC pins. In our experiment, the sensor data pin is connected to pin 7 of chipKIT Uno32, while the sensor is powered through the 3.3V supply pin on the chipKIT Uno32 board. The complete setup of this experiment is shown below.

T7_Setup

Writing sketch

We will need to install two libraries for developing the firmware for this experiment. The first library required is the standard Arduino DHT22 library, which is modified by Trevor van der Linden to make it work with chipKIT platform. The second one is Nokia 5110 LCD library for chipKIT from Rinky-Dink Electronics. There are two versions of the LCD libraries: LCD5110_Basic, which supports texts, and LCD5110_Graph, which supports text, graph, and bitmaps. Download and install these libraries to your mpide/libraries/ folder using the following download links.

Download DHT22 Library

Download LCD5110_Basic

Download LCD5110_Graph

The chipKIT program for this experiment can be downloaded from the following link:

Download chipKIT Sketch

Output

After uploading the chipKIT firmware, the temperature and humidity measurements are displayed on the LCD screen as shown below. The values are refreshed every 5 seconds.

T7_OP2

The LCD5110_Graph library comes with some examples of graphical and bitmap displays, which can be found inside the examples sub-folder and accessed easily through MPIDE environment from File->Examples navigation menu as shown below:

Accessing examples from MPIDE

I would highly recommend to test and run these examples to get more familiar with the LCD5110 libraries. Simply upload these examples one by one to the Uno32 board without making any changes to the current circuit setup and see the action on the LCD screen.

Running sine wave, chipKIT logo, and Pacman examples

– See more at: http://embedded-lab.com/blog/chipkit-nokia-5110-lcd-example/#sthash.FDpyI8vU.dpuf


Feeding power to Arduino: the ultimate guide

$
0
0

Feeding power to Arduino: the ultimate guide

By on July 9, 2015

imm di copert

 

Let’s deal with the problems of the various powering modes for the most famous Arduino boards, in order to overcome doubts users may have and to provide useful advices.

When you want to use an Arduino board in stand-alone mode, the first problem to face is the one of how to power it, once it is disconnected from the computer’s USB port. Unfortunately, a faulty knowledge of the theme of powering sometimes leads people to make unforgivable mistakes, since the first result is often that of seeing the board go up in smoke and almost always irremediably, since from that moment it will not work any more.

In the premise it is good to point out that the article will deal with the powering modes of the Arduino boards operating at 5 V (UNO, MEGA, Duemilanove); a short, specific note will be dedicated to Arduino YÚN, that is still a 5 V board, but with features that are different from the other ones.

 

THE EXTERNAL POWER SOURCES

Basically, in addition to the computer’s USB port, the external power sources for Arduino are: linear and switching power supplies, or having a specific USB output (that most likely is of the switching kind) and batteries of various types.

 

THE POWER SUPPLIES

Amongst the many mistakes that are made, there is surely the one of recycling power supplies kept in a drawer, and by treating them as if they were all the same. Let’s start immediately by making it clear that those of the alternating current kind have to be absolutely excluded (they were used a lot by the analog modems of some years ago). In the figure  we can see the comparison between the two power supplies that are very similar, from a physical point of view: one operates on alternating current (AC) and the other one on direct current (DC).

 

Fig1

Comparison between power supplies operating on AC and DC

 

As it can be noticed from the symbols found on the respective tags, it is quite simple to distinguish the two models, even though they are physically similar.

In the alternating current model, shown on the right side of the figure, the line with the indications concerning the output says: AC 12 V 500mA 6VA, that respectively represent: alternating current, maximum output load and power, expressed in VA (that can always be obtained by means of the P = V*I formula). In some cases, in the place of the AC abbreviation, the symbol “~” may be found, and it still means “alternating current”.

On the left, on the contrary, the direct current model, in the line with the output values shows in an equally clear way +5 V 2A, moreover the symbol “═” graphically points to the direct current; finally, in these power supplies, the voltage polarity is always indicated on the output JACK; in this case the graphics represented on the tag indicates that the positive pole (+) is connected to the central part of the jack while the negative pole (-) is connected to the external part. We may still notice the presence of the “~” symbol on the tag, but it is clearly referred to the power supply input that, obviously, must be connected to the alternating current network.

In the course of this article we will talk about direct current only, having already clearly ruled out the alternating one for our purposes. Basically, the power supplies can be divided in three categories:

Unregulated linear power supplies: an unregulated linear power supply always takes into account an AC transformer converting from 230 Vac to a definitely lower value (usually from 3 to 24 Vac), a diode bridge rectifier (that has the task of converting the alternating current into direct current) and an electrolytic capacitor for filter and levelling. There are the so-called “multiple winding” models that have a transformer with a single primary winding for 230 Vac and many different secondary windings, and it is capable of supplying different alternating current voltages that, by means of a commutator, are connected (only one per time) to the diode bridge and to the capacitor, and therefore to the output. By measuring the behaviour of an unregulated power supply (regardless of the fact it is a single or multiple winding model) with a normal multimeter, it is possible to immediately notice how the voltage, in the absence of load, may be definitely higher than the nominal one, while in the presence of a load it proportionally decreases, depending on the current draw of the last one, decreasing even under the level of the nominal voltage. These power supplies do not offer any reliability and are often even harmful for the machineries that, if absorbing little, are powered at voltages that are much higher than the required ones. Consequently, they are absolutely to be avoided!

 

Fig2

Unregulated linear power supply

 

Regulated linear power supplies: this kind of power supply is characterized by the presence of further electronic components, in comparison with unregulated models, such as a voltage regulator and other capacitors with filter and anti-self-oscillating functions. In the greatest majority of cases they are single voltage tools, and very reliable ones, of dimensions that are proportional to the deliverable power; the voltage is very stable (typical variations of ±0,1V in respect to the nominal value), regardless of the current (always within the limits of the nominal value). In addition to an excellent stability, they have a very low ripple value (the residual variation of alternating current over direct current), but their performance is quite low (between 40% and 60%) since much power is dissipated by the regulator that, for this reason, may require a dissipation system that can even be quite bulky. The power dissipation is directly proportional both to the drop-out (the difference between input voltage at the regulator and output voltage from the same) and to the deliverable power. Moreover, the greater is the dissipated power, the greater is the temperature reached by the regulator’s case and, consequently, the lesser is the deliverable power. For such reasons the input voltage should always have a slightly higher value than the nominal one of the regulator. These power supplies are ideal for applications whose noise (ripple or high frequency) may prove harmful to the proper functioning of the circuit, typically when dealing with very low voltages. In general, they require an input voltage corresponding to the one of the electric network (230 Vac) or with quite a narrow range (220-240 Vac), moreover they are quite bulky.

 

Fig3

Regulated linear power supply

 

Switching power supplies: this last family of power supplies is the most recent, from a technological point of view; it is based on a high frequency work system and it is capable of regulating the output voltage at a value that is lower (step-down) than the input one (as in the case of the kind seen before), or at a higher value (step-up). The design of these systems is much more complex than the linear ones, but recently many integrated circuits have been put on the market, and with the help of a few external components, whose values can be calculated with the help of the data-sheet, and that make their creation quite easy. The dimensions are very limited, because of the high efficiency of such technology (80-90%) and even the stabilization is excellent. On the other hand, in respect to the regulated linear models, these power supplies have high ripple levels in addition to high frequency noise, which makes them not suitable to power circuits that suffer from such residual presences on powering. In general, they operate with a wide range of input voltages (100-240 Vac) and have dimensions that are definitely much smaller than their counterpart of the linear kind.

 

Fig4

Switching power supply

 

A particular type of switching power supplies is the one of mobile phone chargers; in general their usage is inadvisable since they have been designed for the exclusive purpose of recharging the battery, and thus often paying little attention to the noise filtering. Some models even incorporate the control system of the battery charge power, for example the ones for LiPo or Li-Ion batteries, thus making them totally unsuitable to power circuits that are different from the ones of a mobile phone.

 

THE BATTERIES

It is important to deal briefly with the problems connected with battery powering, since the need to make a circuit independent from the home electric network is not rarely felt. When deciding to resort to battery powering, the ratios between their capacity (usually expressed in mAh) and the power required by the Arduino board and the peripheral circuitry connected to it are often neglected, thus leading to results that are often disappointing (autonomy is very low or the system does not turn on at all).

In figure we represented an overview of the most commonly used battery types.

 

Fig5

Batteries Overview

 

Since a single battery cannot always satisfy all circuital needs, because of the low voltage value and/or low capacity, it becomes important to understand the series and parallel mechanism, that is to say, the ways with which two batteries may be connected between them to increase the said values. As a premise it must be very clear that all the batteries that will create a “pack” must be absolutely identical and possibly coming from the same batch; in the case of alkaline batteries they must strictly be new, in the case of rechargeable batteries all of them must be either fully charged or discharged.

Identical batteries, connected in parallel (all the positive poles between them and all the negative poles between them, see in figure) keep the same nominal voltage of a single one and sum up the capacities: e. g. four 1,5 V 200 mAh alkaline batteries connected in parallel make up a 1,5 V battery with a capacity that is equal to the one of a single battery multiplied by four (800 mAh). One resorts to this system when the voltage of the single battery is enough to power the circuit but a greater autonomy is needed.

 

Fig6

 Battery Pack in parallel

 

Identical batteries, connected in series between them (the negative pole of the first one goes to the positive pole of the second one, and so on), keep the capacity of the single battery and sum up the voltages: e. g. five 1,2 V 2000 mAh NiMh batteries, connected in series, make up a 6 V 2000 mAh pack. The connection in series is used when the single battery has a voltage that is too low and is unable to power the circuit; in fact in the specific example, with a single 1,2 V battery we could never power Arduino, and not even with 2, 3, or 4 batteries in series, since we would obtain 2,4 – 3,6 – 4,8 V respectively, and these wouldn’t still be enough for the purpose; on the other hand the fifth battery enables us to reach a 6 V tension that can be applied, for example, to the Vin pin, as we will see.

 

Fig7

Battery Pack in series

 

Of course, it is possible to combine the two types of packs, when in need to increase both the voltage and the current. For example, by connecting in parallel two packs already connected “in series” and made up by five 6 V 2000 mAh NiMh batteries (the pack described just a while ago), it is possible to obtain a 6 V 4000 mAh pack.

Hermetic Lead-Acid batteries are packs made up by 2 V elements that are connected in series; usually they are used alone, since they exist in various “sizes” as for voltage and capacity, but they still can be used in series or in parallel.

It is quite a complex thing to create Li-Ion or LiPo battery packs (the single cells must be “balanced”) therefore it is definitely more convenient to resort to commercial products. There are, however, specific battery chargers for these models’ packs, since each cell of the pack must be charged individually.

 

Fig8

Battery charger for LiPo/Li-Ion batteries

 

It is necessary to keep into account that the recharge system used by LiPo/Li-Ion batteries is very different from the one used by NiMh or hermetic Lead-acid batteries, thus you have to read up correctly before adopting any kind of batteries for your own project.

As regards autonomy, the calculation is quite a simple one, even though the thing gets complicated in the cases of “multi voltage”; in general it is enough to operate a division between the global capacity of the battery (expressed in mAh) and the circuit power consumption (expressed in mA) so to obtain the autonomy time (expressed in hours).

For example, an hermetic 12 V 2400 mAh Lead-acid battery, powering a circuit requiring 12 V 300 mA overall, guarantees a maximum autonomy of 2400/300=8 h(ours).

LiPo/Li-Ion batteries have the peculiarity to be able to deliver, even if for a very short time, current for values that are definitely greater than their nominal value, therefore they are very used in fields that require high inrush currents. On the other hand, they do not lend themselves for the creation of the so called “buffer” applications, that is to say, when a circuit is normally powered by the electric network and the batteries, constantly kept under charge, are used only when the power goes out (for example, in domotic installations), since they would get damaged in a very short time.

In these cases, the most suitable batteries are Lead-Acid ones, while NiMh or, worse, the older NiCd, suffer from the so called memory effect, thus it is better to use them until they are fully discharged to recharge them again.

For the usage as buffer, the Lead-acid batteries are definitely advisable, since they can be left constantly under charge, thus lending themselves to the task.

There are however recharge control circuits, very sophisticated ones, that in some cases allow some exceptions to what has been stated above.

 

THE INPUTS FOR POWERING

Now that we have quite a clear idea of the possible external power sources, we may see how to apply them to Arduino. Everything we will describe in this paragraph can be applied to all the kind of sources previously described, thus both power supplies and batteries. We point out again the need to pay maximum attention to the polarities: it is very important to connect properly the positive and the negative poles to the Arduino board, otherwise there is the risk to see nothing work or even to make irreparable damages. In fact, while in some cases there are some intrinsic protections on the board, in other cases the polarity inversion might cause immediate damages!

Arduino has four possible powering inputs:

 

Fig9

Arduino’s powering inputs

 

1 – USB Port: 5 V have to reach this socket (different voltages are not allowed, absolutely!), coming from a computer’s USB port, or from any power supply that is provided with a USB port (in general, they are small size power supplies, suitable to power devices that are provided with a USB cable). If the powering comes from a computer, there is a current limitation of 250 mA or 500 mA, depending on the USB port of the said computer; if on the other hand you are using an external power supply, the maximum output current (regardless of the one guaranteed by the same power supply, that in general is a maximum of 1 A or 2 A) is anyway limited to 500 mA by the PTC self-resettable protection fuse.

2 – JAPAN JACK socket: an external source (a power supply, usually) must be connected to this socket, with the positive pole going to the central part of the jack, and the value must be ranging between 6 V and 20 V, even though the range recommended by the manufacturer is 7÷12 V, thus it is not advisable to use voltages that are lower than 7 V or greater than 12 V, if not in the case of a real need; 6 V may not guarantee a proper stabilization on the part of the regulator, it is in fact needed to consider the voltage fall of the protection diode, placed in series at the regulator’s input (whose purpose is to preserve the board from destruction in the case of polarity inversion on the jack); while values above 12 V would create an excessively high drop-out (an electric potential difference between the regulator’s input and output) that would cause a pointless overheating of the regulator, even with low levels of current draw.

3 – Vin socket: this socket has a dual function.

3a – input for external powering, not protected by polarity inversions: in fact the connection goes directly to the regulator’s input and below the JACK socket’s diode; of course no voltage must be applied to the jack socket, otherwise dangerous conflicts might arise;

3b: output from which to draw the voltage applied to the JACK socket, detracting the protection diode’s fall. It might prove useful to power small loads, requiring a voltage higher than 5 V and equal to the one applied to the JACK socket (always considering the diode’s voltage fall).

In both cases the voltage negative pole can be found on the board’s GND sockets.

4 – 5 V socket: it is directly connected to the regulator’s output, thus the 5 V to power external loads to Arduino can be drawn from it. In the case voltages are not applied to the USB Port or to the JACK socket, the 5 V socket can be even used to power Arduino directly, if having an external stabilized 5 V source. One has to consider that, in general, regulators do not like voltages being applied to their output, but in this particular case this situation turns out to happen even when powering Arduino from the USB port, therefore we may assume that the designers judged this problem as harmless. Even in this case there is no form of protection, since both the diode and the PTC fuse are found above this socket and thus they do not have any active function. As in the case of the Vin socket, the voltage negative pole can be found on the board’s GND sockets.

NOTE: regardless of the input used, Arduino has a 3.3 V output socket to power loads operating at this voltage; in fact a second regulator, right for the purpose of generating 3.3 V, is directly connected to the 5 V. This socket cannot be used as input.

 

CONFLICTS MANAGEMENT

Arduino is provided with a comparison circuit that controls a type P MOSFET; if a tension is found on Vin (powering from the JACK or from the Vin socket), the MOSFET is interdicted and the possible presence of voltage coming from the USB port is ignored; in the opposite case, the MOSFET will connect the USB port’s 5 V to the 5 V socket, hence below the regulator, thus powering Arduino.

 

Fig10

Management circuit of the power conflicts

 

Therefore it is clear that if you apply the voltage to the USB port and an external source to the JACK socket at the same time, it will be this last one to power the circuit, while the USB connection will keep working for the data exchange with the computer and no longer as a power source. We remind that in both cases the 5 V socket cannot be used as input, but only as output.

 

THE CHOICE OF THE INPUT

Having now a clearer picture on the subject of the power sources and the various inputs offered by Arduino, it is necessary to decide which of the latter should be used for each specific project. The choice must obviously be made on the basis of the source available, but also on the basis of the external peripherals to be powered.

It must be noticed that, as regards the current delivered, it is important that the source is capable of making it available for as much as needed by the maximum load, to be increased by about 20%, in order to avoid that the said source works at the limits; it then has no importance if the increase is by 50% or even 100% greater; in fact if the power supply is capable of delivering 2 A and the load required is only 100 mA (thus 20 times less), there is no risk to damage things, since the residual power quantity will simply remain “available”.

On the other hand, it is extremely dangerous not to take the voltage into account, since it has never to exceed the limits provided or allowed; for example for no reason it will be possible to apply voltages exceeding the 5 V socket even by a single Volt, since the board’s integrated circuits would burn immediately!

1 – USB Port: this one is handy for experimenting with small loads, requiring 5 V, since it enables the dual function of powering and programming the board; the power limit imposed by the PTC fuse is 500 mA, and actually, these components tolerate up to almost twice the value before a protective intervention, but it is better to consider the nominal value; the polarity on the USB socket is a standard one and thus does not cause problems;

 

Fig11

Powering Arduino by means of USB Port

 

2 – JAPAN JACK Port: in general, one resorts to this port to increase the power availability on the 5 V (within the limits allowed by the regulator) and/or to have available a voltage greater than 5 V, in order to power external loads. For example, if you have to power a 12 V relay, Arduino’s pin alone is not enough, but it can be used to pilot a transistor that will bring, as a conductor, the 12 V needed by the relay. In this case a 12-12,5 V voltage is applied to the JACK socket, Arduino’s board is powered by the regulator’s 5 V and from the Vin socket it is possible to draw 12 V to send to the relay (by means of an appropriate circuital configuration); the positive pole must be applied to the JACK’s central pin, the negative pole to the external one;

 

Fig12

Powering Arduino by means of a JAPAN JACK socket

 

3 – Vin socket: as said before, this one can be useful as input if an external voltage is needed and you only have 6 V available, in fact the Vin socket bypasses the protection diode and the regulator may operate properly; or it may be useful to draw the voltage coming from the JACK socket; considering the fact that the Vin socket is unprotected, its usage by the unexperienced is definitely not advised. The positive pole must be connected to the Vin socket, the negative one to the GND. In figure you can see Arduino powered via the Vin socket on the left, while on the right it is powered by means of the JAPAN JACK socket and from the Vin the voltage to light a LED is drawn.

 

Fig13

The Vin socket used as input or as output

 

4 – 5 V socket: even in this case it should be preferable to resort to drawing rather than to inputing voltage, given the enormous risks that are taken when missing protections; one of the possible situations in which this socket comes in handy is the one of having a stabilized 5 V power source but without a USB jack; as previously seen it is necessary to apply at least 7 V to the JAPAN JACK socket and at least 6 V to the Vin socket, thus this socket is the only one capable of accepting 5 V exactly. Going back to the relay example, if having the availability of a model operating at 5 V, but that requires a greater power than the one delivered by one of Arduino’s pins (that cannot exceed 30-35 mA), even here the problem would be solved very well with a transistor and by drawing 5 V from this socket. The positive pole must be connected to the 5 V socket, the negative to the GND.

 

Fig14

The 5 V socket used as input or as output

THE LIMITS OF THE CURRENT

Let’s start by remembering that you cannot pretend to power a load requiring a certain current, without the source being capable of delivering it, and that any load draws the power it needs and not the available one. Let’s see some examples, assuming that Arduino will draw the maximum possible (200 mA), the rest is then absorbed by the external components:

a – Global current consumption of 400 mA; in this case it is possible to power everything via USB, on the condition that the computer’s port (or the power supply with USB output, used as its substitute) is capable of delivering all the 500 mA considered as maximum limit;

b – Global current consumption of 600 mA; in this case it is NOT possible to power the circuit via USB since we saw that the limit set by the PTC protection fuse is of about 500 mA; we have then to resort to an external source applied to the JACK port, one that is capable of guaranteeing a current that is greater than the one required by at least 20-30%, thus for a total of at least 600-700 mA, and as stated before the exceeding current available is not used. The voltage for the peripherals can be drawn from the 5 V pin. As already seen, however, the USB connection may be kept for the programming of the micro or for the usage of the serial monitor.

c – Let’s see the case in which the total drawing is 1A; even in this case we have to resort to an external voltage to be applied to the JACK, but as we will see in the next paragraph we are operating at the extreme limit of the regulator, thus it will be needed to separate Arduino’s powering from the one of the external loads.

In the case in which there are no peripherals requiring a voltage greater than 5 V, for example 12 V, it is needed to resort to an external power supply, applied to the JACK socket, but to understand how to draw the two voltages one must always assess the currents drawn by Arduino and the 5 V and 12 V loads. Let’s see some examples:

d – Let’s see the case of Arduino (200 mA), with 5 V (50 mA) peripherals and 12 V (300 mA) peripherals; by applying a 12 V power supply with at least 1 A maximum current, the limits of the regulator (that we will see in the next paragraph) enable us to power Arduino and its 5 V and the 5 V peripherals; as regards the 12 V peripherals, on the other hand we could draw that voltage from the Vin pin;

e – Let’s see the case of Arduino (200 mA), with 5 V (300 mA) peripherals and 12 V(1A) peripherals; by applying a 12 V power supply with at least 2 A maximum current, the limits of the regulator (that we will see in the next paragraph) will impose to power Arduino alone with its 5 V, while it will not be possible to use the Vin pin (see following NOTE), at this point it a different solution should be found.

NOTE: let’s consider another factor, this time concerning the Vin pin; apparently there should not be limits of deliverable current, in addition to the one imposed by the applied power supply; however all the current will have to flow within the protection diode, that is anyway quite sturdy, but de facto one has to consider that the copper track, that connects the regulator’s input to the Vin pin placed on Arduino’s POWER header, is not very thick and consequently may not endure high currents, as it would risk burning.

 

THE REGULATOR’S LIMITS

We now have to face the problem of the power the regulator has to dissipate; by reading the specifications on the data-sheet  of the NCP1117ST50T3G regulator in the SOT-223 case (the one used on Arduino UNO r3) it can be seen that the maximum operating temperature is 150°C (being a “maximum rating” value one should keep himself at about 20% under it, thus let’s consider 120°C); it can also be read that the regulator reaches a temperature of 67°C for each Watt to dissipate, thus we can reasonably consider a maximum power to be dissipated of about 2W (actually the formula on the data-sheet calculates 1,87W at 25°C). We have already seen how to calculate the power by means of formulae; by opportunely moving the terms we can calculate the maximum deliverable power: for example I = W / (Vin-Vout). Let’s see some examples:

– 12 V Power Supply: I = 2 / (12-5) = 2 / 7 = 285mA

– 9V Power Supply: I = 2 / (9-5) = 2/4 = 500mA

– 7 V Power Supply: I = 2 / (7-5) = 2/2 = 1A

These calculations do not take into account the fall on the input diode, but are however based on a power that is greater than the advised one, thus we may consider them to be reasonable. It can be clearly inferred how it can be definitely preferable to apply the lowest power possible to the regulator.

In the previous “b” example, in which 600mA were needed, it can be well understood h now how voltages greater than 8V cannot be applied to the JACK, while in the “c” example we are definitely at the limits, even applying 7 V at the input, thus in this case we cannot think to make all the current flow through the regulator, but a different system has to be thought of; the same goes for the “e” example, while we have seen that the “d” example lends itself to the usage of a single internal power.

 

POWER SOURCES THAT ARE EXTERNAL TO ARDUINO

In the previously seen examples, we verified possibilities that go beyond the limits of the internal regulator and even of Arduino’s tracks; in these cases a possible solution is the one to create an external board that makes available a series of outputs to power both Arduino and the external peripherals operating at 5 V or other voltages (typically 9 V or 12 V).

– Let’s consider the “c” case: 5 V 1 A are needed, since 200 mA are allocated to Arduino and 800 mA to the 5 V peripherals; for example there can be a 9 V source with a deliverable power that has to be about 20-30% more, for example a 9 V 1,5 A or 2 A regulated power supply; it will be enough to create a small board with an input that is compatible with the power supply jack, below it uses a 5 V regulator (for example the classic 7805 with a TO-220 case and the typical four capacitors), whose exit will go to power the external 5 V peripherals; the 9 V from the external power supply will be brought as output as well and will be connected to a JACK pin for Arduino’s socket.

 

Fig15

High power consumption 5 V circuit plan

 

– Let’s consider the “e” case: 5 V 500 mA are needed (200 mA are allocated to Arduino and 300 mA to the 5 V peripherals), and 12 V 1 A by the 12 V peripherals; for example there can be a 12 V source with deliverable power of at least 2 A; it is enough to create a small board with an input being compatible with the power supply jack, below a 5 V regulator is used (for example the previously seen 7805), whose exit will go to power the external 5 V peripherals; the external power supply’s 12 V will be brought as output as well and split on two sockets: one to be connected to a JACK pin for Arduino’s socket and the other one to be connected to the 12 V peripherals.

 

Fig16

High consumption 5 V and 12 V circuit plan

NOTE UPON ARDUINO YÚN

In conclusion of this article, let’s leave a particular note concerning Arduino YÚN, given that, even if requiring 5 V, it has a powering system that differentiates it from all the other boards. Since it does not have a power regulator on board, it can be powered exclusively with regulated 5 V power sources:

  1. by means of its micro-USB port;
  2. by means of the Vin pin, to which we need to supply 5 V exactly, just because a power regulator below is missing.

 

Fig17

How to power Arduino YÚN

 

Finally, we have to keep in mind that, on the contrary of other Arduino boards, YÚN cannot be powered by the 5 V pin on the lateral header. In fact, as it can clearly be seen on the original electric plan (pag. 5) on the 5 V pin, Arduino YÚN has a diode (D9) that allows the current to flow only as an output.

 

From the store

Arduino YUN

Arduino UNO R3

Starter kit with Arduino UNO – Basic Level


quadcopter in one inch

$
0
0

https://hackaday.io/project/7947-quadcopter-in-one-inch

one inch flying machine
10 DOF IMU, motor drivers, and 32bit ARM CPU.
  • FAA registration?

    12/15/2015 at 02:440 commentsfully assembled with battery, the device weighs 23.5 grams.

    making it exempt from the FAA’s new registration requirements.

  • oops…

    11/13/2015 at 05:362 comments

    I have a feeling this project will require a lot of ceiling paint…

  • test flight

    11/13/2015 at 05:361 comment


Viewing all 759 articles
Browse latest View live