SquareWear Programming Reference 1.0 Oct 10, 2012

Similar documents
Introduction to Embedded Systems

Arduino Uno R3 INTRODUCTION

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

Arduino Prof. Dr. Magdy M. Abdelhameed

Programming Microcontroller Assembly and C

1 Introduction to Computers and Computer Terminology Programs Memory Processor Data Sheet Example Application...

PIC Microcontroller Introduction

Introduction to Microcontroller Apps for Amateur Radio Projects Using the HamStack Platform.

INTERRUPTS in microprocessor systems

MPLAB SIM. MPLAB IDE Software Simulation Engine Microchip Technology Incorporated MPLAB SIM Software Simulation Engine

Lab 01 Arduino 程式設計實驗. Essential Arduino Programming and Digital Signal Process

ESPino - Specifications

keyestudio Keyestudio MEGA 2560 R3 Board

ECGR 4101/5101, Fall 2016: Lab 1 First Embedded Systems Project Learning Objectives:

Introduction to Arduino. Wilson Wingston Sharon

Contents. The USB Logic Tool... 2 Programming... 2 Using the USB Logic Tool... 6 USB Logic Tool Features... 7 Device Hardware...

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING. EE Microcontroller Based System Design

12.1. Unit 12. Exceptions & Interrupts

Arduino Uno. Arduino Uno R3 Front. Arduino Uno R2 Front

MEDIS Module 2. Microcontroller based systems for controlling industrial processes. Chapter 4: Timer and interrupts. M. Seyfarth, Version 0.

Ali Karimpour Associate Professor Ferdowsi University of Mashhad

Infineon C167CR microcontroller, 256 kb external. RAM and 256 kb external (Flash) EEPROM. - Small single-board computer (SBC) with an

Manual of Board ET-PIC STAMP 18F8722-K22 ET-PIC STAMP 18F8722-K22

I Introduction to Real-time Applications By Prawat Nagvajara

Ali Karimpour Associate Professor Ferdowsi University of Mashhad

FIFTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLOGY-MARCH 2014 EMBEDDED SYSTEMS (Common for CT,CM) [Time: 3 hours] (Maximum marks : 100)

CONTENTS. dspicpro4 KEY FEATURES 4 CONNECTING THE SYSTEM 5 INTRODUCTION 6

EDBG. Description. Programmers and Debuggers USER GUIDE

Network Embedded Systems Sensor Networks Fall Hardware. Marcus Chang,

1 Introduction to Computers and Computer Terminology Programs Memory Processor Data Sheet... 4

MCU: Interrupts and Timers. Ganesh Pitchiah

ARDUINO LEONARDO WITH HEADERS Code: A000057

Introduction to Microcontrollers Using Arduino. PhilRobotics

ARDUINO YÚN Code: A000008

MICROPROCESSOR BASED SYSTEM DESIGN

The Atmel ATmega168A Microcontroller

Lab Course Microcontroller Programming

AVR Microcontrollers Architecture

ARDUINO LEONARDO ETH Code: A000022

ARDUINO MEGA INTRODUCTION

Embedded Systems. PIC16F84A Internal Architecture. Eng. Anis Nazer First Semester

USER GUIDE EDBG. Description

Software debouncing of buttons

Part 1 Using Serial EEPROMs

ARDUINO MEGA 2560 REV3 Code: A000067

PIC16F87X. 28/40-pin 8-Bit CMOS FLASH Microcontrollers. Devices Included in this Data Sheet: Pin Diagram PDIP. Microcontroller Core Features:

Department of Electronics and Instrumentation Engineering Question Bank

ARDUINO YÚN MINI Code: A000108

Application Note, V1.0, Jul AP XC16x. Interfacing the XC16x Microcontroller to a Serial SPI EEPROM. Microcontrollers

INTERFACING HARDWARE WITH MICROCONTROLLER

ARDUINO UNO REV3 SMD Code: A The board everybody gets started with, based on the ATmega328 (SMD).

Breeze Board. Type A. User Manual.

CN310 Microprocessor Systems Design

PICAXE X2 Product Briefing.

8051 Microcontroller

Microcontrollers and Interfacing week 8 exercises

Embedded programming, AVR intro

Embedded systems. Exercise session 3. Microcontroller Programming Lab Preparation

Color 7 click. PID: MIKROE 3062 Weight: 19 g

The Atmel ATmega328P Microcontroller

EE4390 Microprocessors. Lessons 2, 3 68HC12 Hardware Overview, Subsystems, and memory System

Centre for Instrumentation, Control and Automation User s Guide to the MAD 2 Microcontroller Board

PIC-LCD-3310 development board Users Manual

Understanding the basic building blocks of a microcontroller device in general. Knows the terminologies like embedded and external memory devices,

The MC9S12 Timer Output Compare Function Making an event happen at specific time on the HC12 The MC9S12 Output Compare Function

More Fun with Timer Interrupts

ATmega Interrupts. Reading. The AVR Microcontroller and Embedded Systems using Assembly and C) by Muhammad Ali Mazidi, Sarmad Naimi, and Sepehr Naimi

Capturing the Time of an External Event Input Capture Subsystem


Developing Reusable Device Drivers for MCU's

Seeeduino LoRaWAN. Description

Microcontroller. BV523 32bit Microcontroller. Product specification. Jun 2011 V0.a. ByVac Page 1 of 8

DPScope SE Programming Interface Description

Microcontrollers. Microcontroller

ARDUINO UNO REV3 Code: A000066

Reprinted by permission of T&L Publications Inc. Copyright 2001 USB MICROCONTROLLERS FOR THE MASSES

Functional block diagram AD53x1 (Analog Devices)

Introduction to ARM LPC2148 Microcontroller

Microcontroller basics

ARDUINO PRIMO. Code: A000135

C Language Programming, Interrupts and Timer Hardware

Explanation of PIC 16F84A processor data sheet Part 1: overview of the basics

ARDUINO MICRO WITHOUT HEADERS Code: A000093

M68HC08 Microcontroller The MC68HC908GP32. General Description. MCU Block Diagram CPU08 1

ArdOS The Arduino Operating System Quick Start Guide and Examples

Layman definition: Gadgets and devices Technical definition: Self-controlled devices Usually, such systems consist of I/O (input/output) devices such

CPU ONE PLC PLC USER S MANUAL

acret Ameya Centre for Robotics & Embedded Technology Syllabus for Diploma in Embedded Systems (Total Eight Modules-4 Months -320 Hrs.

EasyPIC5 Development System

AVR XMEGA Product Line Introduction AVR XMEGA TM. Product Introduction.

Internet of Things: Using MRAA to Abstract Platform I/O Capabilities

Display Real Time Clock (RTC) On LCD. Version 1.2. Aug Cytron Technologies Sdn. Bhd.

C Language Programming, Interrupts and Timer Hardware

IDUINO for maker s life. User Manual. For IDUINO Mega2560 Board(ST1026)

Freescale Semiconductor, I

ARDUINO MEGA ADK REV3 Code: A000069

Lecture (02) PIC16F84 (I)

Hello, and welcome to this presentation of the STM32L4 power controller. The STM32L4 s power management functions and all power modes will also be

Laboratory 10. Programming a PIC Microcontroller - Part II

Exen Mini. Setup Guide - V1. nerdonic.com

Transcription:

Content: 1. Overview 2. Basic Data Types 3. Pin Functions 4. main() and initsquarewear() 5. Digital Input/Output 6. Analog Input/PWM Output 7. Timing, Delay, Reset, and Sleep 8. USB Serial Functions 9. Timer Interrupt 10. Push-button Interrupt 11. External Interrupts 12. Hardware PWM Function 13. EEPROM Functions 14. USART Functions 15. I2C and Flash Functions SquareWear Programming Reference 1.0 Oct 10, 2012 1. Overview SquareWear v1.1 is based on Microchip's PIC18F14K50 microcontroller running at 12MHz. It has 16KB program space, 768B RAM, and 256B EEPROM. The software program is built on MPLAB X IDE with C18 compiler for PIC18. The SquareWear library builds upon C18's peripheral library (plib), which comes with the installation of C18 compiler. The SquareWear library implements a number of high-level functions to accommodate common prototyping need and abstract away low-level details. If needed, you can call plib functions directly to access all available peripheral functions (please refer to C18's documentation for details). Additional Resources: Microchip MPLAB C18 Peripheral Library Documentation (installation folder) Microchip MPLAB C18 User Guide Microchip MPLAB IDE User Guide (installation folder) Microchip MPLAB C18 Getting Started Guide (installation folder) 2. Basic Data Types The basic data types are: char: signed, 8-bit byte: unsigned, 8-bit (equivalent to unsigned char) int: signed, 16-bit uint: unsigned, 16-bit (equivalent to unsigned int) long: signed, 32-bit ulong: unsigned, 32-bit (equivalent to unsigned long) float: 32-bit floating point

As in standard C programming language, you can define structure, union, bit field, array etc. Please refer to the MPLAB C18 User Guide for the complete list of data types. 3. Pin Functions SquareWear 1.1 has 8 general I/O pins, and 4 additional output-only pins that function as power sinks. Among the 8 general I/O pins, 6 can be used as analog input; in addition, 2 among them can be used for external interrupts, 1 for hardware PWM, 2 for I2C (SDA/SCL), and 2 for USART (TX/RX). Software PWM is supported on all Port C pins. The on-board LED is internally wired to pinc7, and the on-board push-button is internally wired to pina3 (input-only pin). The push-button can be used as a general-purpose button; it is also used to trigger software reset and enter programming mode following reset. Pin Name and Function Table: Pin Name Basic Function Analog Input Other Functions Soft. PWM Notes pinc0 general I/O pinadc4 - yes pinc1 general I/O pinadc5 ext. interrupt INT1 yes pinc2 general I/O pinadc6 ext. interrupt INT2 yes pinc3 general I/O pinadc7 - yes pinc4 power sink only - - yes pinc5 power sink only - hardware PWM yes pinc6 power sink only - - yes pinc7 power sink only - - yes on-board LED pinb4 general I/O pinadc10 SDA (I2C) - pinb5 general I/O pinadc11 RX (USART) - pinb6 general I/O - SCL (I2C) - pinb7 general I/O - TX (USART) - pina3 input only - - - on-board push-button Note that since some pins can be used for analog input, you need to refer to the analog name when accessing the analog functions. For example, pinc0 is also pinadc4. You should use pinc0 for accessing digital functions, and pinadc4 for accessing analog functions. 4. main() and initsquarewear() Functions As in standard C, your program must have a main() function, which is the entry function to your program. Also, you must include SquareWear.h, and, at the beginning of the main function, you must call initsquarewear() first in order to properly set up SquareWear and the necessary timers. Your program generally should look like this: #include SquareWear.h // user functions // void main(void) { InitSquareWear(); //

5. Digital Input / Output void setmodeoutput(byte pinname); Set up a pin as digital output. Example: setmodeoutput(pinb4); Upon initialization, all port C pins will be set as output pins by default. void setmodeinput(byte pinname); Set up a pin as digital input. Example: setmodeinput(pinb4); void setvalue(byte pinname, byte value); Assign a value (0 or 1) to a digital output pin. Example: setvalue(pinb4, 1); Note that the same function can be used to set value to a PWM output pin, as described in the next section. uint getvalue(byte pinname); Return the value from a digital input pin. Example: getvalue(pinb4); Return value will be 0 or 1. Note that the same function can be used to get value from an analog input pin, as described in the section below. Direct Access of Pin Values In addition to using the setvalue and getvalue functions, you can also directly access pin values by using pin aliases. There are two types of pin aliases: one is pre-fixed with 'port', such as portc3. For example, Similarly, portc3 = 1; is equivalent to setvalue(pinc3, 1); a = portb4; is equivalent to a = getvalue(pinb4); The other type of alias is pre-fixed with 'lat', such as latc3. This should be used on read-modify-write operations, for example: latc7 =!latc7; toggles pinc7 and is equivalent to setvalue(pinc7,!getvalue(pinc7)); These direct access functions are much faster than calling the setvalue and getvalue functions. You should use them as often as you can. pinc7 pinc7 is internally wired to the on-board LED. Whenever it's set to high, the LED will light up. pina3 pina3 is internally wired to the on-board push-button. You can check the button status by reading porta3. The return value is 1 if the button is released (pulled high); and the value is 0 if it's pressed. You can also use the function: bool buttonpressed(); to check the button status. It returns 1 (logic high) if the button is pressed, and 0 (logic low) if the button is released. pinc4 pinc7 These four pins are internally connected to on-board MOSFETs and they function as power sinks. The typical way of

using them is to connect the positive end of a component (such as an LED) to Vdd (Source), and the negative end to a power sink pin. This way, by sending setting the pin to 1 or 0 you can turn on or turn off the component. Because of the way they are set up, these 4 pins are only used as digital output or PWM output they do not work as input pins. 6. Analog Input / PWM Output void setmodeadc(byte pinname); Set up a pin as analog input. Example: setmodeadc(pinadc4); As described above, here you must use the analog pin names, even though they are physically the same as the digital pins. For example, pinadc4 is physically the same as pinc7. You need to use the name pinc7 for setting it up as digital input or output, and pinadc4 for setting it up as analog input. uint getvalue(byte pinname); Return the value from an analog input pin. Internally this function performs an analog-digital conversion (ADC) and returns a value in the range from 0 to 1023 (10-bit). As described above, if the pinname is given as a digital pin name, the return value will be binary (0 or 1). Pulse-Width Modulation (PWM) Output PWM is a method to simulate analog output (i.e. values in between digital high and low) by producing a highfrequency digital signal and adjusting its duty cycle (i.e. the time share of digital highs). SquareWear supports software PWM output on all Port C pins (pinc0 to pinc7). void setmodepwm(byte pinname); Set up a pin as PWM output. Example: setmodepwm(pinc7); Again, this only works on the eight Port C pins. void setvalue(byte pinname, byte value); Assign a value, between 0 and 31 (5-bit) to a PWM output pin. So the PWM resolution is 32 grades (0 is equivalent to digital low or 0V, and 31 is equivalent to digital high or Vdd). The software PWM works by generating a high-frequency timer interrupt, and at each cycle adjusting the digital output based on the desired duty cycle (value). For example, for duty cycle of 50%, the digital signal will be Vdd (high) half of the time, and 0 (low) the other half of the time. So on average the output value is about 50% of Vdd. SquareWear generate software PWM at 183Hz frequency. This is not high, but sufficient to avoid LED flickering. If you want higher frequency PWM, you should use the hardware PWM. Hardware PWM is much faster, but a microcontroller typically only has a small number of pins that support hardware PWM. In comparison, software PWM is more flexible and can be simulated on any digital pins. 7. Timing, Delay, Reset, and Sleep Functions ulong millis(); Return milliseconds that has passed since the start of the program.

void delaymicroseconds(int us); void delaymilliseconds(int ms); void delayseconds(int seconds); Delay the specified amount of microseconds, milliseconds, or seconds. void opensoftwarereset(); void closesoftwarereset(); Software reset is a feature where if you have pressed the on-board push-button for more than 5 seconds, it will trigger a reset and bring the microcontroller to programming mode. This feature is turned on by default. It is implemented by using a timer interrupt to periodically check the button status, so it does not interfere with or stall your main program. void idlesleep(); void deepsleep(); These two are sleep functions that can help reduce the microcontroller's energy consumption and save power. In idlesleep, the mcu's clock source continues running, so the time keeping functions work as usual, and all timer interrupts are triggered as usual. The mcu will return back to normal execution upon interrupt events, such as button interrupt, timer interrupt, or external interrupts. In deepsleep, the mcu's clock source will stop running, so all time-related functions will stop working. The only way to wake up the mcu is by using button interrupt or external interrupts (which do not rely on timers). This is useful to put the mcu to minimal power state. You can combine it with button interrupt or external interrupts to allow the mcu to run over a long time without draining the battery. 8. USB Serial Functions SquareWear's built-in USB module can be used to create a USB Serial (CDC) port in order to perform serial communications with a computer. This does not require any external USB Serial cable. void openusbserial(); Open the USB serial port. If a USB cable is plugged in, your operating system should automatically detect the USB Serial device (CDC) after this function is called. On Linux or Mac, you do not need any driver. The system automatically detects the device and it should appear as /dev/ttyacmx in Linux or /dev/ttyusbserial.x in Mac (where x is system assigned number). In case it appears as /dev/ttyusbx in Linux, you can unplug the USB, run 'sudo rmmod ftdi_sio' and replug in the USB until it shows up as /dev/ttyacmx. On Windows, you need to install the CDC device driver, available in the inf/ folder under the uploaders/ directory. Once installed, the device should appear as COMx port (where x is a system assigned number). void putsusbserial(char *string); Output a string (array of chars) to USB Serial. Example: char msg[]= hello ; putsusbserial(msg); msg[0]='h'; putsusbserial(msg);

void putrsusbserial(const rom char *string); Output a constant string to USB Serial. Example: putrsusbserial( hello ); Note the extra 'r' in the function name. This differs from the previous function in that you must provide a constant string, not an array of chars. In MPLAB C18, any string in double quotes are compiled as constant string, and is placed in program memory space, not in RAM. In contrast, an array of chars is placed in RAM. So you need to be careful which function to use. Examples: char msg[]= Hello ; putsusbserial(msg); putrsusbserial( World! ); void putnusbserial(char *string, byte n); Output the first n characters of the string to USB serial. void getusbserial(char *string, byte n); Read a maximum of n characters from USB serial port. The parameter 'string' is a char array of size at least n. void pollusbserial(); This function polls and processes pending USB tasks. Since it's not based on a timer interrupt, it MUST be called as often as you can in your program, otherwise the USB Serial connection will be lost. Example: void main(void) { initsquarewear(); while(1) { pollusbserial(); Read/Write Numbers Although the USB Serial functions cannot directly read or write numbers, you can use standard C's functions (from <stdlib.h>) to convert numbers to and from strings. For example, itoa(number, string) converts an integer to string, and atoi(string) does the reverse. Similarly, ltoa and atol handle long integer and string conversions; atof handles string to double conversion. There is no ftoa function, but you can use the sprinf() function (from <stdio.h>) instead. Serial Monitor In order to perform serial communication, you need to run a serial monitor on your computer. First of all, you can use the serial monitor built-in to Arduino or Processing they are both cross-platform. Alternatively, On Linux, you can use putty or gtkterm. The typical serial port number is /dev/ttyacm0 but the actual port number may be different. You need to run the serial monitor in sudo, or alternatively add the device vendor and id (04d8:000a) to your /etc/udev/rules.d/ On Mac, you can use screen or stty. The typical serial port number is /dev/ttyusbserialxxx. On Windows, you can use putty. The typical serial port number is COMx.

9. Timer Interrupt SquareWear's library internally uses several timer interrupts to implement time keeping, PWM, and software reset. In addition, you can define a custom timer interrupt to perform periodic tasks without stalling your main loop. void opentimerinterrupt(ulong ms, isr_handler callback); This function opens custom timer interrupt function. The parameters are trigger interval (in milliseconds), and callback function. Once opened, the callback function will be executed regularly at the trigger interval. The callback function must be of type void function_name(void). In other words, it does not take any parameter and does not return any value. Example: void blink(void) { latc7 =!latc7; // toggle on-board LED void main(void) { initsquarewear(); opentimerinterrupt(500, blink); while(1) { pollusbserial(); This toggles pinc7 (hence the on-board LED) every 500 milliseconds, while the main loop performs other tasks. Note 1: Because an interrupt will temporarily pause the main execution path, you should keep the callback function as short as possible. A long callback function will cause significant delay on the main execution path and should be avoided. Note 2: If you will be changing any global variable in your callback function, you must declare the variable as volatile. This tells the compiler that the variable is subject to change inside an interrupt function. Example: volatile uint counter; void count(void) { counter++; // increment counter value void main(void) { initsquarewear(); opentimerinterrupt(500, blink); while(1) { pollusbserial(); void closetimerinterrupt(); Disable custom timer interrupt function.

10. Push-button Interrupt Push-button interrupt allows a callback function to be executed whenever the on-board push-button has a state change, i.e. either pressed or released. void openonboardbuttoninterrupt(isr_handler callback); Open on-board button interrupt. Again, callback function is a function that neither takes parameters nor return a value. Follow the same rules as timer interrupt with regard to the length of the callback function and volatile variables. As described previously, button interrupt can be used to wake up the mcu from deep sleep mode. This way, whenever the button is pressed, the mcu will resume from sleep and perform some tasks, such as displaying an LED pattern. Then after a while it goes to deep sleep again. This allows you to keep the controller on for a very long time without draining the battery. void closeonboardbuttoninterrupt(); Disable push-button interrupt. 11. External Interrupts External interrupt is triggered by state change on a specific digital input pin. SquareWear library allows two external interrupts: INT1 and INT2. They correspond to pinc1 and pinc2. void openextinterrupt(byte index, byte mode, isr_handler callback); Open external interrupt. The input parameters are: index (1 or 2), mode (RISING or FALLING), and the callback function. RISING means the interrupt is triggered when the input signal rises from low to high; and FALLING means the reverse. External interrupt is useful for applications such as counting the number of pulses. It can also be used to wake up the mcu from deep sleep. For example, you can use an external 1Hz square wave to wake up the mcu once per second from deep sleep. void closeextinterrupt(byte index); Close external interrupt 1 or 2. 12. Hardware PWM Compared to software PWM, hardware PWM has higher frequency and precision (10-bit). On the other hand, it is limited to a small number of pins. SquareWear support one hardware PWM on pinc5. void openhardwarepwm(); Void sethardwarepwmduty(uint duty); void closehardwarepwm(); The hardware PWM runs at 11.8kHz frequency, and allows a precision of 1024 steps (10-bit). So duty can be anywhere from 0 to 1023.

13. EEPROM Functions EEPROM is a common type of non-volatile memory. It is used to store and preserve values over power loss. SquareWear has 256 bytes of EEPROM. void writeeeprom(uint addr, byte data); Void busyeeprom(); byte readeeprom(uint addr); In these functions, addr is the EEPROM address (0 to 255), and the data to read/write is a byte (8-bit). The first time you call any EEPROM read/write function, make sure there is at least a couple hundred milliseconds of delay since the start of the program, in order for the EEPROM unit to stabilize. The busyeeprom function is used to wait for an EEPROM write to complete. So you should usually call it after each writeeeprom, or at least call it before the next readeeprom. 14. USART Functions USART is used for serial communication. In contrast to USB Serial functions, USART requires an external serial cable, such as FTDI cable, so it's less convenient. On the other hand, its implementation is much simpler and so it takes less program memory space. On SquareWear, the USART pins are pinb5 (RX) and pinb7(tx). To use USART, you need to connect the TX and RX pins on your serial cable to the RX and TX pins respectively. Then open a serial monitor to perform the serial communication. void openusart(); Void closeusart(); void putsusart(char *data); void putrsusart(const rom char *data); Void getusart(char *data, byte len); These functions are equivalent to the USB Serial functions. Please refer to the USB Serial functions for usage. 15. I2C and Flash Functions I2C is a technique that allows two devices to communicate data to each other via only two pins (SCL and SDA). Since the I2C functions provided by the MPLAB peripheral library (plib) is sufficiently high-level, SquareWear library does not need to implement any wrapper functions for them. Please refer to the plib documentation for instructions. The peripheral library also contains functions to read and write the microcontroller's flash memory. Unlike the Arduino, Microchip mcus allow you to write flash memory at run-time. This way you can use flash memory as nonvolatile memory (in addition to EEPROM), or use it as extra (but slow) RAM space. Again, the plib functions are sufficient high-level. Please refer to the plib documentation for instructions.