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

remotework.in – React and ES6 by example Meteor.js

$
0
0

remotework.in – React and ES6 by example

If you’ve followed the news about Meteor 1.2 you may came across React.js and ECMAScript 2015 (formerly ECMAScript 6) which will play a huge role in the 1.2 release and the future of Web development in general.

Today I want to show you a project I’ve started a few days ago which is open source and should make it easier to get started with Meteor, ES6 and React.

I could post some code snippets here and go through the code but I think that there are already some great tutorials out there (see “Additional Resources” below) which just do that.

I read a lot of source code on GitHub and I think that reading others source code is a great way to learn some new patterns and concepts. It’s even better if you can play with the application in production so you can see what action on the site triggers what functionality in the code.

So today I want to show you the project remotework.in. The Source Code can be found on GitHub.

Bildschirmfoto 2015-09-08 um 07.19.33

What is this project about?

As a freelancing Meteor developer I often use Platforms such as Upwork, Elance,Freelancer and We Work Meteor (which is an awesome platform if you want to find Meteor related jobs).

However, I’m always looking to find other JavaScript related jobs as well. I really liked the “We Work Meteor”-Approach of an easy job board where you just see the jobs and can contact the author of the job directly via Mail. But I wanted a Platform where every job can be posted (not just Meteor related jobs).

As I was already digging into ES6 and React I thought that it is time to start a project to create a remote job board with the help of those two new technologies to learn something along the way. So I started working on remotework.in / GitHub Source Code.

The functionality

The whole development process was focused on the creation of an easy to use job board.
There are no sign-ups or sign-ins for anyone. Just post a job or search for a new job. That’s it.

As a job poster you just enter the information about your job offer and hit save.
After that you get an E-Mail right into your inbox.
This E-Mail contains three links.
One to activate your job posting (after that it’s activated and will be visible to others), a second to edit your job posting and a third which makes it easy to remove your job posting. You should keep this E-Mail as it’s the only way to edit / remove the job posting later on.

As a job seeker you just browse through the jobs or search for specific jobs (the title and description of the job will be searched with the help of the MongoDB fulltext search).
Just click on the E-Mail Address and contact the job author if you think the job suits you.

The source code

Here’s the source code to the project. Feel free to send me sone PRs so we can improve it together.
You may look through the commits to see the history of the projects creation.

One thing at the end

I would be happy if you could maybe spread the love and share the job platform so that we can stress test it (if you know what I mean). :-)

Additional resources

Here are some blog posts about ES6, React and Meteor. You should definitely read them if you want to dig deeper into these topics.



ANALYSING 433 MHZ TRANSMITTERS WITH RTL-SDR

$
0
0

ANALYSING 433 MHZ TRANSMITTERS WITH RTL-SDR

RTL-SDR is a good addition to the arsenal of any hardware geek and this holds true for hardware security researchers too. Recently I did a talk at HITB Amsterdam (http://www.slideshare.net/yashinm/sniffing-the-airwaves-with-rtl-sdr) where I explained how the RTL-SDR was useful and how it can be leveraged for security applications.  With this blog post I intend to demonstrate how the RTL-SDR can be used to sniff 433 Mhz transmitters. These are pretty cheap and can be found in a lot of appliances including alarm sensors. This post is also intended to be an intro to RTL-SDR usage. I suggest you get Kali linux (1.0.6>) on your system as it has most of the dependencies required for this demo.

To show the capture of data and to simulate a transmission I’ll be using a FS1000A 433 mhz transmitter along with a Teensy to control it. These use ASK modulation.

IMG_20140618_162410-300x225

The code I used to transmit “1″ every 2 seconds:

#include <VirtualWire.h>
char *controller;
void setup() {
 pinMode(13,OUTPUT);
vw_set_ptt_inverted(true);
vw_set_tx_pin(2);
vw_setup(4000);
}

void loop(){
controller="1" ;
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx();
digitalWrite(13,1);
delay(2000);
digitalWrite(13,0);
delay(100);
}

Initially to check whether the transmitter is working correctly I used gqrx (https://github.com/csete/gqrx). It’s a SDR receiver implemented in GnuRadio and is very useful for tracking down and recording signals. The following spike is obtained every two seconds:

centre

This tells us that the transmitter is working fine . To get a good look at the signal being generated we can use rtl_sdr combined with baudline (http://www.baudline.com/download.html). rtl_sdr is a tool that comes with the rtl-sdr package (rtl_sdr is the tool and rtl-sdr is the collection. For more info: http://sdr.osmocom.org/trac/wiki/rtl-sdr). It outputs raw I/Q data. Baudline is another useful tool that can be used to visually understand signals. The following command will pipe the output of rtl_sdr to baudline for analysis:

rtl_sdr -f 433920000 -s 1000000 – | baudline -reset -samplerate 1000000 -channels 2 -format u8 -quadrature -stdin

baudline  -F1- FFT=2048 sample_rate=1000000 Hz=1X timebase=1X  _020

In most cases baudline can help you determine which modulation the transmitter is using and can be a good addition to gqrx and other receivers.

Another tool that we haven’t touched yet (at least not directly) is GnuRadio. Any serious work with software defined radio will probably include GnuRadio as it has support for a large number of devices such as the HackRF, RTL-SDR, USRP and the Funcube dongle. GnuRadio works with a block architecture: signal sources, converters, amplifiers and more are all blocks. Devices from which there’s an output of data is known as sources and blocks to which there’s only input are known as sinks. The source block for RTL-SDR gets installed when you install the rtl-sdr block. I’m using GNURadio 3.7 on Ubuntu.

To get started, open up GNU Radio Companion and from the Source section drag the “RTL-SDR” Source to the main work area.

Double click on the newly created source and set frequency as 433920e3 (433.92 Mhz). Change the variable block samp_rate on the right so that it’s value is 96e3 (96k). Since we need to hear the transmissions we’ll need an audio sink. Choose Audio Sink from the Audio section and drop it into the work area. In the sample rate section of the sink enter “int(samp_rate)”.

-untitled - GNU Radio Companion_023

There’s a slight problem as the output of the RTL-SDR source is a complex data type and the Audio Sink accepts real datatype. GNURadio has you covered for this too! Choose a complex to real convertor from the Type Convertor section.

Join the blocks by clicking on the Out of the source and then the In of the Complex to Real convertor. Do the same for the sink. Click on the Execute button on the top of the GRC and you’ll begin to hear small pips of data every two seconds.

Now that we can access the audio stream through GRC we’ll also need to see the actual signal wave. To see the peaks in radio traffic we’ll  use a FFT sink and for saving to file, a wav file sink. Make sure you set the filename that you want to save to and the bits per sample as 8. Your GRC graph should look like this:

You can open up the file in Audacity and see the signal wave in it:

Note:Sometimes when you open up audacity you’ll notice that there’s no signal in it. This happens because when a flow graph is terminated suddenly, the wav block may not write to the file correctly. For this purpose we’ll add a dropdown box that’ll allow you to switch between the file and /dev/null. Once the recording is done you should switch to /dev/null before closing. This will ensure that the file has been written properly.

Here’s how file choosing was implemented:

However since this is a 433 mhz transmission we already have a very easy to use tool by merbanan (https://github.com/merbanan/rtl_433) that actually converts the radio signals back to data.  As the transmissions aren’t from any weather station or temperature sensor we will have to run rtl_433 with the analyse option set.  It can be clearly seen that the data exists after a sequences of “0″s.

rtl_433 -a

4331

If we change the transmission from the Arduino to a “2″ instead of “1″ we get:

4332

Stay tuned for more posts on radio hackery!


Hardware Security Resources

$
0
0

Hardware Security Resources

Here are some whitepapers and blogpapers that should help you get started/learn more about hardware security. I’ve divided the page into divisions for easier viewing.

I’ll keep adding to the list when I remember any other sites/papers that I refer to. Please let me know of any mistakes/suggestions down in the comments!

Blogs/Websites

/dev/ttys0 blog 

cybergibbons

IOActive

Natashenka’s blog

Travis Goodspeed’s blog

Michael Ossman’s blog

Hackaday

Bunnie Huang’s blog

Adafruit

Sparkfun Blog

Lacklustre Blog

Dangerous Prototypes

Adam Laurie’s blog

SRLabs

Xipiter

Chip Whisperer Documentation

Spritesmod blog

Whitepapers/Required reading

General hardware reverse engineering/ attacks

Intro to hardware hacking

Reversing a vacuum cleaner

Joe Grand’s talk on Tools of the Hardware Hacking Trade

Craig Heffner’s blogpost on identifying and using serial ports

Reverse engineering a DTV converter

Reverse engineering a router

Joe Grand: Current state of hardware hacking

LayerOne talk on hardware reverse engineering [Check the other parts too]

HW RE course at Rensselaer Polytechnic Institute. Course Material

A collection of posts by CyberGibbons on wireless burglar alarms[CyberGibbons]

Reverse Engineering a Furby

Recon talk on hardware RE

Hardware hacking for software people – Stephen Ridley

Using Shikra for UART/JTAG debugging

Reversing a home controller

Breaking a Fingerprint protected HD

Breaking a Fingerprint protected USB

Hijacking Drones

Bluetooth Low Energy

Bluetooth: With Low Energy Comes Low Security

Bypassing Passkey Authentication in Bluetooth Low Energy

NIST document on Bluetooth security

Outsmarting Bluetooth Smart

How Smart is Bluetooth Smart

Understanding BLE advertisement packets

Understanding BLE advertising packets

Introduction to BLE

Reverse engineering a BLE bulb

Bluetooth 2.0/3.0

NIST document on bluetooth security

Security in Bluetooth

Bluetooth threats (old ones)

Security Weaknesses in Bluetooth

Sniffing Bluetooth using Ubertooth by Dominic Spill

Side channel attacks

Side Channel Attacks [Good intro to SCA]

Improved Higher-Order Side-Channel Attacks with FPGA Experiments

Power Analysis for Cheapskates – Colin O’Flynn

Video for the above talk: https://www.youtube.com/watch?v=i27NiVuWmhE

ChipWhisperer documentation/ Good info on SCA

Glitching/Fault Injection

Intro to Fault Injection attacks

Writeup of how the PS3 hypervisor was attacked using glitching

Low Cost Attacks on Tamper Resistant Devices

The Sorcerer’s Apprentice Guide to Fault Attacks

Clock glitching tutorial

Vcc glitching

Fault attacks on secure chips: from glitch to flash

Glitching for noobs

Practical Analysis of Embedded Microcontrollers against Clock Glitching Attacks

Practical Attacks against the MSP430 BSL

Fault injection attacks and defences

Security Failures in Secure Devices

Firmware analysis

Firmware Analysis Writeup

Belkin WPS PIN reversing

DLINK DIR980L Firmware reversal

DLINK security failures

Reversing DLINK WPS PIN algorithm

RFID/NFC

New Attacks against RFID

RFID Security: Attacks, Countermeasures and Challenges

Attacks on RFID Protocols

NFC Attack Surface

Practical Relay Attack on Contactless Transactions by Using NFC Mobile Phones

RF Hackery

Good writeup on RF security in general

SDR attacks on smart homes

KillerBee Zigbee attack framework

Exploiting ZigBee

Penetration of ZigBee-based wireless sensor networks

Ghost-in-the-Wireless: Energy Depletion Attack on ZigBee

Decoding Train Announcement Boards

Deciphering mystery signals from a helicopter

Decoding radio controlled bus stop displays

OpenSesame attack on garage door openers

Remotely trigger doorbells

SDR tutorials by Mike Ossman

Hacking a Lego Car using HackRF

GSM/UMTS

Attacking SMS

GSM sniffing [CCC talk by Karsten Nohl]

A practical attack against GPRS/EDGE/UMTS/HSPA mobile data communications

UMTS MITM

Privacy through Pseudonymity in Mobile Telephony Systems

Location leaks on the GSM air interface

Decrypting GSM phone calls

Rooting SIM cards

Automotive security

Charlie Miller/Chris Valasek comprehensive paper on automotive security

Good writeup on CAN bus packets

Hacking into a Vehicle CAN bus (Toyothack and SocketCAN)

Books to read:

Hacking the XBox by Andrew “bunnie” Huang

http://www.amazon.com/Introduction-Hardware-Security-Mohammad-Tehranipoor/dp/1441980792

http://www.amazon.com/Android-Hackers-Handbook-Joshua-Drake/dp/111860864X/ [Good section on hardware hacking]

People to follow on twitter

Mike Ryan

Felix Domke

CyberGibbons

Jay Beale

Justin Searle

SpritesMods

Samy Kamkar

Charlie Miller

Dangerous Prototypes

Joe Grand

/dev/ttys0

Oona Räisänen

at1as

Travis Goodspeed

Michael Ossmann

Chris Valasek

Xipiter

Stephen Ridley


Particle Guides, Tutorials, Projects, Links

$
0
0

Love making things with the Particle Core and Photon? Just getting started? Either way, this page should have some links with guides, tutorials and a bunch of existing projects out there that might inspire your development adventures with the cloud connected microcontroller!

Getting Started

Useful Links

Interesting Project Tutorials

Using Particle Core with Node

Troubleshooting

Community

Looking to find the LightBlue Bean community? The best spot appears to be their Particle forums.


Where to buy electronics in Toronto?

$
0
0

Selected US/international vendors that serve Canada.

Presented in no particular order:

  1. Digi-Key. Canada-specific home page 
    •The best service. A very complete parts line-up.
  2. Mouser. Canada-specific home page 
    •Good service. A very complete line-up, probably not as many as Digi-Key, but close.
  3. Allied. Home page–you have to change the country yourself 
    •I’ve not ordered from them, but I have received a good recommendation.
  4. Arrow. The North American division 
    •I recently ordred one of their own products. Surprise extra charges from Fedex came a week later.
  5. Newark (Element 14). Canada-specific home page .
    •Full line distro, I have no recent experience with them.
  6. Sparkfun .
    •I have not ordered from them. Several Canadian suppliers distribute SparkFun items.
  7. AdaFruit .
    •I have not ordered from them. Several Canadian suppliers distribute AdaFruit items.

Canadian sources.

Presented in no particular order (the numbers exist only for reference), I’ve tried to condense all the important information into a couple of lines. I certainly have not ordered from all of them!

  1. dipmicro , Niagara Falls.
    •Web-based initially, now, as of mid 2014, a retail store has opened in Niagara Falls, no phone orders. They sell new components and some boards, e.g. Chinese Arduino clones.
  2. Spikenzie , Montreal.
    •Sell new components and many boards: AdaFruit, SparkFun and others. A few ICs only.
  3. Electrosonic .
    •One of the best things about taking EE at the University of Toronto when I did was being able to walk over to Electro Sonic at lunch! Alas they moved long ago, and they no longer list anysemi companies on their linecard. Still OK for passives, tools, instruments and Hammond cases. Despite their stock being maintained in the US I still think of them as Canadian.
  4. Active 
    •Retail stores in Toronto, Ottawa, Winnipeg, Edmonton and Calgary (no longer Vancouver). More or less full product line.
  5. Sayal , Toronto.
    •Several retail outlets in Southern Ontario. Largely surplus stock. Terrible web site with almost no prices!
  6. Cana Kit , Vancouver.
    •Sell kits and boards: their own designs as well as SparkFun and others. No components.
  7. RP Electronics , Vancouver.
    •Retail location in Vancouver. Failrly full line from books to components, to test equipment.
  8. Lee’s Electronics , Vancouver.
    •Retail location on Main in Vancouver. Wide variety of items, including some Hammond boxes. Poor web site.
  9. Creatron , Toronto.
    •Retail store on College. Wide range of parts and assemblies up to modern boards such as the Lilypad series and Raspberry Pi.
  10. Proto Advantage , Hamilton.
    •Mostly breadboarding package adapters, but Arduinos also carried, especially the Netduino.
  11. RobotCraft , London, ON.
    •No retail store. Components and boards related to robotics mostly.
  12. A-One Counterparts , London, ON.
    •Retail store. Components and boards, including Sparkfun and Adafruit. (Poor site with broken links in menu.)
  13. RobotShop , Mirabel, PQ.
    •No retail store. Components and boards related to robotics mostly.
  14. Solarbotics , Calgary.
    •No retail outlet. From BEAM robotics to solar to Arduinos…
  15. B&E Electrnics , Calgary, Regina, Saskatoon.
    •Retail outlets in all three cities. Slanted towards industrial electronics. Refreshingly they only ship to Canadian addresses.
  16. Canada Robotix  Markham, ON.
    •Retail outlet. Roombas to Arduinos…
  17. ABRA Electronics , Montreal.
    •Montreal retail location. Quite a wide range of parts and boards.
  18. A1 Electronic Parts , Toronto.
    •Retail store near the bottom of Hwy 427. Stock is a mix of surplus parts up to modern boards such as Raspberry pi.
  19. Interior Electronics, Kelowna & Burnaby plus Queale Electronics , Victoria.
    •More oriented towards repair and maintenace of equipment, these stores are still sources for passive components and test equipment.
  20. BC Robotics , Nanaimo BC.
    •Arduino; R-Pi; Beagle; Adafruit; a bit of Spikenzie. Strange that one learns about a (the only?)local electronics supplier from somebody at a bus stop in another city! It did help that I was on the way to the Vancouver Mini Maker Faire…
  21. Mikronauts , Lower Mainland, BC.
    •A supplier of boards and kits of their own design. Aimed largely at the education market, their microcontrollers are heavily Propeller based.
  22. Voltatek Electronics , Montreal.
    •No storefront. Arduino, Raspberry pi, Beaglebone as well as general parts and prototyping supplies.
  23. Main Electronic Supplies , Vancouver.
    •Arduino clones, good selection of power supplies and some other test equipment, NTE TV service components.
  24. Meistertech Solutions , Southern Ontario (Aylmer).
    •An interesting collection. Mostly discrete parts aimed at repair and refurbishment. A good place to look for a replacement bulb or an audio grade capacitor.

If you are in the Toronto area, a site which serves as a resource to local suppliers can be found at Karma Laboratories 

Toronto Electronics Retailers

A-1 Electronic Parts

http://a1parts.com

196 North Queen Street, Toronto, ON

(416) 255-0343

I haven’t been here but I’m told it’s like Active Surplus.

Above All Electronics

602 Bloor St W, Toronto, ON

(416) 588-8119

It’s been a while but I remember this place being sort of between Active Surplus and Supremetronics in selection.

Active Surplus

http://activesurplus.com

347 Queen Street West – 2nd floor, Toronto, ON

(416) 593-0909

Carries major electronics components plus cheap, quirky surplus items. Everything sold “as is” so it may be hard to find the exact item you’re looking for since they don’t offer datasheets or specs. 20-30% of inventory turns over often so wander its aisles every month or so.

Creatron

http://creatroninc.com

349 College St, Toronto, ON

(647) 349 9258

Carries almost all of the major electronics components in very neat organized baggies on the wall or bins in the back. This is one of the few places you’ll be able to pick up an Arduino or Arduino-related hardware in Toronto. Carries a small collection of the kits you might find at Sparkfun or the Makezine store (listed as online retailers below) so Creatron is definitely worth checking out if you don’t want to wait for shipping, plus the prices are comparable.

Note: As of mid-2014, Creatron opened a new store at Vic Park and Sheppard and moved their original downtown store to 349 College St (at Augusta Ave) from previous location at 255 College St (at Spadina Ave).

Note: The new downtown location is smaller so doesn’t stock everything that Creatron sells. They will bring items down from their better stocked suburban store – just give them a call to ask.

Creatron – Scarborough store

https://www.creatroninc.com/

3127 Sheppard Ave. East, Scarborough, Ontario, Canada M1T 3J7

(416) 977 9258

Opened mid-2014. Same owners as the Spadina Creatron, but they tend to have a wider range of stock (plus Lawrence the owner is based there and he’s a great resource on electronic design if he has time).

Sayal

http://sayal.com

3791 Victoria Park Ave – Units 1-5, Toronto, ON

(416) 494-8999

Additional stores in Mississauga, Vaughan, Cambridge, and Burlington. Never been there but apparently has a lot bigger selection than Supremetronics.

Supremetronic

290 College St, Toronto, ON

(416) 922-1158

Carries a wider range of electronics components than Active Surplus but not as much as Creatron. Specs are marked on most bins.

Note: Supremetronic is part of Home Hardware and is located in the basement of this Home Hardware location.

Toronto Hardware & Misc Retailers

Brafasco (CTF Supply)

http://brafasco.com

31 Parliament St, Toronto, ON

(416) 364-9191

If you’ve got a tricky screw head (tamper-resisant ones) they might have the right screwdriver for you.

LaserGlow

http://laserglow.com

5 Adrian Ave, Toronto, ON

(416) 729-7976

Need lasers for your next GRL Laser Tag project? Special infrared lasers? Email the folks there (or ask for Justin) and they can work with you to get you the right laser. They don’t carry everything in stock so give them at least 2-3 weeks notice first so they can order it from their supplier.

Lee Valley

http://leevalley.com

590 King Street W, Toronto, ON

(416) 366-5959

Two other locations in Toronto and online shopping available. Lee Valley is kind of a throwback to the 70s and 80s since Lee Valley is really famous for their catalouge sales. But the things they stock are the best of the best.

Rotblott’s Discount Warehouse

http://rotblotts.com

443 Adelaide Street W, Toronto, ON

(416) 703-0456

This is a go-to destination if you work in the film industry. They have a random assortment of hardware and office supplies, along with surplus items. But my favourite thing is something called “Gaffers tape” which is a slightly more expensive tape than duct tape, but it doesn’t leave any sticky residue behind when removed.

Toronto Tool Library

http://torontotoollibrary.com/

1499 Queen St W, Toronto, ON, M6R 1A3

(647) 965-5604

Non-profit tool rental service providing everyone with access to home repair tools and power tools.

As a member of the Toronto Tool Library, members signout tools for both their home and community initiatives. Whether you are hanging a picture or renovating a community park, the Toronto Tool Library offers a rangeof equipment for your project as a low-cost, resource sharing and space-saving alternative to purchasing and owning tools. Non-profits and charitable organizations will also enjoy special membership rates.

Online Retailers

Adafruit Industries

Adafruit has done tons for the maker community. Easy website to shop on with tutorials for both individual electronics components and their own custom kits like the MintyBoost. (U.S. based so be careful of customs.)

Brickyard Ceramics & Crafts

Closest retailer of Amaco’s “Friendly Plastic” (polymorph plastic) – they are actually in the same building! If you have a GST account, call them directly and they can offer a 30% discount. (U.S. based so be careful of customs; and if you want next day or 3 day shipping, be prepared to pay $80, otherwise only $15 for regular 5-7 day standard shipping.)

Digikey

U.S. based company that offers a Canadian retail portal; Prices are in CAD$ and customs/duty charges are already worked in so you won’t be surprised with a $30 FedEx bill for a $10 purchase. Shipping is cheap and prompt (2-5 days). Unless you know the exact part you’re looking for or have good specs, download a catalog for browsing.

Inventables

All sorts of interesting and inspiring materials here. Get ready to browse this site for an hour!

Maker SHED

A few years ago, the web store companion to the iconic Make magazine only really carried kits but today is a formidable place for getting Arduinos, Arduino accessories, and general electronics supplies. They even carry more one-off items such as Chumby Guts, Shapelock moldable plastic, and Pixel Qi screens.

Newark

Alternative Canadian retail portal. Consider opening a FedEx, UPS, etc account so you have more shipping options (including guarenteed next day delivery) but I’ve never had to wait more than 2 days for my packages. Offers a nice visual “selector guide” section.

Robot Shop

Not too sure where exactly they are based but there’s a Canadian retail portal; Prices are in CAD$ and customs/duty charges are already worked in. Haven’t bought anything robotics-related from them yet but I have purchased Flexinol wires from them – and they may be the only place in CAD$ that you can find them.

Sparkfun

Super user-friendly electronics shopping. Very visual and easy to understand. Carries lots of Arduino-related products, including the LilyPad. (U.S. based so be careful of customs.)

Sundance Solar

Retailer of solar panels and many other solar related items. User friendly product descriptions keeps you from shopping in the dark. (U.S. based so be careful of customs.)

Upverter

Upverter is not a retailer but they do have an option to order PCBs from the designs you create in their software.


install the Guest Additions in VirtualBox

$
0
0
sudo apt-get install build-essential linux-headers-`uname -r` dkms

ARMING A BREADBOARD — EVERYONE SHOULD PROGRAM AN ARM

$
0
0

ARMING A BREADBOARD — EVERYONE SHOULD PROGRAM AN ARM

I’m always a little surprised that we don’t see more ARM-based projects. Of course, we do see some, but the volume isn’t what I’d expect given that low-level ARM chips are cheap, capable, low power, and readily available. Having a 32-bit processor with lots of memory running at 40 or 50 MIPS is a game changer compared to, say, a traditional Arduino (and, yes, the Arduino Due and Zero are ARM-based, so you can still stay with Arduino, if that’s what you want).

A few things might inhibit an Arduino, AVR, or PIC user from making the leap. For one thing, most ARM chips use 3.3V I/O instead of the traditional 5V levels (there are exceptions, like the Kinetis E). There was a time when the toolchain was difficult to set up, although this is largely not a problem anymore. But perhaps the largest hurdle is that most of the chips are surface mount devices.

Of course, builders today are getting pretty used to surface mount devices and you can also get evaluation boards pretty cheaply, too. But in some situations–for example, in classrooms–it is very attractive to have a chip that is directly mountable on a common breadboard. Even if you don’t mind using a development board, you may want to use the IC directly in a final version of a project and some people still prefer working with through hole components.

THE 28 PIN SOLUTION

One solution that addresses most, if not all, of these concerns is the LPC1114FN28 processor. Unlike most other ARM processors, this one comes in a 28 pin DIP package and works great on a breadboard. It does require 3.3V, but it is 5V tolerant on digital inputs (and, of course, a 3.3V output is usually fine for driving a 5V input). The chip will work with mbed or other ARM tools and after prototyping, you can always move to a surface mount device for production, if you like. Even if you are buying just one, you should be able to find the device for under $6.

I recently wanted some breadboard setups for students. I did end up make a simple PCB that plugs into a breadboard, but looking back the simple circuit would have worked just as well placed directly on a breadboard. Here’s what you need:

  • An LPC1114FN28
  • A 3.3V power supply
  • A 3.3V or 5V USB to serial cable or adapter
  • One or two 220 ohm resistors (not absolutely necessary)
  • An LED and suitable resistor (optional)
  • Two 0.1uF capacitors (not absolutely necessary)

If you have a USB cable that puts out 3.3V, you can probably drive the chip directly with that. Otherwise, you can use an LD1117-3.3 or an LM7833. A bench supply or one of those cheap power supplies that plugs into a breadboard will work too. Just remember, the chip needs between 1.8V and 3.6V to operate.

BUILDING THE HARDWARE

The circuit is so simple, you almost don’t need a schematic. Here’s one anyway:

Breadboard

One reason that this works so well is the chip has a built-in serial bootloader. If you short the PIO0_1 pin to ground and reset the chip, you can easily upload a program to the device. You could probably get away with just shorting both pins to ground (they are internally pulled up). However, I like to put a small (220 ohm) resistor in series in case software is driving the pin as an output for some reason.

Of course, the jumpers (BOOT and RESET) and connectors in the schematic can just be breadboard wires if you don’t want to mount actual pins. The USB “connector” assumes that pin 2 is ground, pin 3 is the PC’s receiver and pin 4 is the transmit (that is, the LPC1114 talks on 16 and listens on pin 15). If that doesn’t match your cable or RS232 converter, change it as needed.

You may also want to adjust the value of the resistor depending on your LED, but you aren’t making a flashlight, so any value that will get a visible glow ought to be fine (or, omit it completely if you don’t want to blink an LED). If you are a real minimalist, you could dump the 220 ohm resistors, too. The capacitors help decouple your power supply, but breadboards have a good bit of capacitance already and if you have a clean supply, you might not need those either.

So if you have a breadboard and a USB to serial adapter, you could build the bare bones version of this for about $6 and maybe break the bank at $15 if you had to buy everything. Of course, if you have another ARM programmer/debugger that you want to use, that could be wired up instead of the USB cable. But I’m guessing if you have that kind of hardware, you’ve already solved your breadboarding problem.

breadboard1Here’s my (almost) bare bones version:

Not pretty, but effective. I used a switch for the reset and just a wire for the boot jumper. The LED has an internal 5V dropping resistor, but works fine at 3.3V (and I dropped the other two resistors and the capacitors). To work through the software example below, you’ll either need another LED connected to pin 1, or you can just lift up the connection on the breadboard and repurpose the LED. Be aware though: The mbed code assumes you have an LED connected to pin 14 and will blink it if it finds run time errors. If you move the LED you could have an error and won’t get an indication.

SOFTWARE

You can use any ARM tool chain that can generate code for the LPC1114. There are plenty to choose from, but I’m going to assume you are just getting started, so let’s use the mbed web site. I’ve covered how to program using mbed before, and you might want to check out the video below for that walk through.

Here’s a quick summary of the steps you’ll need to take:

  • Go to http://developer.mbed.org
  • Create an account if necessary and log in
  • Click on Platforms and find LPC1114FN28 (or go directly to the page)
  • Click Add to Your mbed Compiler–if you see a button that says Remove, you’ve already done this
  • Now head to the project page and import the project
  • Compile the project and download the BIN file

Once you have the BIN file you’ll need to upload the program via your serial port. I’m going to use a utility called lpc21isp to do that. You can usually find this in your Linux repository, and there is a Windows version available, too. If you just hate the command line, you can always use FlashMagic or the official NXP Windows downloader. There are some GUI front ends for lpc21isp, too, but it is simple enough to use the command line.

The file you’ll download from the mbed website will be named HaD1114Demo_LPC1114.bin unless you changed it (I’ll assume it is in directory /tmp). You also need to know the name of your serial port (e.g., COM1 or /dev/ttyUSB8). The last thing you need to know is roughly what clock frequency the CPU is using. In our case it is 48MHz. Here’s the command line:

lpc21isp -verify -bin /tmp/HaD1114Demo_LPC1114.bin /dev/ttyUSB8 115200 48000

You want to engage the boot jumper and reset the chip either right before or right after executing that command line. The 115200 sets the baud rate and the 48000 is required so the software can sync with the bootloader.

Once you get a successful download, lpc21isp will tell you it is launching the new code. Don’t believe it — It isn’t doing anything yet. You’ll need to disengage the boot jumper and then reset the CPU again. If you prefer to do just a blinking LED, start a new project and that’s one of the boilerplate examples you can use in a new project.

INSIDE THE CODE

The code is simple. Just like the Arduino has a lot of helper library routines, mbed provides most of what you need to drive the devices on the CPU. There’s also an active community of shared libraries for external devices and example code. Here’s the simple code used for the demo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "mbed.h"
PwmOut myled(dp1);
int main()
{
 int i,j;
 while(1)
 {
 for (j=0;j<2;j++)
   for (i=0;i<1000;i+=10)
    {
    float pwm=i/1000.0;
    myled=j?1.0-pwm:pwm;
    wait(0.01);
    }
 }
}

The mbed library frequently makes use of floating point numbers. In the example code, the PWM range is from 0.0 to 1.0. The wait call uses seconds, so 0.01 is 10 milliseconds (there is a wait call that takes a millisecond value, by the way).

The j loop keeps track of even or odd passes so the PWM gets reversed on alternate passes. When j is zero, the PWM goes from 0 to 1.0. When j is not zero, the steps go from 1.0 down to 0. Each pass requires 100 steps (0 to 1000, counting by 10s) so the total time per pass is about 100 times 10 millisecond, or one second.

WHAT’S NEXT?

The mbed library is one place to start, and you can read its documentation online. If you are tied to the Arduino library, there is a port on Github (although I haven’t tried it). However, you can step up to bigger tools and even debugging when you are ready (there’s a good set of examples on Digikey’s eewiki, or you can keep using mbedwith your own IDE and debugger). If you want a quick rapid prototyping arrangement, this set up will easily run a pretty nice Forth, too. And if you are concerned that this isn’t really a hack, you could always chop the chip down to size literally (although we don’t recommend it).


SDR TUTORIALS FROM MICHAEL OSSMANN

$
0
0

SDR TUTORIALS FROM MICHAEL OSSMANN

If you’re just getting into software-defined radio (SDR) but you find some of the math and/or terminology a bit of hurdle, you could absolutely do worse than to check out these SDR tutorials by [Michael Ossmann]. While they’re aimed at people using his HackRF One tool (which we love), most of the tutorial videos are very generally applicable, and we realized that we hadn’t mentioned them explicitly before. Shame on us!

Ossmann focuses on SDR using the open-source GNURadio Companion GUI tool, which makes implementing a lot of cool SDR techniques as easy as dragging and dropping items into a flow diagram. If you want an overview of GNURadio or SDR in general, these videos are a must-watch.

In particular, we loved his entries on complex numbers and complex numbers in DSP because he goes through the whole rationale behind using imaginary numbers in radio work with a graphical presentation that helps add rationale to the otherwise slightly spooky math. Heck, watch these two even if you’re not interested in radio.

The newest entry, covering DSP filters includes a great hands-on introduction to finite impulse response (moving average) digital filters. We really like the practical, simulation-based approach presented in the video — it’s just perfect for a quick introduction.

So if you’re looking for a relatively painless way to get into SDR, grab yourself an RTL-SDR dongle, burn yourself aGNURadio Live DVD, and work through these videos.

POST NAVIGATION



超全!iOS 面试题汇总

$
0
0

作者:Job_Yang

之前看了很多面试题,感觉要不是不够就是过于冗余,于是我将网上的一些面试题进行了删减和重排,现在分享给大家。(题目来源于网络,侵删)

1. Object-c的类可以多重继承么?可以实现多个接口么?Category是什么?重写一个类的方式用继承好还是分类好?为什么?

答: Object-c的类不可以多重继承;可以实现多个接口,通过实现多个接口可以完成C++的多重继承;Category是类别,一般情况用分类好,用Category去重写类的方法,仅对本Category有效,不会影响到其他类与原有类的关系。

2. #import 跟#include 又什么区别,@class呢, #import<> 跟 #import””又什么区别?

答:#import是Objective-C导入头文件的关键字,#include是C/C++导入头文件的关键字,使用#import头文件会自动只导入一次,不会重复导入,相当于#include和#pragma once;@class告诉编译器某个类的声明,当执行时,才去查看类的实现文件,可以解决头文件的相互包含;#import<>用来包含系统的头文件,#import””用来包含用户头文件。

3. 属性readwrite,readonly,assign,retain,copy,nonatomic 各是什么作用,在那种情况下用?

答:

1). readwrite 是可读可写特性;需要生成getter方法和setter方法时

2). readonly 是只读特性 只会生成getter方法 不会生成setter方法 ;不希望属性在类外改变

3). assign 是赋值特性,setter方法将传入参数赋值给实例变量;仅设置变量时;

4). retain 表示持有特性,setter方法将传入参数先保留,再赋值,传入参数的retaincount会+1;

5). copy 表示赋值特性,setter方法将传入对象复制一份;需要完全一份新的变量时。

6).nonatomic 非原子操作,决定编译器生成的setter getter是否是原子操作,atomic表示多线程安全,一般使用nonatomic

4.写一个setter方法用于完成@property (nonatomic,retain)NSString *name,写一个setter方法用于完成@property(nonatomic,copy)NSString *name

答:

1
2
3
4
5
6
7
8
9
10
11
12
- (void) setName:(NSString*) str
{
[str retain];
[name release];
name = str;
}
- (void)setName:(NSString *)str
{
id t = [str copy];
[name release];
name = t;
}

5.对于语句NSString*obj = [[NSData alloc] init]; obj在编译时和运行时分别时什么类型的对象?

答: 编译时是NSString的类型;运行时是NSData类型的对象

6.常见的object-c的数据类型有那些, 和C的基本数据类型有什么区别?如:NSInteger和int

答:object-c的数据类型有NSString,NSNumber,NSArray,NSMutableArray,NSData等等,这些都是class,创建后便是对象,而C语言的基本数据类型int,只是一定字节的内存空间,用于存放数值;NSInteger是基本数据类型,并不是NSNumber的子类,当然也不是NSObject的子类。NSInteger是基本数据类型Int或者Long的别名(NSInteger的定义typedef long NSInteger),它的区别在于,NSInteger会根据系统是32位还是64位来决定是本身是int还是Long。

7.id 声明的对象有什么特性?

答:Id 声明的对象具有运行时的特性,即可以指向任意类型的objcetive-c的对象;

8.Objective-C如何对内存管理的,说说你的看法和解决方法?

答:Objective-C的内存管理主要有三种方式ARC(自动内存计数)、手动内存计数、内存池。

1). (Garbage Collection)自动内存计数:这种方式和java类似,在你的程序的执行过程中。始终有一个高人在背后准确地帮你收拾垃圾,你不用考虑它什么时候开始工作,怎样工作。你只需要明白,我申请了一段内存空间,当我不再使用从而这段内存成为垃圾的时候,我就彻底的把它忘记掉,反正那个高人会帮我收拾垃圾。遗憾的是,那个高人需要消耗一定的资源,在携带设备里面,资源是紧俏商品所以iPhone不支持这个功能。所以“Garbage Collection”不是本入门指南的范围,对“Garbage Collection”内部机制感兴趣的同学可以参考一些其他的资料,不过说老实话“Garbage Collection”不大适合适初学者研究。

解决: 通过alloc – initial方式创建的, 创建后引用计数+1, 此后每retain一次引用计数+1, 那么在程序中做相应次数的release就好了.

2). (Reference Counted)手动内存计数:就是说,从一段内存被申请之后,就存在一个变量用于保存这段内存被使用的次数,我们暂时把它称为计数器,当计数器变为0的时候,那么就是释放这段内存的时候。比如说,当在程序A里面一段内存被成功申请完成之后,那么这个计数器就从0变成1(我们把这个过程叫做alloc),然后程序B也需要使用这个内存,那么计数器就从1变成了2(我们把这个过程叫做retain)。紧接着程序A不再需要这段内存了,那么程序A就把这个计数器减1(我们把这个过程叫做release);程序B也不再需要这段内存的时候,那么也把计数器减1(这个过程还是release)。当系统(也就是Foundation)发现这个计数器变 成员了0,那么就会调用内存回收程序把这段内存回收(我们把这个过程叫做dealloc)。顺便提一句,如果没有Foundation,那么维护计数器,释放内存等等工作需要你手工来完成。

解决:一般是由类的静态方法创建的, 函数名中不会出现alloc或init字样, 如[NSString string]和[NSArray arrayWithObject:], 创建后引用计数+0, 在函数出栈后释放, 即相当于一个栈上的局部变量. 当然也可以通过retain延长对象的生存期.

3). (NSAutoRealeasePool)内存池:可以通过创建和释放内存池控制内存申请和回收的时机.

解决:是由autorelease加入系统内存池, 内存池是可以嵌套的, 每个内存池都需要有一个创建释放对, 就像main函数中写的一样. 使用也很简单, 比如[[[NSString alloc]initialWithFormat:@”Hey you!”] autorelease], 即将一个NSString对象加入到最内层的系统内存池, 当我们释放这个内存池时, 其中的对象都会被释放.

9. 原子(atomic)跟非原子(non-atomic)属性有什么区别?

答:

1). atomic提供多线程安全。是防止在写未完成的时候被另外一个线程读取,造成数据错误

2). non-atomic:在自己管理内存的环境中,解析的访问器保留并自动释放返回的值,如果指定了 nonatomic ,那么访问器只是简单地返回这个值。

10. 看下面的程序,第一个NSLog会输出什么?这时str的retainCount是多少?第二个和第三个呢? 为什么?

1
2
3
4
5
6
7
8
9
10
11
NSMutableArray* ary = [[NSMutableArray array] retain];
NSString *str = [NSString stringWithFormat:@"test"];
[str retain];
[aryaddObject:str];
NSLog(@”%@%d”,str,[str retainCount]);
[str retain];
[str release];
[str release];
NSLog(@”%@%d”,str,[str retainCount]);
[aryremoveAllObjects];
NSLog(@”%@%d”,str,[str retainCount]);

str的retainCount创建+1,retain+1,加入数组自动+1 3

retain+1,release-1,release-1 2

数组删除所有对象,所有数组内的对象自动-1 1

11. 内存管理的几条原则时什么?按照默认法则.那些关键字生成的对象需要手动释放?在和property结合的时候怎样有效的避免内存泄露?

答:谁申请,谁释放

遵循Cocoa Touch的使用原则;

内存管理主要要避免“过早释放”和“内存泄漏”,对于“过早释放”需要注意@property设置特性时,一定要用对特性关键字,对于“内存泄漏”,一定要申请了要负责释放,要细心。

关键字alloc 或new 生成的对象需要手动释放;

设置正确的property属性,对于retain需要在合适的地方释放,

12.如何对iOS设备进行性能测试?

答: Profile-> Instruments ->Time Profiler

13. Object C中创建线程的方法是什么?如果在主线程中执行代码,方法是什么?如果想延时执行代码、方法又是什么?

答:线程创建有三种方法:使用NSThread创建、使用GCD的dispatch、使用子类化的NSOperation,然后将其加入NSOperationQueue;在主线程执行代码,方法是performSelectorOnMainThread,如果想延时执行代码可以用performSelector:onThread:withObject:waitUntilDone:

14. MVC设计模式是什么? 你还熟悉什么设计模式?

答:

设计模式:并不是一种新技术,而是一种编码经验,使用比如java中的接口,iphone中的协议,继承关系等基本手段,用比较成熟的逻辑去处理某一种类型的事情,总结为所谓设计模式。面向对象编程中,java已经归纳了23种设计模式。

mvc设计模式 :模型,视图,控制器,可以将整个应用程序在思想上分成三大块,对应是的数据的存储或处理,前台的显示,业务逻辑的控制。 Iphone本身的设计思想就是遵循mvc设计模式。其不属于23种设计模式范畴。

代理模式:代理模式给某一个对象提供一个代理对象,并由代理对象控制对源对象的引用.比如一个工厂生产了产品,并不想直接卖给用户,而是搞了很多代理商,用户可以直接找代理商买东西,代理商从工厂进货.常见的如QQ的自动回复就属于代理拦截,代理模式在iphone中得到广泛应用.

单例模式:说白了就是一个类不通过alloc方式创建对象,而是用一个静态方法返回这个类的对象。系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为,比如想获得[UIApplication sharedApplication];任何地方调用都可以得到 UIApplication的对象,这个对象是全局唯一的。

观察者模式: 当一个物体发生变化时,会通知所有观察这个物体的观察者让其做出反应。实现起来无非就是把所有观察者的对象给这个物体,当这个物体的发生改变,就会调用遍历所有观察者的对象调用观察者的方法从而达到通知观察者的目的。

工厂模式:

1
2
3
4
5
6
7
8
public class Factory{
public static Sample creator(int which){
if (which==1)
return new SampleA();
else if (which==2)
return new SampleB();
}
}

15 浅复制和深复制的区别?

答:浅层复制:只复制指向对象的指针,而不复制引用对象本身。

深层复制:复制引用对象本身。

意思就是说我有个A对象,复制一份后得到A_copy对象后,对于浅复制来说,A和A_copy指向的是同一个内存资源,复制的只不过是是一个指针,对象本身资源

还是只有一份,那如果我们对A_copy执行了修改操作,那么发现A引用的对象同样被修改,这其实违背了我们复制拷贝的一个思想。深复制就好理解了,内存中存在了

两份独立对象本身。

用网上一哥们通俗的话将就是:

浅复制好比你和你的影子,你完蛋,你的影子也完蛋

深复制好比你和你的克隆人,你完蛋,你的克隆人还活着。

16. 类别的作用?继承和类别在实现中有何区别?

答:category 可以在不获悉,不改变原来代码的情况下往里面添加新的方法,只能添加,不能删除修改,并且如果类别和原来类中的方法产生名称冲突,则类别将覆盖原来的方法,因为类别具有更高的优先级。

类别主要有3个作用:

1).将类的实现分散到多个不同文件或多个不同框架中。

2).创建对私有方法的前向引用。

3).向对象添加非正式协议。

继承可以增加,修改或者删除方法,并且可以增加属性。

17. 类别和类扩展的区别。

答:category和extensions的不同在于 后者可以添加属性。另外后者添加的方法是必须要实现的。

extensions可以认为是一个私有的Category。

18. oc中的协议和java中的接口概念有何不同?

答:OC中的代理有2层含义,官方定义为 formal和informal protocol。前者和Java接口一样。

informal protocol中的方法属于设计模式考虑范畴,不是必须实现的,但是如果有实现,就会改变类的属性。

其实关于正式协议,类别和非正式协议我很早前学习的时候大致看过,也写在了学习教程里

“非正式协议概念其实就是类别的另一种表达方式“这里有一些你可能希望实现的方法,你可以使用他们更好的完成工作”。

这个意思是,这些是可选的。比如我门要一个更好的方法,我们就会申明一个这样的类别去实现。然后你在后期可以直接使用这些更好的方法。

这么看,总觉得类别这玩意儿有点像协议的可选协议。”

现在来看,其实protocal已经开始对两者都统一和规范起来操作,因为资料中说“非正式协议使用interface修饰“,

现在我们看到协议中两个修饰词:“必须实现(@requied)”和“可选实现(@optional)”。

19. 什么是KVO和KVC?

答:KVC:键 – 值编码是一种间接访问对象的属性使用字符串来标识属性,而不是通过调用存取方法,直接或通过实例变量访问的机制。

很多情况下可以简化程序代码。apple文档其实给了一个很好的例子。

KVO:键值观察机制,他提供了观察某一属性变化的方法,极大的简化了代码。

具体用看到嗯哼用到过的一个地方是对于按钮点击变化状态的的监控。

比如我自定义的一个button

1
2
3
4
5
6
7
8
[self addObserver:self forKeyPath:@"highlighted" options:0 context:nil];
#pragma mark KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"highlighted"] ) {
[self setNeedsDisplay];
}
}

对于系统是根据keypath去取的到相应的值发生改变,理论上来说是和kvc机制的道理是一样的。

对于kvc机制如何通过key寻找到value:

“当通过KVC调用对象时,比如:[self valueForKey:@”someKey”]时,程序会自动试图通过几种不同的方式解析这个调用。首先查找对象是否带有 someKey 这个方法,如果没找到,会继续查找对象是否带有someKey这个实例变量(iVar),如果还没有找到,程序会继续试图调用 -(id) valueForUndefinedKey:这个方法。如果这个方法还是没有被实现的话,程序会抛出一个NSUndefinedKeyException异常错误。

(cocoachina.com注:Key-Value Coding查找方法的时候,不仅仅会查找someKey这个方法,还会查找getsomeKey这个方法,前面加一个get,或者_someKey以及_getsomeKey这几种形式。同时,查找实例变量的时候也会不仅仅查找someKey这个变量,也会查找_someKey这个变量是否存在。)

设计valueForUndefinedKey:方法的主要目的是当你使用-(id)valueForKey方法从对象中请求值时,对象能够在错误发生前,有最后的机会响应这个请求。这样做有很多好处,下面的两个例子说明了这样做的好处。“

来至cocoa,这个说法应该挺有道理。

因为我们知道button却是存在一个highlighted实例变量.因此为何上面我们只是add一个相关的keypath就行了,

可以按照kvc查找的逻辑理解,就说的过去了。

20. 代理的作用?

答:代理的目的是改变或传递控制链。允许一个类在某些特定时刻通知到其他类,而不需要获取到那些类的指针。可以减少框架复杂度。

另外一点,代理可以理解为java中的回调监听机制的一种类似。

21. oc中可修改和不可以修改类型。

答:可修改不可修改的集合类。这个我个人简单理解就是可动态添加修改和不可动态添加修改一样。

比如NSArray和NSMutableArray。前者在初始化后的内存控件就是固定不可变的,后者可以添加等,可以动态申请新的内存空间。

22. 我们说的oc是动态运行时语言是什么意思?

答:多态。 主要是将数据类型的确定由编译时,推迟到了运行时。

这个问题其实浅涉及到两个概念,运行时和多态。

简单来说,运行时机制使我们直到运行时才去决定一个对象的类别,以及调用该类别对象指定方法。

多态:不同对象以自己的方式响应相同的消息的能力叫做多态。意思就是假设生物类(life)都用有一个相同的方法-eat;

那人类属于生物,猪也属于生物,都继承了life后,实现各自的eat,但是调用是我们只需调用各自的eat方法。

也就是不同的对象以自己的方式响应了相同的消息(响应了eat这个选择器)。

因此也可以说,运行时机制是多态的基础?~~~

23. 通知和协议的不同之处?

答:协议有控制链(has-a)的关系,通知没有。

首先我一开始也不太明白,什么叫控制链(专业术语了~)。但是简单分析下通知和代理的行为模式,我们大致可以有自己的理解

简单来说,通知的话,它可以一对多,一条消息可以发送给多个消息接受者。

代理按我们的理解,到不是直接说不能一对多,比如我们知道的明星经济代理人,很多时候一个经济人负责好几个明星的事务。

只是对于不同明星间,代理的事物对象都是不一样的,一一对应,不可能说明天要处理A明星要一个发布会,代理人发出处理发布会的消息后,别称B的

发布会了。但是通知就不一样,他只关心发出通知,而不关心多少接收到感兴趣要处理。

因此控制链(has-a从英语单词大致可以看出,单一拥有和可控制的对应关系。

24. 什么是推送消息?

答:推送通知更是一种技术。

简单点就是客户端获取资源的一种手段。

普通情况下,都是客户端主动的pull。

推送则是服务器端主动push。 测试push的实现可以查看该博文。

25. 关于多态性

答:多态,子类指针可以赋值给父类。

这个题目其实可以出到一切面向对象语言中,

因此关于多态,继承和封装基本最好都有个自我意识的理解,也并非一定要把书上资料上写的能背出来

26. 对于单例的理解

答:在objective-c中要实现一个单例类,至少需要做以下四个步骤:

1).为单例对象实现一个静态实例,并初始化,然后设置成nil,

2).实现一个实例构造方法检查上面声明的静态实例是否为nil,如果是则新建并返回一个本类的实例,

3).重写allocWithZone方法,用来保证其他人直接使用alloc和init试图获得一个新实力的时候不产生一个新实例,

4).适当实现allocWitheZone,copyWithZone,release和autorelease。

27. 说说响应链

答: 事件响应链。包括点击事件,画面刷新事件等。在视图栈内从上至下,或者从下之上传播。

可以说点事件的分发,传递以及处理。具体可以去看下touch事件这块。因为问的太抽象化了

严重怀疑题目出到越后面就越笼统。

可以从责任链模式,来讲通过事件响应链处理,其拥有的扩展性

28. frame和bounds有什么不同?

答:frame指的是:该view在父view坐标系统中的位置和大小。(参照点是父亲的坐标系统)

bounds指的是:该view在本身坐标系统中 的位置和大小。(参照点是本身坐标系统)

29. 方法和选择器有何不同?

答:selector是一个方法的名字,method是一个组合体,包含了名字和实现.

详情可以看apple文档。

30. OC的垃圾回收机制?

答: OC2.0有Garbage collection,但是iOS平台不提供。

一般我们了解的objective-c对于内存管理都是手动操作的,但是也有自动释放池。

但是差了大部分资料,貌似不要和arc机制搞混就好了。

31. NSOperation queue?

答:存放NSOperation的集合类。

操作和操作队列,基本可以看成java中的线程和线程池的概念。用于处理ios多线程开发的问题。

网上部分资料提到一点是,虽然是queue,但是却并不是带有队列的概念,放入的操作并非是按照严格的先进现出。

这边又有个疑点是,对于队列来说,先进先出的概念是Afunc添加进队列,Bfunc紧跟着也进入队列,Afunc先执行这个是必然的,

但是Bfunc是等Afunc完全操作完以后,B才开始启动并且执行,因此队列的概念离乱上有点违背了多线程处理这个概念。

但是转念一想其实可以参考银行的取票和叫号系统。

因此对于A比B先排队取票但是B率先执行完操作,我们亦然可以感性认为这还是一个队列。

但是后来看到一票关于这操作队列话题的文章,其中有一句提到

“因为两个操作提交的时间间隔很近,线程池中的线程,谁先启动是不定的。”

瞬间觉得这个queue名字有点忽悠人了,还不如pool~

综合一点,我们知道他可以比较大的用处在于可以帮组多线程编程就好了。

32. 什么是延迟加载?

答:懒汉模式,只在用到的时候才去初始化。

也可以理解成延时加载。

我觉得最好也最简单的一个列子就是tableView中图片的加载显示了。

一个延时载,避免内存过高,一个异步加载,避免线程堵塞。

33. 是否在一个视图控制器中嵌入两个tableview控制器?

答:一个视图控制只提供了一个View视图,理论上一个tableViewController也不能放吧,

只能说可以嵌入一个tableview视图。当然,题目本身也有歧义,如果不是我们定性思维认为的UIViewController,而是宏观的表示视图控制者,那我们倒是可以把其看成一个视图控制者,它可以控制多个视图控制器,比如TabbarController那样的感觉。

34. 一个tableView是否可以关联两个不同的数据源?你会怎么处理?

答:首先我们从代码来看,数据源如何关联上的,其实是在数据源关联的代理方法里实现的。

因此我们并不关心如何去关联他,他怎么关联上,方法只是让我返回根据自己的需要去设置如相关的数据源。

因此,我觉得可以设置多个数据源啊,但是有个问题是,你这是想干嘛呢?想让列表如何显示,不同的数据源分区块显示?

35. 什么时候使用NSMutableArray,什么时候使用NSArray?

答:当数组在程序运行时,需要不断变化的,使用NSMutableArray,当数组在初始化后,便不再改变的,使用NSArray。需要指出的是,使用NSArray只表明的是该数组在运行时不发生改变,即不能往NSAarry的数组里新增和删除元素,但不表明其数组內的元素的内容不能发生改变。NSArray是线程安全的,NSMutableArray不是线程安全的,多线程使用到NSMutableArray需要注意。

36. 给出委托方法的实例,并且说出UITableVIew的Data Source方法

答:CocoaTouch框架中用到了大量委托,其中UITableViewDelegate就是委托机制的典型应用,是一个典型的使用委托来实现适配器模式,其中UITableViewDelegate协议是目标,tableview是适配器,实现UITableViewDelegate协议,并将自身设置为talbeview的delegate的对象,是被适配器,一般情况下该对象是UITableViewController。

UITableVIew的Data Source方法有- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

37. 在应用中可以创建多少autorelease对象,是否有限制?

答案:无

38. 如果我们不创建内存池,是否有内存池提供给我们?

答:界面线程维护着自己的内存池,用户自己创建的数据线程,则需要创建该线程的内存池

39. 什么时候需要在程序中创建内存池?

答:用户自己创建的数据线程,则需要创建该线程的内存池

40. 类NSObject的那些方法经常被使用?

答:NSObject是Objetive-C的基类,其由NSObject类及一系列协议构成。

其中类方法alloc、class、 description 对象方法init、dealloc、– performSelector:withObject:afterDelay:等经常被使用

41. 什么是简便构造方法?

答:简便构造方法一般由CocoaTouch框架提供,如NSNumber的 + numberWithBool: + numberWithChar: + numberWithDouble: + numberWithFloat: + numberWithInt:

Foundation下大部分类均有简便构造方法,我们可以通过简便构造方法,获得系统给我们创建好的对象,并且不需要手动释放。

42. 如何使用Xcode设计通用应用?

答:使用MVC模式设计应用,其中Model层完成脱离界面,即在Model层,其是可运行在任何设备上,在controller层,根据iPhone与iPad(独有UISplitViewController)的不同特点选择不同的viewController对象。在View层,可根据现实要求,来设计,其中以xib文件设计时,其设置其为universal。

43. UIView的动画效果有那些?

答:有很多,如 UIViewAnimationOptionCurveEaseInOut UIViewAnimationOptionCurveEaseIn UIViewAnimationOptionCurveEaseOut UIViewAnimationOptionTransitionFlipFromLeft UIViewAnimationOptionTransitionFlipFromRight UIViewAnimationOptionTransitionCurlUpUIViewAnimationOptionTransitionCurlDown

44. 在iPhone应用中如何保存数据?

答:有以下几种保存机制:

1).通过web服务,保存在服务器上

2).通过NSCoder固化机制,将对象保存在文件中

3).通过SQlite或CoreData保存在文件数据库中

45. 什么是coredata?

答:coredata是苹果提供一套数据保存框架,其基于SQlite

46. 什么是NSManagedObject模型?

答:NSManagedObject是NSObject的子类 ,也是coredata的重要组成部分,它是一个通用的类,实现了core data 模型层所需的基本功能,用户可通过子类化NSManagedObject,建立自己的数据模型。

47. 什么是NSManagedobjectContext?

答:NSManagedobjectContext对象负责应用和数据库之间的交互。

48. 什么是谓词?

答:谓词是通过NSPredicate,是通过给定的逻辑条件作为约束条件,完成对数据的筛选。

1
2
predicate = [NSPredicate predicateWithFormat:@"customerID == %d",n];
a = [customers filteredArrayUsingPredicate:predicate];

49. 和coredata一起有哪几种持久化存储机制?

答:存入到文件、 存入到NSUserDefaults(系统plist文件中)、存入到Sqlite文件数据库

50. 谈谈对Block 的理解?并写出一个使用Block执行UIVew动画?

答:Block是可以获取其他函数局部变量的匿名函数,其不但方便开发,并且可以大幅提高应用的执行效率(多核心CPU可直接处理Block指令)

1
2
3
4
5
[UIView transitionWithView:self.view
duration:0.2
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{ [[blueViewController view] removeFromSuperview]; [[self view] insertSubview:yellowViewController.view atIndex:0]; }
completion:NULL];

51. 写出上面代码的Block的定义。

答:

1
2
typedef void(^animations) (void);
typedef void(^completion) (BOOL finished);

52. 试着使用+ beginAnimations:context:以及上述Block的定义,写出一个可以完成

1
+ (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion NS_AVAILABLE_IOS(4_0);

操作的函数执行部分

答案:无

53. 做过的项目是否涉及网络访问功能,使用什么对象完成网络功能?

答:ASIHTTPRequest与NSURLConnection

54. 简单介绍下NSURLConnection类及+ sendSynchronousRequest:returningResponse:error:与– initWithRequest:delegate:两个方法的区别?

答: NSURLConnection主要用于网络访问,其中+ sendSynchronousRequest:returningResponse:error:是同步访问数据,即当前线程会阻塞,并等待request的返回的response,而– initWithRequest:delegate:使用的是异步加载,当其完成网络访问后,会通过delegate回到主线程,并其委托的对象。

55. 多线程是什么

答: 多线程是个复杂的概念,按字面意思是同步完成多项任务,提高了资源的使用效率,从硬件、操作系统、应用软件不同的角度去看,多线程被赋予不同的内涵,对于硬件,现在市面上多数的CPU都是多核的,多核的CPU运算多线程更为出色;从操作系统角度,是多任务,现在用的主流操作系统都是多任务的,可以一边听歌、一边写博客;对于应用来说,多线程可以让应用有更快的回应,可以在网络下载时,同时响应用户的触摸操作。在iOS应用中,对多线程最初的理解,就是并发,它的含义是原来先做烧水,再摘菜,再炒菜的工作,会变成烧水的同时去摘菜,最后去炒菜。

56. iOS 中的多线程

答: iOS中的多线程,是Cocoa框架下的多线程,通过Cocoa的封装,可以让我们更为方便的使用线程,做过C++的同学可能会对线程有更多的理解,比如线程的创立,信号量、共享变量有认识,Cocoa框架下会方便很多,它对线程做了封装,有些封装,可以让我们创建的对象,本身便拥有线程,也就是线程的对象化抽象,从而减少我们的工程,提供程序的健壮性。

GCD是(Grand Central Dispatch)的缩写 ,从系统级别提供的一个易用地多线程类库,具有运行时的特点,能充分利用多核心硬件。GCD的API接口为C语言的函数,函数参数中多数有Block,关于Block的使用参看这里,为我们提供强大的“接口”,对于GCD的使用参见本文

NSOperation与Queue

NSOperation是一个抽象类,它封装了线程的细节实现,我们可以通过子类化该对象,加上NSQueue来同面向对象的思维,管理多线程程序。具体可参看这里:一个基于NSOperation的多线程网络访问的项目。

NSThread

NSThread是一个控制线程执行的对象,它不如NSOperation抽象,通过它我们可以方便的得到一个线程,并控制它。但NSThread的线程之间的并发控制,是需要我们自己来控制的,可以通过NSCondition实现。

参看 iOS多线程编程之NSThread的使用

其他多线程

在Cocoa的框架下,通知、Timer和异步函数等都有使用多线程,(待补充).

57. 在项目什么时候选择使用GCD,什么时候选择NSOperation?

答: 项目中使用NSOperation的优点是NSOperation是对线程的高度抽象,在项目中使用它,会使项目的程序结构更好,子类化NSOperation的设计思路,是具有面向对象的优点(复用、封装),使得实现是多线程支持,而接口简单,建议在复杂项目中使用。

项目中使用GCD的优点是GCD本身非常简单、易用,对于不复杂的多线程操作,会节省代码量,而Block参数的使用,会是代码更为易读,建议在简单项目中使用。

58. 什么是block

答: 对于闭包(block),有很多定义,其中闭包就是能够读取其它函数内部变量的函数,这个定义即接近本质又较好理解。对于刚接触Block的同学,会觉得有些绕,因为我们习惯写这样的程序main(){ funA();} funA(){funB();} funB(){…..}; 就是函数main调用函数A,函数A调用函数B… 函数们依次顺序执行,但现实中不全是这样的,例如项目经理M,手下有3个程序员A、B、C,当他给程序员A安排实现功能F1时,他并不等着A完成之后,再去安排B去实现F2,而是安排给A功能F1,B功能F2,C功能F3,然后可能去写技术文档,而当A遇到问题时,他会来找项目经理M,当B做完时,会通知M,这就是一个异步执行的例子。在这种情形下,Block便可大显身手,因为在项目经理M,给A安排工作时,同时会告诉A若果遇到困难,如何能找到他报告问题(例如打他手机号),这就是项目经理M给A的一个回调接口,要回掉的操作,比如接到电话,百度查询后,返回网页内容给A,这就是一个Block,在M交待工作时,已经定义好,并且取得了F1的任务号(局部变量),却是在当A遇到问题时,才调用执行,跨函数在项目经理M查询百度,获得结果后回调该block。

59. block 实现原理

答: Objective-C是对C语言的扩展,block的实现是基于指针和函数指针。

从计算语言的发展,最早的goto,高级语言的指针,到面向对象语言的block,从机器的思维,一步步接近人的思维,以方便开发人员更为高效、直接的描述出现实的逻辑(需求)。

使用实例

cocoaTouch框架下动画效果的Block的调用

使用typed声明block

1
2
typedef void(^didFinishBlock) (NSObject *ob);
这就声明了一个didFinishBlock类型的block,

然后便可用

1
@property (nonatomic,copy) didFinishBlock finishBlock;

声明一个blokc对象,注意对象属性设置为copy,接到block 参数时,便会自动复制一份。

__block是一种特殊类型,

使用该关键字声明的局部变量,可以被block所改变,并且其在原函数中的值会被改变。

60.关于block

答: 面试时,面试官会先问一些,是否了解block,是否使用过block,这些问题相当于开场白,往往是下面一系列问题的开始,所以一定要如实根据自己的情况回答。

1). 使用block和使用delegate完成委托模式有什么优点?

首先要了解什么是委托模式,委托模式在iOS中大量应用,其在设计模式中是适配器模式中的对象适配器,Objective-C中使用id类型指向一切对象,使委托模式更为简洁。了解委托模式的细节:

iOS设计模式—-委托模式

使用block实现委托模式,其优点是回调的block代码块定义在委托对象函数内部,使代码更为紧凑;

适配对象不再需要实现具体某个protocol,代码更为简洁。

2). 多线程与block

GCD与Block

使用 dispatch_async 系列方法,可以以指定的方式执行block

GCD编程实例

dispatch_async的完整定义

1
2
3
void dispatch_async(
dispatch_queue_t queue,
dispatch_block_t block);

功能:在指定的队列里提交一个异步执行的block,不阻塞当前线程

通过queue来控制block执行的线程。主线程执行前文定义的 finishBlock对象

1
dispatch_async(dispatch_get_main_queue(),^(void){finishBlock();});

62.谈谈Object-C的内存管理方式及过程?

答: 1).当你使用new,alloc和copy方法创建一个对象时,该对象的保留计数器值为1.当你不再使用该对象时,你要负责向该对象发送一条release或autorelease消息.这样,该对象将在使用寿命结束时被销毁.

2).当你通过任何其他方法获得一个对象时,则假设该对象的保留计数器值为1,而且已经被设置为自动释放,你不需要执行任何操作来确保该对象被清理.如果你打算在一段时间内拥有该对象,则需要保留它并确保在操作完成时释放它.

3).如果你保留了某个对象,你需要(最终)释放或自动释放该对象.必须保持retain方法和release方法的使用次数相等.

63.Object-C有私有方法吗?私有变量呢?

答: objective-c – 类里面的方法只有两种, 静态方法和实例方法. 这似乎就不是完整的面向对象了,按照OO的原则就是一个对象只暴露有用的东西. 如果没有了私有方法的话, 对于一些小范围的代码重用就不那么顺手了. 在类里面声名一个私有方法

1
2
3
4
5
6
7
@interface Controller : NSObject { NSString *something; }
+ (void)thisIsAStaticMethod;
– (void)thisIsAnInstanceMethod;
@end
@interface Controller (private) -
(void)thisIsAPrivateMethod;
@end

@private可以用来修饰私有变量

在Objective‐C中,所有实例变量默认都是私有的,所有实例方法默认都是公有的

64.Object-C有多继承吗?没有的话用什么代替?cocoa 中所有的类都是NSObject 的子类

答: 多继承在这里是用protocol 委托代理 来实现的

你不用去考虑繁琐的多继承 ,虚基类的概念.

ood的多态特性 在 obj-c 中通过委托来实现.

65.内存管理 Autorelease、retain、copy、assign的set方法和含义?

答: 1).你初始化(alloc/init)的对象,你需要释放(release)它。例如:

NSMutableArray aArray = [[NSArray alloc] init]; 后,需要 [aArray release];

2).你retain或copy的,你需要释放它。例如:

[aArray retain] 后,需要 [aArray release];

3).被传递(assign)的对象,你需要斟酌的retain和release。例如:

obj2 = [[obj1 someMethod] autorelease];

对象2接收对象1的一个自动释放的值,或传递一个基本数据类型(NSInteger,NSString)时:你或希望将对象2进行retain,以防止它在被使用之前就被自动释放掉。但是在retain后,一定要在适当的时候进行释放。

关于索引计数(Reference Counting)的问题

retain值 = 索引计数(Reference Counting)

NSArray对象会retain(retain值加一)任何数组中的对象。当NSArray被卸载(dealloc)的时候,所有数组中的对象会 被 执行一次释放(retain值减一)。不仅仅是NSArray,任何收集类(Collection Classes)都执行类似操作。例如 NSDictionary,甚至UINavigationController。

Alloc/init建立的对象,索引计数为1。无需将其再次retain。

[NSArray array]和[NSDate date]等“方法”建立一个索引计数为1的对象,但是也是一个自动释放对象。所以是本地临时对象,那么无所谓了。如果是打算在全Class中使用的变量(iVar),则必须retain它。

缺省的类方法返回值都被执行了“自动释放”方法。(*如上中的NSArray)

在类中的卸载方法“dealloc”中,release所有未被平衡的NS对象。(*所有未被autorelease,而retain值为1的)

66. C和obj-c 如何混用

答: 1).obj-c的编译器处理后缀为m的文件时,可以识别obj-c和c的代码,处理mm文件可以识别obj-c,c,c++代码,但cpp文件必须只能用c/c++代码,而且cpp文件include的头文件中,也不能出现obj-c的代码,因为cpp只是cpp

2).在mm文件中混用cpp直接使用即可,所以obj-c混cpp不是问题

3).在cpp中混用obj-c其实就是使用obj-c编写的模块是我们想要的。

如果模块以类实现,那么要按照cpp class的标准写类的定义,头文件中不能出现obj-c的东西,包括#import cocoa的。实现文件中,即类的实现代码中可以使用obj-c的东西,可以import,只是后缀是mm。

如果模块以函数实现,那么头文件要按c的格式声明函数,实现文件中,c++函数内部可以用obj-c,但后缀还是mm或m。

总结:只要cpp文件和cpp include的文件中不包含obj-c的东西就可以用了,cpp混用obj-c的关键是使用接口,而不能直接使用 实现代 码,实际上cpp混用的是obj-c编译后的o文件,这个东西其实是无差别的,所以可以用。obj-c的编译器支持cpp

67. Objective-C堆和栈的区别?

答: 管理方式:对于栈来讲,是由编译器自动管理,无需我们手工控制;对于堆来说,释放工作由程序员控制,容易产生memory leak。

申请大小:

栈:在Windows下,栈是向低地址扩展的数据结构,是一块连续的内存的区域。这句话的意思是栈顶的地址和栈的最大容量是系统预先规定好的,在 WINDOWS下,栈的大小是2M(也有的说是1M,总之是一个编译时就确定的常数),如果申请的空间超过栈的剩余空间时,将提示overflow。因 此,能从栈获得的空间较小。

堆:堆是向高地址扩展的数据结构,是不连续的内存区域。这是由于系统是用链表来存储的空闲内存地址的,自然是不连续的,而链表的遍历方向是由低地址向高地址。堆的大小受限于计算机系统中有效的虚拟内存。由此可见,堆获得的空间比较灵活,也比较大。

碎片问题:对于堆来讲,频繁的new/delete势必会造成内存空间的不连续,从而造成大量的碎片,使程序效率降低。对于栈来讲,则不会存在这个问题,因为栈是先进后出的队列,他们是如此的一一对应,以至于永远都不可能有一个内存块从栈中间弹出

分配方式:堆都是动态分配的,没有静态分配的堆。栈有2种分配方式:静态分配和动态分配。静态分配是编译器完成的,比如局部变量的分配。动态分配由alloca函数进行分配,但是栈的动态分配和堆是不同的,他的动态分配是由编译器进行释放,无需我们手工实现。

分配效率:栈是机器系统提供的数据结构,计算机会在底层对栈提供支持:分配专门的寄存器存放栈的地址,压栈出栈都有专门的指令执行,这就决定了栈的效率比较高。堆则是C/C++函数库提供的,它的机制是很复杂的。

68. ViewController的didReceiveMemoryWarning怎么被调用:

答:[supper didReceiveMemoryWarning];

69.什么时候用delegate,什么时候用Notification?

答: delegate针对one-to-one关系,用于sender接受到reciever的某个功能反馈值。

notification针对one-to-one/many/none,reciver,用于通知多个object某个事件。

70.用预处理指令#define声明一个常数,用以表明1年中有多少秒(忽略闰年问题)

答:

#define SECONDS_PER_YEAR (60 * 60 * 24 * 365)UL

我在这想看到几件事情:

#define 语法的基本知识(例如:不能以分号结束,括号的使用,等等)

懂得预处理器将为你计算常数表达式的值,因此,直接写出你是如何计算一年中有多少秒而不是计算出实际的值,是更清晰而没有代价的。

意识到这个表达式将使一个16位机的整型数溢出-因此要用到长整型符号L,告诉编译器这个常数是的长整型数。

如果你在你的表达式中用到UL(表示无符号长整型),那么你有了一个好的起点。记住,第一印象很重要。

71.写一个”标准”宏MIN ,这个宏输入两个参数并返回较小的一个。

答:

1
#define MIN(A,B) ((A) <= (B) ? (A) : (B))

这个测试是为下面的目的而设的:

标识#define在宏中应用的基本知识。这是很重要的,因为直到嵌入(inline)操作符变为标准C的一部分,宏是方便产生嵌入代码的唯一方

法,

对于嵌入式系统来说,为了能达到要求的性能,嵌入代码经常是必须的方法。

三重条件操作符的知识。这个操作符存在C语言中的原因是它使得编译器能产生比 if-then-else 更优化的代码,了解这个用法是很重要的。

懂得在宏中小心地把参数用括号括起来

我也用这个问题开始讨论宏的副作用,例如:当你写下面的代码时会发生什么事?

1
least = MIN(*p++, b);

结果是:

1
((*p++) <= (b) ? (*p++) : (*p++))

这个表达式会产生副作用,指针p会作三次++自增操作。

72.关键字const有什么含意?修饰类呢?static的作用,用于类呢?还有extern c的作用

答:

const 意味着”只读”,下面的声明都是什么意思?

1
2
3
4
5
const int a;
int const a;
const int *a;
int * const a;
int const * a const;

前两个的作用是一样,a是一个常整型数。

第三个意味着a是一个指向常整型数的指针(也就是,整型数是不可修改的,但指针可以)。

第四个意思a是一个指向整型数的常指针(也就是说,指针指向的整型数是可以修改的,但指针是不可修改的)。

最后一个意味着a是一个指向常整型数的常指针(也就是说,指针指向的整型数是不可修改的,同时指针也是不可修改的)。

结论:

关键字const的作用是为给读你代码的人传达非常有用的信息,实际上,声明一个参数为常量是为了告诉了用户这个参数的应用目的。

如果你曾花很多时间清理其它人留下的垃圾,你就会很快学会感谢这点多余的信息。(当然,懂得用const的程序员很少会留下的垃圾让别人来清理的)  通过给优化器一些附加的信息,使用关键字const也许能产生更紧凑的代码。合理地使用关键字const可以使编译器很自然地保护那些不希望被改变的参数,防止其被无意的代码修改。简而言之,这样可以减少bug的出现。

1).欲阻止一个变量被改变,可以使用 const 关键字。在定义该 const 变量时,通常需要对它进行初

始化,因为以后就没有机会再去改变它了;

2).对指针来说,可以指定指针本身为 const,也可以指定指针所指的数据为 const,或二者同时指

定为 const;

3).在一个函数声明中,const 可以修饰形参,表明它是一个输入参数,在函数内部不能改变其值;

4).对于类的成员函数,若指定其为 const 类型,则表明其是一个常函数,不能修改类的成员变量;

5).对于类的成员函数,有时候必须指定其返回值为 const 类型,以使得其返回值不为“左值”。

73. 关键字volatile有什么含意?并给出三个不同的例子。

答:一个定义为 volatile的变量是说这变量可能会被意想不到地改变,这样,编译器就不会去假设这个变量的值了。精确地说就是,优化器在用到这个变量时必须每次都小心地重新读取这个变量的值,而不是使用保存在寄存器里的备份。

下面是volatile变量的几个例子:

并行设备的硬件寄存器(如:状态寄存器)

一个中断服务子程序中会访问到的非自动变量(Non-automatic variables)

多线程应用中被几个任务共享的变量

74. 一个参数既可以是const还可以是volatile吗? 一个指针可以是volatile 吗?解释为什么。

答:1).是的。一个例子是只读的状态寄存器。它是volatile因为它可能被意想不到地改变。它是const因为程序不应该试图去修改它。

2).是的。尽管这并不很常见。一个例子是当一个中服务子程序修该一个指向一个buffer的指针时。

75 . static 关键字的作用:

答:

1).函数体内 static 变量的作用范围为该函数体,不同于 auto 变量,该变量的内存只被分配一次,

因此其值在下次调用时仍维持上次的值;

2).在模块内的 static 全局变量可以被模块内所用函数访问,但不能被模块外其它函数访问;

3).在模块内的 static 函数只可被这一模块内的其它函数调用,这个函数的使用范围被限制在声明

它的模块内;

4).在类中的 static 成员变量属于整个类所拥有,对类的所有对象只有一份拷贝;

5).在类中的 static 成员函数属于整个类所拥有,这个函数不接收 this 指针,因而只能访问类的static 成员变量。

76. 线程与进程的区别和联系?

答:

1). 进程和线程都是由操作系统所体会的程序运行的基本单元,系统利用该基本单元实现系统对应用的并发性

2). 进程和线程的主要差别在于它们是不同的操作系统资源管理方式。

3). 进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响,而线程只是一个进程中的不同执行路径。

4.)线程有自己的堆栈和局部变量,但线程之间没有单独的地址空间,一个线程死掉就等于整个进程死掉。所以多进程的程序要比多线程的程序健壮,但在进程切换时,耗费资源较大,效率要差一些。

5). 但对于一些要求同时进行并且又要共享某些变量的并发操作,只能用线程,不能用进程。

77. 列举几种进程的同步机制,并比较其优缺点。

答: 原子操作  信号量机制    自旋锁    管程,会合,分布式系统

78. 进程之间通信的途径

答:共享存储系统消息传递系统管道:以文件系统为基础

79. 进程死锁的原因

答:资源竞争及进程推进顺序非法

80. 死锁的4个必要条件

答:互斥、请求保持、不可剥夺、环路

81. 死锁的处理

答:鸵鸟策略、预防策略、避免策略、检测与解除死锁

82. cocoa touch框架

答:iPhone OS 应用程序的基础 Cocoa Touch 框架重用了许多 Mac 系统的成熟模式,但是它更多地专注于触摸的接口和优化。

UIKit 为您提供了在 iPhone OS 上实现图形,事件驱动程序的基本工具,其建立在和 Mac OS X 中一样的 Foundation 框架上,包括文件处理,网络,字符串操作等。

Cocoa Touch 具有和 iPhone 用户接口一致的特殊设计。有了 UIKit,您可以使用 iPhone OS 上的独特的图形接口控件,按钮,以及全屏视图的功能,您还可以使用加速仪和多点触摸手势来控制您的应用。

各色俱全的框架 除了UIKit 外,Cocoa Touch 包含了创建世界一流 iPhone 应用程序需要的所有框架,从三维图形,到专业音效,甚至提供设备访问 API 以控制摄像头,或通过 GPS 获知当前位置。

Cocoa Touch 既包含只需要几行代码就可以完成全部任务的强大的 Objective-C 框架,也在需要时提供基础的 C 语言 API 来直接访问系统。这些框架包括:

Core Animation:通过 Core Animation,您就可以通过一个基于组合独立图层的简单的编程模型来创建丰富的用户体验。

Core Audio:Core Audio 是播放,处理和录制音频的专业技术,能够轻松为您的应用程序添加强大的音频功能。

Core Data:提供了一个面向对象的数据管理解决方案,它易于使用和理解,甚至可处理任何应用或大或小的数据模型。

功能列表:框架分类

下面是 Cocoa Touch 中一小部分可用的框架:

音频和视频:Core Audio ,OpenAL ,Media Library ,AV Foundation

数据管理 :Core Data ,SQLite

图形和动画 :Core Animation ,OpenGL ES ,Quartz 2D

网络:Bonjour ,WebKit ,BSD Sockets

用户应用:Address Book ,Core Location ,Map Kit ,Store Kit

83. 自动释放池是什么,如何工作

答:当您向一个对象发送一个autorelease消息时,Cocoa就会将该对象的一个引用放入到最新的自动释放.它仍然是个正当的对象,因此自动释放池定义的作用域内的其它对象可以向它发送消息。当程序执行到作用域结束的位置时,自动释放池就会被释放,池中的所有对象也就被释放。

84. Objective-C的优缺点。

答:objc优点:

1).  Cateogies

2).  Posing

3). 动态识别

4).指标计算

5).弹性讯息传递

6).不是一个过度复杂的 C 衍生语言

7).Objective-C 与 C++ 可混合编程

objc缺点:

1).不支援命名空间

2).不支持运算符重载

3).不支持多重继承

4).使用动态运行时类型,所有的方法都是函数调用,所以很多编译时优化方法都用不到。(如内联函数等),性能低劣。

85. sprintf,strcpy,memcpy使用上有什么要注意的地方。

答:

1). sprintf是格式化函数。将一段数据通过特定的格式,格式化到一个字符串缓冲区中去。sprintf格式化的函数的长度不可控,有可能格式化后的字符串会超出缓冲区的大小,造成溢出。

2).strcpy是一个字符串拷贝的函数,它的函数原型为strcpy(char *dst, const char *src

将src开始的一段字符串拷贝到dst开始的内存中去,结束的标志符号为 ‘\0’,由于拷贝的长度不是由我们自己控制的,所以这个字符串拷贝很容易出错。

3). memcpy是具备字符串拷贝功能的函数,这是一个内存拷贝函数,它的函数原型为memcpy(char *dst, const char* src, unsigned int len);将长度为len的一段内存,从src拷贝到dst中去,这个函数的长度可控。但是会有内存叠加的问题。

86. readwrite,readonly,assign,retain,copy,nonatomic 属性的作用

答:@property是一个属性访问声明,扩号内支持以下几个属性:

1).getter=getterName,setter=setterName,设置setter与 getter的方法名

2).readwrite,readonly,设置可供访问级别

2).assign,setter方法直接赋值,不进行任何retain操作,为了解决原类型与环循引用问题

3).retain,setter方法对参数进行release旧值再retain新值,所有实现都是这个顺序(CC上有相关资料)

4).copy,setter方法进行Copy操作,与retain处理流程一样,先旧值release,再 Copy出新的对象,retainCount为1。这是为了减少对上下文的依赖而引入的机制。

5).nonatomic,非原子性访问,不加同步,多线程并发访问会提高性能。注意,如果不加此属性,则默认是两个访问方法都为原子型事务访问。锁被加到所属对象实例级。

87. http和scoket通信的区别。

答: http是客户端用http协议进行请求,发送请求时候需要封装http请求头,并绑定请求的数据,服务器一般有web服务器配合(当然也非绝对)。 http请求方式为客户端主动发起请求,服务器才能给响应,一次请求完毕后则断开连接,以节省资源。服务器不能主动给客户端响应(除非采取http长连接 技术)。iphone主要使用类是NSUrlConnection。

scoket是客户端跟服务器直接使用socket“套接字”进行连接,并没有规定连接后断开,所以客户端和服务器可以保持连接通道,双方 都可以主动发送数据。一般在游戏开发或股票开发这种要求即时性很强并且保持发送数据量比较大的场合使用。主要使用类是CFSocketRef。

88. TCP和UDP的区别

答: TCP全称是Transmission Control Protocol,中文名为传输控制协议,它可以提供可靠的、面向连接的网络数据传递服务。传输控制协议主要包含下列任务和功能:

* 确保IP数据报的成功传递。

* 对程序发送的大块数据进行分段和重组。

* 确保正确排序及按顺序传递分段的数据。

* 通过计算校验和,进行传输数据的完整性检查。

TCP提供的是面向连接的、可靠的数据流传输,而UDP提供的是非面向连接的、不可靠的数据流传输。

简单的说,TCP注重数据安全,而UDP数据传输快点,但安全性一般

89. 你了解svn,cvs等版本控制工具么?

答: 版本控制 svn,cvs 是两种版控制的器,需要配套相关的svn,cvs服务器。

scm是xcode里配置版本控制的地方。版本控制的原理就是a和b同时开发一个项目,a写完当天的代码之后把代码提交给服务器,b要做的时候先从服务器得到最新版本,就可以接着做。 如果a和b都要提交给服务器,并且同时修改了同一个方法,就会产生代码冲突,如果a先提交,那么b提交时,服务器可以提示冲突的代码,b可以清晰的看到,并做出相应的修改或融合后再提交到服务器。

90. 什么是push。

答: 客户端程序留下后门端口,客户端总是监听针对这个后门的请求,于是 服务器可以主动像这个端口推送消息。

91. 静态链接库

答:此为.a文件,相当于java里的jar包,把一些类编译到一个包中,在不同的工程中如果导入此文件就可以使用里面的类,具体使用依然是#import “ xx.h”。

92. fmmpeg框架

答: 音视频编解码框架,内部使用UDP协议针对流媒体开发,内部开辟了六个端口来接受流媒体数据,完成快速接受之目的。

93. fmdb框架

答:数据库框架,对sqllite的数据操作进行了封装,使用着可把精力都放在sql语句上面。

94. 320框架

答: ui框架,导入320工程作为框架包如同添加一个普通框架一样。cover(open)  flower框架 (2d 仿射技术),内部核心类是CATransform3D.

94. 什么是沙盒模型?哪些操作是属于私有api范畴?

答:某个iphone工程进行文件操作有此工程对应的指定的位置,不能逾越。

iphone沙箱模型的有四个文件夹documents,tmp,app,Library,永久数据存储一般放documents文件夹,得到模拟器的路径的可使用NSHomeDirectory()方法。Nsuserdefaults保存的文件在tmp文件夹里。

95. 在一个对象的方法里面:self.name= “object”;和 name =”object” 有什么不同吗?

答:self.name =”object”:会调用对象的setName()方法;

name = “object”:会直接把object赋值给当前对象的name属性。

96. 请简要说明viewDidLoad和viewDidUnload何时调用

答:viewDidLoad在view从nib文件初始化时调用,loadView在controller的view为nil时调用。此方法在编程实现view时调用,view控制器默认会注册memory warning notification,当view controller的任何view没有用的时候,viewDidUnload会被调用,在这里实现将retain的view release,如果是retain的IBOutlet view 属性则不要在这里release,IBOutlet会负责release 。

97. 简述内存分区情况

答:

1).代码区:存放函数二进制代码

2).数据区:系统运行时申请内存并初始化,系统退出时由系统释放。存放全局变量、静态变量、常量

3).堆区:通过malloc等函数或new等操作符动态申请得到,需程序员手动申请和释放

4).栈区:函数模块内申请,函数结束时由系统自动释放。存放局部变量、函数参数

98. 队列和栈有什么区别:

答:队列和栈是两种不同的数据容器。从”数据结构”的角度看,它们都是线性结构,即数据元素之间的关系相同。

队列是一种先进先出的数据结构,它在两端进行操作,一端进行入队列操作,一端进行出列队操作。

栈是一种先进后出的数据结构,它只能在栈顶进行操作,入栈和出栈都在栈顶操作。

99. HTTP协议中,POST和GET的区别是什么?

答:

1).GET 方法

GET 方法提交数据不安全,数据置于请求行,客户端地址栏可见;

GET 方法提交的数据大小有限

GET 方法不可以设置书签

2).POST 方法

POST 方法提交数据安全,数据置于消息主体内,客户端不可见

POST 方法提交的数据大小没有限制

POST 方法可以设置书签

100.  iOS的系统架构

答: iOS的系统架构分为( 核心操作系统层 theCore OS layer )、( 核心服务层theCore Services layer )、( 媒体层 theMedia layer )和( Cocoa 界面服务层 the Cocoa Touch layer )四个层次。

101.  控件主要响应3种事件

答:1). 基于触摸的事件 ;  2). 基于值的事件 ;  3).基于编辑的事件。

102.  xib文件的构成分为哪3个图标?都具有什么功能。

答: File’s Owner 是所有 nib 文件中的每个图标,它表示从磁盘加载 nib 文件的对象;

First Responder 就是用户当前正在与之交互的对象;

View 显示用户界面;完成用户交互;是 UIView 类或其子类。

103.  简述视图控件器的生命周期。

答: loadView 尽管不直接调用该方法,如多手动创建自己的视图,那么应该覆盖这个方法并将它们赋值给试图控制器的 view 属性。

viewDidLoad 只有在视图控制器将其视图载入到内存之后才调用该方法,这是执行任何其他初始化操作的入口。

viewDidUnload 当试图控制器从内存释放自己的方法的时候调用,用于清楚那些可能已经在试图控制器中创建的对象。

viewVillAppear 当试图将要添加到窗口中并且还不可见的时候或者上层视图移出图层后本视图变成顶级视图时调用该方法,用于执行诸如改变视图方向等的操作。实现该方法时确保调用 [super viewWillAppear:

viewDidAppear 当视图添加到窗口中以后或者上层视图移出图层后本视图变成顶级视图时调用,用于放置那些需要在视图显示后执行的代码。确保调用 [super viewDidAppear:] 。

104.  动画有基本类型有哪几种;表视图有哪几种基本样式。

答:动画有两种基本类型:隐式动画和显式动画。

105.  实现简单的表格显示需要设置UITableView的什么属性、实现什么协议?

答:实现简单的表格显示需要设置 UITableView 的 dataSource 和 delegate 属性,实现UITableViewDataSource 和 UITableViewDelegate 协议。

106.  Cocoa Touch提供了哪几种Core Animation过渡类型?

答: Cocoa Touch 提供了 4 种 Core Animation 过渡类型,分别为:交叉淡化、推挤、显示和覆盖。

107.  UIView与CLayer有什么区别?

答:

1).UIView 是 iOS 系统中界面元素的基础,所有的界面元素都是继承自它。它本身完全是由 CoreAnimation 来实现的。它真正的绘图部分,是由一个 CALayer 类来管理。 UIView 本身更像是一个 CALayer 的管理器,访问它的跟绘图和跟坐标有关的属性。

2).UIView 有个重要属性 layer ,可以返回它的主 CALayer 实例。

3).UIView 的 CALayer 类似 UIView 的子 View 树形结构,也可以向它的 layer 上添加子layer ,来完成某些特殊的表示。即 CALayer 层是可以嵌套的。

4).UIView 的 layer 树形在系统内部,被维护着三份 copy 。分别是逻辑树,这里是代码可以操纵的;动画树,是一个中间层,系统就在这一层上更改属性,进行各种渲染操作;显示树,其内容就是当前正被显示在屏幕上得内容。

5).动画的运作:对 UIView 的 subLayer (非主 Layer )属性进行更改,系统将自动进行动画生成,动画持续时间的缺省值似乎是 0.5 秒。

6).坐标系统: CALayer 的坐标系统比 UIView 多了一个 anchorPoint 属性,使用CGPoint 结构表示,值域是 0~1 ,是个比例值。这个点是各种图形变换的坐标原点,同时会更改 layer 的 position 的位置,它的缺省值是 {0.5,0.5} ,即在 layer 的中央。

7).渲染:当更新层,改变不能立即显示在屏幕上。当所有的层都准备好时,可以调用setNeedsDisplay 方法来重绘显示。

8).变换:要在一个层中添加一个 3D 或仿射变换,可以分别设置层的 transform 或affineTransform 属性。

9).变形: Quartz Core 的渲染能力,使二维图像可以被自由操纵,就好像是三维的。图像可以在一个三维坐标系中以任意角度被旋转,缩放和倾斜。 CATransform3D 的一套方法提供了一些魔术般的变换效果。

108. Quatrz 2D的绘图功能的三个核心概念是什么并简述其作用。

答:上下文:主要用于描述图形写入哪里;

路径:是在图层上绘制的内容;

状态:用于保存配置变换的值、填充和轮廓, alpha 值等。

109.  iPhone OS主要提供了几种播放音频的方法?

答: SystemSound Services

AVAudioPlayer 类

Audio Queue Services

OpenAL

110.  使用AVAudioPlayer类调用哪个框架、使用步骤?

答: AVFoundation.framework

步骤:配置 AVAudioPlayer 对象;

实现 AVAudioPlayer 类的委托方法;

控制 AVAudioPlayer 类的对象;

监控音量水平;

回放进度和拖拽播放。

111.  有哪几种手势通知方法、写清楚方法名?

答:

-(void)touchesBegan:(NSSet*)touchedwithEvent:(UIEvent*)event;

-(void)touchesMoved:(NSSet*)touched withEvent:(UIEvent*)event;

-(void)touchesEnded:(NSSet*)touchedwithEvent:(UIEvent*)event;

-(void)touchesCanceled:(NSSet*)touchedwithEvent:(UIEvent*)event;

112.  CFSocket使用有哪几个步骤。

答:创建 Socket 的上下文;创建 Socket ;配置要访问的服务器信息;封装服务器信息;连接服务器;

113.  Core Foundation中提供了哪几种操作Socket的方法?

答: CFNetwork 、 CFSocket 和 BSD Socket 。

114.  解析XML文件有哪几种方式?

答:以 DOM 方式解析 XML 文件;以 SAX 方式解析 XML 文件;

115. ios 平台怎么做数据的持久化?coredata 和sqlite有无必然联系?coredata是一个关系型数据库吗?

答:iOS 中可以有四种持久化数据的方式:属性列表(plist)、对象归档、 SQLite3 和 Core Data; core data 可以使你以图形界面的方式快速的定义 app 的数据模型,同时在你的代码中容易获取到它。 coredata 提供了基础结构去处理常用的功能,例如保存,恢复,撤销和重做,允许你在 app 中继续创建新的任务。在使用 core data 的时候,你不用安装额外的数据库系统,因为 core data 使用内置的 sqlite 数据库。 core data 将你 app 的模型层放入到一组定义在内存中的数据对象。 coredata 会追踪这些对象的改变,同时可以根据需要做相反的改变,例如用户执行撤销命令。当 core data 在对你 app 数据的改变进行保存的时候, core data 会把这些数据归档,并永久性保存。 mac os x 中sqlite 库,它是一个轻量级功能强大的关系数据引擎,也很容易嵌入到应用程序。可以在多个平台使用, sqlite 是一个轻量级的嵌入式 sql 数据库编程。与 core data 框架不同的是, sqlite 是使用程序式的, sql 的主要的 API 来直接操作数据表。 Core Data 不是一个关系型数据库,也不是关系型数据库管理系统 (RDBMS) 。虽然 Core Dta 支持SQLite 作为一种存储类型,但它不能使用任意的 SQLite 数据库。 Core Data 在使用的过程种自己创建这个数据库。 Core Data 支持对一、对多的关系。

116.  tableView 的重用机制?

答:UITableView 通过重用单元格来达到节省内存的目的: 通过为每个单元格指定一个重用标识符(reuseIdentifier),即指定了单元格的种类,以及当单元格滚出屏幕时,允许恢复单元格以便重用.对于不同种类的单元格使用不同的ID,对于简单的表格,一个标识符就够了.


盘点 OSX 上最佳的 DevOps 工具

$
0
0
  • 推荐 0 推荐
  • 收藏 22 收藏,324 浏览

【编者按】对于运维人员来说,他们往往需要各种各样的工具来应对工作需求,近日 Dustin Collins 通过「The Best DevOps Tools on OSX」一文对 OSX 平台上的工具进行盘点。本文系 OneAPM 工程师整理翻译。

以下为译文

如果你供职于一个 DevOps 团队,那么肯定会用到很多工具,比如通讯、架构、编排、编程、测试等等。笔者总是关注一些热门工具,这样就能一直跟随潮流。笔者工作中使用的就是 Macbook Pro,因此本文列出了一些经常使用的工具,以及一些使用工具。

协作方面

Slack——沟通(内部或对外),还支持 Github、Jenkins 和 Pingdom 的推送通知。

Google Drive——分享设计文档/电子表格/演示文稿(内联注释十分强大)。

Google Hangouts——用来举行日常简短的视频会议及其他会议。

Screenhero——协作编程工具:双方都能控制鼠标/键盘,是笔者所发现当下诸多工具中体验最稳定的。

asciinema——终端录制与屏幕分享工具。尤其适合分享 CLI 工作流与创建教程。试试 rec 命令中的-w flag,对长期运行的命令支持良好。

ngrok——建立到本地主机的安全通道。在修改本地 API 或站点后,笔者在发布前一般会通过它进行分享并获得反馈,对缩短设计工作的反馈环节非常有效。

mac2imgur——将截屏上传到 imgur.com,比发送文件存到桌面上要好太多了。一旦上传后,就会将 imgur URL 自动复制到剪贴板上。

keen.io——用来追踪时间段发生的一系列事件,比如 Github 下载的开源项目。Keen 使得代码可以更清晰的可视化,取代盲目猜测。

Mou——撰写可实时预览的 Markdown 文件。在将 READMEs 文档推送到 GitHub 之前,使用 Mou 进行编写是个不错的选择。

开发方面

iTerm2——比默认的 Terminal app 要好得多,可以拆分 panes、search、instant replay 等。这里使用的是 Pastel(黑色背景)的配色方案。

zsh——比旧 OSX 自带的 bash 好用,可以用于结束 tab、自动安装插件,并易于定制。通过 homebrew 执行 zsh 的安装命令 brew install zsh,再将 oh-my-zsh 添加到顶层,就全部搞定了。

mackup——将配置文件备份到 Dropbox 上,这样一旦换新机器了,就无需数天时间,而是仅仅一个小时就能配置好开发环境。

CakeBrew——图形化管理 homebrew 的工具。笔者安装了很多 homebrew 安装包,而图形用户界面显然更好理解。

docker-machine——使用它来建立 VirtualBox 虚拟机从而运行 Docker 服务,也可以在 OSX 上安装 Docker 客户端。之前用的是 boot2docker,不过将来都会改用 docker-machine 了。

Vagrant——如果个项目不是运行在 Docker 上,那么就是运行在 Vagrant 虚拟机上。

ChefDK——在 Conjur,chef-solo 被大量使用,使用它整合工具非常方便。在这些工具中笔者最喜欢的就是 test-kitchen,它不止适用 Chef。比如,可以给 Docker 容器配置一个 shell 脚本,并对其运行测试。test-kitchen 可用来管理测试机器的生命周期。

packer——构建 AMI 的首选工具,比 vagrant-aws 插件更为轻量级。

RubyMine——vim 还是 emacs?都不是首先。RubyMine 的 debug 功能非常棒,可以远程连接 Ruby 编译器(Vagrant 或者 Docker 实例)。Chef 插件也很不错。

PyCharm——很棒的 debug 工具,集成了 IPython notebook。笔者使用过每一种 Python IDE,最终在前几年选中了它。

Sublime Text 3——对于规模较小且非 Ruby/Python 项目,它是默认编辑器。GoSublime 插件配置起来有点复杂,但是在写 Go 代码时会更简便。Conjur 已经开始使用 Jenkins Job DSL 插件,因此也会 Sublime 来写 Groovy 代码。

CheatSheet——CheatSheet 在后台运行,长按 command 键就能显示当前应用的快捷键列表。

Rested——man curl,查看 flags。笔者使用 Rested 浏览测试 API,有时候会保存请求,稍后做回归测试时进行回放。httpie 也是个很不错的备选。

Patterns——用来复查正则表达式,支持多种语言,还有内置的 cheat sheet。

其他

盘点OSX上最佳的DevOps工具

OneAPM–专业的应用性能的监控工具,能够实时展现整个系统的业务拓扑图,帮助进行故障的预警和定位,减少业务系统维护的工作量,协助开发和运维人员持续性的优化代码。

盘点OSX上最佳的DevOps工具

RescueTime——用来追踪不同应用上每周所花费的时间,也可用于评估工作时各种工具对于产效的影响。

Yoink——让文件拖拽更简便:Generate CloudFormation json -> Yoink -> AWS console

Evernote——在查看会议视频或者阅读科技书籍时做笔记。用过不少工具,不过最终还是选择了 Evernote。

原文链接:The Best DevOps Tools on OSX


React Native for Android 实践 —实现知乎日报客户端

$
0
0

React Native for Android 实践 — 实现知乎日报客户端

React Native for Android 的发布,对一个 Android 开发者来说还是有相当的吸引力的。通过前面这篇博客:React Native for Android 入门老虎好不容易入了门了,然后想找一个简单的项目,来练练手。一方面来熟悉一下 RN(React Native, 后面都做此简写),另一方面来验证使用 RN 来实现一个相对完整的项目的可行性。

平时用的最多的客户端之一:知乎日报,这个 APP 相对简单,而且也找到了有人分析的知乎日报 API 分析。就选择它了:实现一个 React Native 版的知乎日报客户端,目标是尽量实现官方客户端一致的效果。

这篇文章主要讲使用 RN 来实现知乎日报客户端的可行性和实现方法。整个项目开源在 GitHub 上:ZhiHuDaily-React-Native,欢迎 Star 和 PR。

基本概念

这里以我的个人理解,快速过一下 React Native 中一些基本概念。如果和官方的理解有些偏差,还请指出。

1. 组件

React Native 主要是通过 Virtual Dom 来实现显示页面或者页面中的模块。可以通过 React.createClass() 来创建自己的 Dom,在 React 中称之为组件(Component)。创建之后,就可以直接像 HTML 标准标签一样使用了。如下:

var MyCustomComponent = React.createClass({
    ...
});

// 然后就可以这样使用
<MyCustomComponent />

到底什么是一个组件?我的理解就是页面上的一个逻辑单元。组件可以小到一个按钮,也可以大到整个页面,组件嵌套组合,就成了各种复杂的界面了。

2. 组件生命周期

类似于 Android 中的一个 View,它也有自己的生命周期,有自己的状态。React 组件的数据保存在自己内部的 state 变量中。每个组件都有自己的生命周期,每个生命周期都有对应的回调,这个和 Android 中的 View 非常类似:

  • getInitialState:获得初始化组件状态,只调用一次
  • componentWillMount:组件将要加载,只调用一次
  • componentDidMount:组件加载完成并显示出来了,也就是完成了一次绘制,只调用一次
  • render:绘制组件,可能调用多次。

具体要写自己的页面的话,要从哪里入手呢?我们这里就要来看一下React.createClass() 是什么的。这个方法可以辅助你创建一个组件,其中传入创建组件的参数,就是自定义组件需要的内容。一个基本的自定义组件写法如下:

var MyCustomComponent = React.createClass({
    // 这里返回一个对象,设置组件的初始化状态,
    // 后面就可以通过 this.state 来获得这个对象
    getInitialState: function() {
        return {
            key1: data1,
            key2: data2,
            ...
        };
    },
    // 这里一般做一些和界面显示无关的初始化操作
    componentWillMount: function() {
    },
    // 这里一般做加载数据的操作
    componentDidMount: function() {
    },
    // 这是最重要的函数,用来绘制界面,
    // 所有的自定义组件,这个函数是必须提供的
    render: function() {
        return(
            <View>
                ...
            </View>
        );
    },
});

一个自定义组件基本上就是上面那样定义了。只有 render 函数是必须的,其他都是可选的。

3. 组件的数据

绘制界面部分,一般情况下会根据组件的状态 state 来绘制动态页面,例如下面一个最简单的例子:

render: function() {
    return(
        <Text>{this.state.key1}</Text>
    );
}

这里就是直接把状态中的 key1 的值用 Text 组件直接显示出来。

另外,React 组件中最重要的一个概念就是 state — 组件的状态。除了前面的使用 getInitialState 方法来设置初始化状态外。在界面逻辑处理或者事件交互的过程中,可以调用 this.setState(...) 方法来修改组件的状态值。

如果在代码中直接修改 state,React 就会把旧状态和新状态做一个 diff,找到变化的部分,然后对应找到和这个变化的值关联的界面部分,请求重新绘制这个部分。例如刚才的例子中,如果调用:

this.setState({key1: 'Hello world!'});

界面上的 Text 内容马上就会显示出 Hello world!

组件中还有一种数据:属性(Property),这种数据可以通过 this.props 来直接获取,例如非常常见的

<View style={{flex: 1}}>

这里的 style 就是 View 这个组件的一个属性。

那么属性(props)和状态(state)两种数据有什么区别呢?一般 属性 表示静态的数据,组件创建后,就基本不变的内容,状态 是动态数据。

4. React Native 布局

关于 React Native 的布局,实用的是 FlexBox 实现,类似网页的 CSS 布局方法,具体可以参考官方推荐的 A Complete Guide to Flexbox 和官方文档 Flexbox。关于布局说起原理比较简单,但是要很灵活的写出你想要的样式,还是需要慢慢积累经验。

另外,值得一提的是,React Native 中的样式长度单位,是逻辑单位,概念和 Android 中的 dp 一样。

以上就是 React Native 的基本逻辑,有了这些概念,我们就可以开始写 APP 了。

APP 开发实践

我们要实现的知乎日报的 APP 的主页面是一个文章列表,左边可以滑动出来抽屉,账号信息和显示主题列表。选择主题列表,可以在列表页更新对应主题的文章列表。点击文章列表进入文章详情。还有评论,点赞,登录等功能初期并不计划做。

1. 抽屉的实现

庆幸的是,官方提供了 DrawerLayoutAndroid 组件,这个组件其实就是对 Android 中的 DrawerLayout 的封装。可以参考官方文档,使用过 Native 版本的 DrawerLayout 话,很容易上手这个组件。主要代码如下:

render: function() {
  ...
  return (
    <DrawerLayoutAndroid
      ref={(drawer) => { this.drawer = drawer; }}
      drawerWidth={Dimensions.get('window').width - DRAWER_WIDTH_LEFT}
      keyboardDismissMode="on-drag"
      drawerPosition={DrawerLayoutAndroid.positions.Left}
      renderNavigationView={this._renderNavigationView}>
      <View style={styles.container}>
         ...
        {content}
      </View>
    </DrawerLayoutAndroid>
  );
}

其中 renderNavigationView 属性,表示抽屉里面显示的内容。本项目的实现,可以参考:ListScreen.js

2. 主页文章列表

文章列表在 Android 可以用 ListView 实现,React Native 也很贴心提供了对应的组件ListView。实用方法和 Android 原生的也类似,需要提供一个数据源 dataSource 和一个基本的绘制每行界面的函数。借用官方的一个代码片段:

getInitialState: function() {
  var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
  return {
    dataSource: ds.cloneWithRows(['row 1', 'row 2']),
  };
},

render: function() {
  return (
    <ListView
      dataSource={this.state.dataSource}
      renderRow={(rowData) => <Text>{rowData}</Text>}
    />
  );
},

这是一个最简的 ListView 使用的例子。其实,React Native 提供的 ListView 比原生还要强大一些,提供了列表的 Section 的支持,列表可以分节,可以显示每节的头部,这个和 iOS 的 UITableView 类似。

因为知乎日报的文章列表是按照日期分 Section 的。具体的使用方法在官方的例子UIExplorer 中有例子。问项目中可以参考这个文件: ListScreen.js

3. 详情页的实现

知乎日报的文章详情页是使用一个 WebView 显示内容的。遗憾的是,React Native 官方在 Android 上并没有提供 WebView 的支持。好在 React Native 很容易集成原生的组件:Native UI Components。我就按照官方文档,导出一个 React 的 WebView 组件。Java 端的代码如下:

public class ReactWebViewManager extends SimpleViewManager<WebView> {

    public static final String REACT_CLASS = "RCTWebView";

    @UIProp(UIProp.Type.STRING)
    public static final String PROP_URL = "url";

    @UIProp(UIProp.Type.STRING)
    public static final String PROP_HTML = "html";

    @UIProp(UIProp.Type.STRING)
    public static final String PROP_CSS = "css";

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @Override
    protected WebView createViewInstance(ThemedReactContext reactContext) {
        return new WebView(reactContext);
    }

    @Override
    public void updateView(final WebView webView, CatalystStylesDiffMap props) {
        super.updateView(webView, props);
        if (props.hasKey(PROP_URL)) {
            webView.loadUrl(props.getString(PROP_URL));
        }

        if (props.hasKey(PROP_HTML)) {
            String html = props.getString(PROP_HTML);
            if (props.hasKey(PROP_CSS)) {
                String css = props.getString(PROP_CSS);
                html = "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + css + "\" />" + html;
            }
            webView.loadData(html, "text/html; charset=utf-8", "UTF-8");
        }

    }
}

这里我导出了一个简单的 WebView,并暴露了 url, html, css 三个属性。url 表示网页要显示的网页地址,html 表示要加载的 HTML 字符串, css 表示网页样式链接。还要注册这个 ReactWebViewManagerReactInstanceManager 中。具体代码可以看MyReactPackage.javaMainActivity.java

在 JS 端,需要做对应的封装:

class ObservableWebView extends React.Component {
  ...

  render() {
    return <RCTWebView {...this.props} onChange={this._onChange} />;
  }
}

ObservableWebView.propTypes = {
  url: PropTypes.string,
  html: PropTypes.string,
  css: PropTypes.string,
  onScrollChange: PropTypes.func,
};

var RCTWebView = requireNativeComponent('RCTWebView', ObservableWebView, {
  nativeOnly: {onChange: true}
});

module.exports = ObservableWebView;

然后就可以在 React 中使用了,如下:

var MyWebView = require('./WebView');

render: function() {
    return (
      <View style={styles.container}>
        <MyWebView
          style={styles.content}
          html={this.state.detail.body}
          css={this.state.detail.css[0]}/>
      </View>
    );
}

这样就能直接显示了网页内容,挺出乎我意料的简单。

还有一个细节,官方客户端,随着 WebView 的滑动,头部的 Image 也跟着往上收起来。这里我们就要监听 WebView 的滑动事件,然后来设置头部的 Image 的跟随移动。还好,官方文档也提供了一个可以方便从 Native 往 React 传递事件的方法:Events。跟着文档来,实现了一个 ObservableWebView,继承于原生的 WebView,同时把滑动事件上报给 React:

// ObservableWebView.java
public class ObservableWebView extends WebView {
    ...
    @Override
    protected void onScrollChanged(final int l, final int t, final int oldl, final int oldt)
    {
        super.onScrollChanged(l, t, oldl, oldt);

        WritableMap event = Arguments.createMap();
        event.putInt("ScrollX", l);
        event.putInt("ScrollY", t);
        ReactContext reactContext = (ReactContext)getContext();
        reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
                getId(), "topChange", event);
    }
}

这里在 onScrollChanged() 回调中,就是往 React 中报 topChange 事件。事件中包含 ScrollXScrollY 两个值。这里的 topChange 被映射到了 JS 的 onChange 事件。在 React 层就能这样用了: <MyWebView onChange={onChangeCallback}/>,这里的 onChangeCallback 是一个自定义的回调函数。WebView 滑动的时候,就会回调到这个函数中来。为了实用方便,这里还可以做一些封装,把 topChange 封装为我们关心的滑动事件onScrollChange

class ObservableWebView extends React.Component {
  constructor() {
    super();
    this._onChange = this._onChange.bind(this);
  }

  _onChange(event: Event) {
    if (!this.props.onScrollChange) {
      return;
    }
    this.props.onScrollChange(event.nativeEvent.ScrollY);
  }

  render() {
    return <RCTWebView {...this.props} onChange={this._onChange} />;
  }
}

详情可以参考:WebView.js

这时,我们就可以在 React 组件中的 onScrollChange 事件回调中实现滑动详情页的头部图片的效果:

onWebViewScroll: function(event) {
    // 这里移动头部的 Image
},
render: function() {
    return (
        <View style={styles.container}>
            <MyWebView
              ...
              onScrollChange={this.onWebViewScroll}/>
            <Image
              ref={REF_HEADER}
              source={{uri: this.state.detail.image}}
              style={styles.headerImage} />
            {toolbar}
        </View>
    );
},

这里的写起来也很简单。关键看一下 onWebViewScroll 函数的实现。最简单的实现方法就是,通过 ScrollY 来设置组件的 state,来让 React 自动触发重绘。因为事件上报非常频繁,就会触发大量的重绘,会带来严重的性能问题。

React Native 提供了 Direct Manipulation,也就是直接操作组件,这种方式不会触发重绘,效率会高很多。

onWebViewScroll: function(event) {
      // 像素转为 React 中的大小单元
    var scrollY = -event / PIXELRATIO;
    var nativeProps = precomputeStyle({transform: [{translateY: scrollY}]});
    // 直接操作组件的属性
    this.refs[REF_HEADER].setNativeProps(nativeProps);
},

到这里,实现这个 React Native 版的知乎日报客户端所涉及的技术点,基本都讲完了。还有很多细节请参考源码:ZhiHuDaily-React-Native,欢迎一起交流,和发 pull request 来一起完善这个项目。

总结

这篇文章几百字就写完了,看起来实现这个客户端并不复杂。其实,这里有远超过我想象的坑,后面我应该还会写一篇文章,来总结这个项目中遇到的坑。总体来说,React Native for Android 作为初期的版本,实现一个简单 APP 已经可行。但是它并不完善,如果想用在实际项目中,还需要慎重考量。

最后,大家可以关注这个项目:ZhiHuDaily-React-Native。希望能对开始关注 React Native 的同学有些帮助。


10 best IOT Hardware platforms

$
0
0

10 best IOT Hardware platforms

 IOT is growing rapidly and we are not far from days where our machines can interact with each other and act accordingly. In fact we will be left behind if we don’t adapt or learn this amazing technology. Here is a list of 10 best IOT hardware platforms which will help us to learn and prototype IOT devices and stuffs.

This list was compiled after seeking experts opinions, conducting polls, forum discussions and much more. Therefore it reflects the choice of many Embedded Programmers and designers. I believe this list will help to choose the perfect platform for  you.

1) Arduino Yun:

arduino-yun-development-board

Arduino Yun is a hybrid board which has inbuilt Ethernet and Wi-Fi connectivity features. This board is powered by ATmega32u4 which handles USB communication whereas the powerful Atheros AR9331 which handles the Wifi and Ethernet interfaces and comes with a Linux distribution based on OpenWrt. There is no need to add external shileds and interfaces for providing internet connectivity. Also you will get tons of technical support from its huge community. This makes Arduino Yun a great platform for developing IOT projects.

Buy Arduino Yun from Amazon here.

2)Raspberry Pi:

raspberry-pi-development-board

Raspberry Pi is a credit card sized computing platform which runs on linux platform. This board features USB ports for keyboard and mouse, a HDMI port for display and an Ethernet port for wired internet connectivity. However for wireless connectivity we need to go for Wifi adapters which we can get it from the market without any trouble. The vast community makes it perfect to develop IOT projects since we get plenty of hands when we stumble.

Buy Raspberry Pi 2 from Amazon

3)ESP8266:

esp8266-wifi-chip-iot

ESP8266 is a Wi-Fi module that is capable of providing internet connectivity to any microcontroller through UART communication. Also it comes with an integrated TCP/IP protocol stack. Each of these module comes pre programmed with AT commands making it easy to plug and play for IOT projects. This module also can also be used for specific application devices and sensors by using its GPIO pins.

4)Beaglebone Black:

beaglebone-black-development-board

Beaglebone Black is a pretty famous low-cost development platform built around ARM Cortex A8 processor. It runs on Linux environment just like the Raspberry Pi. This board has in-built Ethernet Connectivity feature along with HDMI port to connect a monitor to work on. The robust community of Beaglebone makes it outstanding and viable solution to learn and built IOT projects.

Buy Beaglebone Black Rev C from Amazon.

5) Particle.io (Photon and Electron) :

particle-io-photon

Particle.io (formerly known as Spark Core) Photon and Electron is a Wi-Fi enabled IOT hardware platform. It was built using powerful STM32 ARM Cortex M3 and Broadcom Wi-Fi chip . The striking feature of this Particle products is a website cloud platform that allows user to send and receive data seamlessly from anywhere rather than only accessing data from your local network.

6) Intel Edison:

intel-edison-development-board

Intel Edison is a tiny development platform  featuring a Intel Atom CPU and 32 bit Intel Quark microcontroller. This tiny board carries all Wi-Fi and bluetooth modules for connectivity and thus requires no external modules to do so. Also it carries other striking features such as UART, SPI, I2C, I2S, GPIO and SD card support.

7) Arduino + Shields:

arduino-ethernet-shield

Arduino is pretty familiar in the world of prototyping however only some boards have inbuilt internet connectivity. Meanwhile while other Arduino boards can be used with a external shields to provide the connectivity. You can use Ethernet shield for wired connections and Wi-Fi shield for Wireless connection to the internet. Arduino is significant tool in IOT development because of its robust community.

8) Netduino:

netduino-3-ethernet-development-boardNetduino is an open source electronics prototyping platform build around STMicro STM32F4 controller and runs in .NET Micro Framework. Special versions of this Netduino Ethernet and Wi-Fi certainly gives an edge for IOT developers and enthusiasts. Ethernet board equipped with inbuilt Ethernet connectivity and Wi-Fi connectivity for the Wi-Fi board. Other features such as UART, I2C, SPI and SD card connectivity adds flavor to it.

9) Flutter:

flutter-development-board

Flutter is a basic radio board powered by SMART SAM3S Cortex-M3 processor provides a range of about half a mile. This board lets users to develop mesh networking protocols and connect devices with least power expense. It is also equipped with ATSHA204 crypto engine to keep the data transmission safe.

10) Tessel 2:

tessel-2-development-board

Tessel 2 is an affordable yet robust IOT hardware platform powered by Atmel SMART SAMD21 Cortex M0+ processor  to control IO and Mediatek MT7260n Wi-Fi Router SOC to take care of the connectivity. The board is equipped with built-in WI-Fi , Ethernet port, USB port and runs real Node.js/io.js.

And that’s the end of 10 best IOT hardware platforms to learn and prototype devices. I hope this list might have given some idea about the platforms. However do remember there are plenty of hardware platforms available in the market and this article only listed out handful, famous and most preferred by users. So do make research on it and make sure the platform meets your needs. All the best and happy building.


DIY Sous vide cooker with Meteor App

$
0
0

Final Project

http://fab.cba.mit.edu/classes/863.14/people/matthew_arbesfeld/2014/12/14/final-project/

For my final project I built a sous-vide immersion cooker:

 

Sous-vide is a method for cooking food in a temperature-controlled water environment for longer than normal cooking times, at an accurately regulated temperature. Sous-vide cookers are often used in high-end restaurants. In the past few years, however, they have become more popular in household kitchens.

An average sous-vide cooker costs $2000, with low-end cookers going for around $300. I wanted to build my own cheaper version of the device. I also wanted to be able to control it via Bluetooth, so that I could leave the device in my room and control it from anywhere on my floor.

Just want to see the food it can make? Click here

Electronics

The electronics for the cooker are fairly simple. We really are dealing with three components:

  • A waterproof temperature sensor: DS18B20
  • A switched AC current via a solid-state relay: SSR-25da
  • Bluetooth for serial input / output: BLE Mini

I got a chance to play around with the temperature sensor and BLE mini device in week 11. I also got the solid-state relay working in week 10. This week, I brought all of the components together on a single board.

Reading Temperature

Step 1 is to read the temperature of the water. I found a handy device which could do exactly this, a DS18B20:

A ‘one wire’ waterproof temperature sensor.
A 'one wire' waterproof temperature sensor.

This is known as a “one-wire device,” because data from the sensor is transferred over a single wire. We also connect a VCC and GND wire, so there are three wires in total. In software, there is a OneWire Arduino librarywhich lets you create a OneWire bus for data transfer. Dallas Temperature created their own library on top of the OneWire library which provides intuitive commands for reading temperature:

#include <OneWire.h>
#include <DallasTemperature.h>

// Where the temperature sensor probe is connected.
#define ONE_WIRE_BUS 14

// Setup a OneWire instance to communicate with any devices.
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature(&oneWire);

void setup() {
  // Start up the library.
  sensors.begin();
}

void loop() {
  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);
}

Switching AC Current

I used these guys to heat water. They’re AC powered, so we need a way to turn them on and off via a signal from our microcontroller. The most common way to do this is via a solid state relay.

 

The green wires are connected to a pinout and GND, and the white wire intersects a link to the heaters. When the pin is turned on, current from the wall socket can flow to the heaters.

Bluetooth

The final piece of the puzzle is Bluetooth. I used the BLE Mini device from RedBearLabs. The device is super simple to setup. Since I was using an ATMega which has hardware serial, I simply connected RX/TX to the microcontroller and powered the board. It worked on the first try.

Bluetooth + temperature sensing in action:

Power

I needed an AC -> 5V power adapter. The only thing I had on hand was an iPhone charger, but any ~1A power adapter would do the trick.

Board Assembly

Here is the schematic for my board:

 

and the layout:

 

Some points about this design:

  • An ATMega328 was required because the libraries are larger than 8kb.
  • 2×2 headers provide an interface for input/output devices to the microcontroller
  • The board is powered via 5V USB.
  • I drilled holes in the board (shown in green) to serve as mounting points.

The only hard part about soldering the board are the small leads on the ATMega.

Tape served as a lever for positioning the chip.
Tape served as a lever for positioning the chip.
The final board, with all soldered components.
The final board, with all soldered components.

Hardware

Since I will be running 120V AC through my circuit, I needed to build an enclosure to house the various components of the device. No one likes electrocution!

Design

My tool of choice for the design was SolidWorks. I wanted very precise measurements, because I would be mounting various components to the enclosure. Also, I wanted to be able to define the model parametrically, to allow me to quickly change the design if needed.

The final SolidWorks model.
The final SolidWorks model.
Equations defining the enclosure.
Equations defining the enclosure.

Download the SolidWorks file.

Printing

I used the MakerBot Replication 2 with PLA plastic. MakerBot has proprietary software for printing .obj and .stl files.

Printing the top of the case in MakerWare
Printing the top of the case in MakerWare
 
Printing in progress.
Printing in progress.

I was quite pleased with how the parts came out:

The top half of the enclosure. 10 hour print, 0.33 pounds of PLA.
The top half of the enclosure. 10 hour print, 0.33 pounds of PLA.
The bottom half of the enclosure, with mounted power sockets. 3 hour print, 0.25 pounds of PLA.
The bottom half of the enclosure, with mounted power sockets. 3 hour print, 0.25 pounds of PLA.

A few interesting points about my enclosure:

  • I used a friction-fit sliding mechanism to attach the two parts of the case. Clearance was only 0.01”, so I had to do quite a bit of sanding to get the part to fit. Make sure to account for 3d printing artifacts when calculating your tolerances.
  • For AC connectors, I used this female outlet and this male socket from Amazon. I copied the “mounting size” directly from Amazon, but really should have left some clearance to let the parts slide in more easily.
  • Screw mounting works great with PLA plastic. I left ~0.1” holes and hand drilled 6×3/4” screws into the plastic.
  • I also built a small power-strip. We power a circulation pump whenever the sous-vide is turned on.
  • In order to make the device as general as possible, you can plug in any device which is switched on by the relay. This lets you connect devices other than heaters to the unit. For example, we could control a refrigeration unit with the same device.

Assembly

Once my 3d prints finished, it was time to assemble everything together!

This was my first time working with AC power, but I learned a few tricks:

  • 16 or 18 gauge wire must be used to carry the high AC current.
  • Wire nuts work great for attaching multiple wires together.
  • Don’t forget to solder wires onto the power leads.
  • There is nothing wrong with copious amounts of electrical tape.
Wiring the front face of the enclosure with 16 gauge wire.
Wiring the front face of the enclosure with 16 gauge wire.
The solid state relay is mounted on a heatsink which is attached to the enclosure via screws.
The solid state relay is mounted on a heatsink which is attached to the enclosure via screws.
These things work great for connecting multiple wires together.
These things work great for connecting multiple wires together.
Screwing the PCB into the mount holes.
Screwing the PCB into the mount holes.
Taken just before closing the enclosure. Everything is tested and working!
Taken just before closing the enclosure. Everything is tested and working!
Sliding the top into place.
Sliding the top into place.
Everything sealed tightly inside. Ready to make some food!
Everything sealed tightly inside. Ready to make some food!

Woo! That was a lot of work.

My post on Hacker News garnered a lot of feedback on the AC component of my design. There were safety issues in my original design which should have been addressed. Thank you to cnvogel and mikeytown2.

  • I should have used crimped terminal connectors to connect the wire to the inlet sockets.
  • Terminal blocks are safer than screw caps for connecting cables.
  • I could have 3d printed a clip that goes over the terminals on the relay.
  • Always design enclosures with a physical barrier between the “high voltage” side and the “low voltage” side.
  • Running the AC through a device like this or this would have made it much safer, especially since we are dealing with water.

Application Programming

I go into detail about the SousVide controller application in Week 11. In essence, the app is a cross-platform mobile app that lets you control the temperature and duration of your sous-vide recipes. Some features include:

  • Signing in (via Google) to save recipes.
  • Notifications when the recipe duration has elapsed
  • Preheating the sous-vide, and cooking when ready.
  • Monitoring temperature and on/off state of the sous-vide.
A screenshot of the app, when cooking food. The blue text indicates that the heaters are switched off (because the current temperature is slightly higher than the target).
A screenshot of the app, when cooking food. The blue text indicates that the heaters are switched off (because the current temperature is slightly higher than the target).

All of the code is available on my GitHub.

Cost

Parts:

Total cost: ~$100

Overall, this project was much cheaper than buying a conventional sous-vide. Moreover, this device can control any arbitrary AC current based on temperature via Bluetooth. For example, we could use the same device to smoke meats or refrigerate beer.

Results

Finally, it’s time for the food porn! A sous-vide is only as good as the food it makes:

Eggs

My first test was cooking eggs at 76C for 45 minutes:

Soft-boiling eggs at 76C.
Soft-boiling eggs at 76C.
Delicious! The yolk tasted like butter!
Delicious! The yolk tasted like butter!

Hamburger

I cooked a burger at 57C and then seared on the grill for a great medium-rare:

Using a cup to hold the burger submerged in the liquid. Yea, the food looks kinda gross as it is being cooked.
Using a cup to hold the burger submerged in the liquid. Yea, the food looks kinda gross as it is being cooked.
 
I’m enjoying the burger.
I'm enjoying the burger.

Steak

Steak is the quintessential sous-vide item. I cooked this boneless ribeye at 56C for 90 minutes.

The steak après sous-vide.
The steak après sous-vide.
Searing the food after sous-vide seals in the juices and makes it look more appetizing.
Searing the food after sous-vide seals in the juices and makes it look more appetizing.
Medium-rare throughout the whole steak. This is really hard to achieve with conventional cooking techniques.
Medium-rare throughout the whole steak. This is really hard to achieve with conventional cooking techniques.
Steak and sweet potato medallions — the perfect way to celebrate the end of a semester!
Steak and sweet potato medallions -- the perfect way to celebrate the end of a semester!

Android RecyclerView Example

$
0
0

Android RecyclerView Example

1. What is RecyclerView?

Google’s upcoming operating system named Android L looks very promising. It is highly focused on rich user experience and what they called it as material design. In this example we will take a look at the new UI widget called RecyclerView.

RecyclerView is more advanced and flexible and efficient version of ListView. RecyclerView ViewGroup is an container for larger data set of views that can be recycled and scrolled very efficiently. RecyclerView can be used for larger datasets to be rendered on the UI like a list. RecyclerView provides maximum flexibility to design different kind of views

2. RecyclerView Example

The tutorial, download the feed data from server, parse the JSON feed response and display the items on list. This example using both RecyclerView and CardView for creating the UI as shown in the following video.

To accomplish this result as shown in the above video, we need to follow the following steps:

  1. Create a new Android application in Android Studio IDE and add the support library dependency.
  2. Declare an layout for your activity and add a RecyclerView and ProgressBar widget
  3. Create an activity class to initiate data download, initialize the adapter and display data on RecyclerView
  4. Create RecyclerView row layout. Here we will use the CardView widget.
  5. Create an custom adapter that will be used for RecyclerView
  6. Implementing RecyclerView click event handling

2.1. Adding Support Library

Android SDK doesn’t includes the RecyclerView class, and hence for using RecyclerView in your project you first need to add the recycler view support library to your project. Android Studio users can add the following graddle dependency to project build.graddle file.

dependencies {
       compile 'com.android.support:recyclerview-v7:+'
       compile 'com.android.support:cardview-v7:21.0.+'
       compile project(':picasso-2.3.4')
}

Notice that in the above dependency declaration, I have added the RecyclerView and CardView support library, and the Picasso.jar. Before this, you need to add Picasso jar module by going to your Android Studio Project properties.

2.2. Adding Internet Permission

You might be aware that, Android application must declare all the permissions that are required for application. As we need to download the data form server, we need to add the INTERNET permission. Add the following line toAndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javatechig.app">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
       .....
    </application>
</manifest>

2.3. Declaring Activity Layout

Our first step towards this example is to declare the activity layout. Here in this example, we will add a RecyclerView and ProgressBar inside aRelativeLayout. The progress bar will be shown to user while the data is being downloaded. Add the following code snippets tolayout/activity_feed_list.xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/activity_vertical_margin">

    <view
        android:id="@+id/recycler_view"
        class="android.support.v7.widget.RecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true" />

    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
</RelativeLayout>

2.4. Activity Using RecyclerView

RecyclerView is a ViewGroup similar to ListView or GridView. A ViewGroup is an UI widget that is used to render collection of data. In this example, we are trying to download the latest feeds from this site and display it on RecyclerView.  The focus of this tutorial is narrow down to RecyclerView, hence it doesn’t include any explanation for download and parse data from server. For learning how to download data from server, you may read Android Networking Tutorial.

As the data is downloaded, inside onPostExecute() we are initializing the adapter and setting adapter to RecyclerView instance by just calling setAdapter()method.

package com.javatechig.app;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class FeedListActivity extends AppCompatActivity {
    private static final String TAG = "RecyclerViewExample";
    private List<FeedItem> feedsList;
    private RecyclerView mRecyclerView;
    private MyRecyclerAdapter adapter;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feeds_list);

        // Initialize recycler view
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        progressBar.setVisibility(View.VISIBLE);

        // Downloading data from below url
        final String url = "http://javatechig.com/?json=get_recent_posts&count=45";
        new AsyncHttpTask().execute(url);
    }

    public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

        @Override
        protected void onPreExecute() {
            setProgressBarIndeterminateVisibility(true);
        }

        @Override
        protected Integer doInBackground(String... params) {
            Integer result = 0;
            HttpURLConnection urlConnection;
            try {
                URL url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                int statusCode = urlConnection.getResponseCode();

                // 200 represents HTTP OK
                if (statusCode == 200) {
                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        response.append(line);
                    }
                    parseResult(response.toString());
                    result = 1; // Successful
                } else {
                    result = 0; //"Failed to fetch data!";
                }
            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return result; //"Failed to fetch data!";
        }

        @Override
        protected void onPostExecute(Integer result) {
            // Download complete. Let us update UI
            progressBar.setVisibility(View.GONE);

            if (result == 1) {
                adapter = new MyRecyclerAdapter(FeedListActivity.this, feedsList);
                mRecyclerView.setAdapter(adapter);
            } else {
                Toast.makeText(FeedListActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONArray posts = response.optJSONArray("posts");
            feedsList = new ArrayList<>();

            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);
                FeedItem item = new FeedItem();
                item.setTitle(post.optString("title"));
                item.setThumbnail(post.optString("thumbnail"));

                feedsList.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Notice that in the above code snippet, we are using the FeedItem POJO class to parse the data from server. Create a new file named FeedItem.java class in your project source folder and add the following snippets.

package com.javatechig.recyclerview;

public class FeedItem {
    private String title;
    private String thumbnail;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }
}

2.5. Creating RecyclerView Adapter

Android RecyclerView includes special kind of adapter which works pretty much same as traditional Android adapters but with additional functionalities. The additional functionalities includes;

  • It adds two new methods like onCreateViewHolder() andonBindViewHolder() to organize the code. You must override these two methods for inflate the view and to bind data to the view
  • Implements a ViewHolder by default. ConceptuallyRecyclerView.ViewHolder works same as the ViewHolder design pattern which we have been using with other Adapters
  • Takes care of the overhead of recycling and gives better performance and scrolling
package com.javatechig.app;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.List;

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.CustomViewHolder> {
    private List<FeedItem> feedItemList;
    private Context mContext;

    public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
        this.feedItemList = feedItemList;
        this.mContext = context;
    }

    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);

        CustomViewHolder viewHolder = new CustomViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
        FeedItem feedItem = feedItemList.get(i);

        //Download image using picasso library
        Picasso.with(mContext).load(feedItem.getThumbnail())
                .error(R.drawable.placeholder)
                .placeholder(R.drawable.placeholder)
                .into(customViewHolder.imageView);

        //Setting text view title
        customViewHolder.textView.setText(Html.fromHtml(feedItem.getTitle()));
    }

    @Override
    public int getItemCount() {
        return (null != feedItemList ? feedItemList.size() : 0);
    }
}

2.6. RecyclerView Row Layout

The above code mentions about another new layout list_row.xml. This is defies the layout for RecyclerView item.  Here in this example, we are using the CardView as parent layout and CardView hosts a RelativeLayout with an ImageView and TextView.

Click here to learn more about Android CardView.

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cardview="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:layout_margin="8dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="80dp">

        <ImageView
            android:id="@+id/thumbnail"
            android:layout_width="100dp"
            android:layout_height="80dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:scaleType="centerCrop"
            android:src="@drawable/placeholder" />

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/thumbnail"
            android:maxLines="3"
            android:padding="8dp"
            android:text="dafdafda"
            android:textColor="#222"
            android:textSize="15dp" />

    </RelativeLayout>
</android.support.v7.widget.CardView>

2.6. Implementing ViewHolder Pattern

Now let us create our ViewHolder class. The ViewHolder contains the reference to the each of the ui widget on the row. We have defined this class as a private class inside MyRecyclerAdapter.

public class CustomViewHolder extends RecyclerView.ViewHolder {
        protected ImageView imageView;
        protected TextView textView;

        public CustomViewHolder(View view) {
            super(view);
            this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
            this.textView = (TextView) view.findViewById(R.id.title);
        }
    }

3. Handle RecyclerView Click Event

Handling click event on RecyclerView is not as sweet as handling click listener in ListView or GridView. Android RecyclerView doesn’t provide any built in listeners or handy way of handling click events.

However we can use workaround to handle click event explicitly by adding the following code in onBindViewHolder() method.

//Handle click event on both title and image click
customViewHolder.textView.setOnClickListener(clickListener);
customViewHolder.imageView.setOnClickListener(clickListener);

customViewHolder.textView.setTag(customViewHolder);
customViewHolder.imageView.setTag(customViewHolder);

Add declare the clickListener variable as follows

View.OnClickListener clickListener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        CustomViewHolder holder = (CustomViewHolder) view.getTag();
        int position = holder.getPosition();

        FeedItem feedItem = feedItemList.get(position);
        Toast.makeText(mContext, feedItem.getTitle(), Toast.LENGTH_SHORT).show();
    }
};

4. Download Source Code

Download from GitHub.


Eagle: Extract a symbol from a project to a library

$
0
0

Eagle: Extract a symbol from a project to a library

Eagle – a widespread PCB design tool – comes with a huge amount of libraries but sometimes it is missing the exact device you need for your project. A common way to add a new device to your libraries is to copy an existent but similar one and to adapt it to your needs.

Another more comfortable solution is – assuming you downloaded an existent eagle project from the internet – to generate a complete library with all the devices used in the schematic or board file of that project.

It’s done amazing easy with a few clicks only. In your menu toolbar there’s the ULP tool. ULP stands for User Language Program which is the language used to write scripts to add new functionality to eagle. These scripts can be seen as a kind of plugins such as there are add-ons in firefox to give it new abilities.

After clicking on the ULP tool you have to choose the exp-project-lbr.ulp ULP script.

Update (April 11th, 2013):

As of version 6.4 the export of schematic and/or board libraries has been integrated into the EAGLE GUI, available in the File menu under Export/Libraries while the new ULP exp-lbrs.ulp is replacing the existing exp-project-lbr.ulp.

The new script hasn’t been tested yet and thus the rest of this article is still referencing the old ULP. Please leave a comment if this howto cannot be applied any longer.

The script will ask you for some options but chances are that you leave them unchanged. Just click on the Collect data and Create library afterwards.

Optionally also the mechanical packages can be generated. Make your choice.

The generation can take a while now depending on the schematic and board complexity. The ULP script will finally create a file with the file name of your schematic but uses lbr as the file extension then.

You should have got now what you were looking for.



A development board for the STM32F042 TSSOP package

$
0
0

It’s been a while since I posted a new article, a delay at least partly due to me herniating a disc in my neck which left me completely unable to look downwards for any length of time and as you’ll know all too well you can’t work on circuit boards without peering down at them. Look after your neck and back folks, and I mean that seriously.

Well I’m back now and I’ve got a lot of ideas for articles spinning around in my head that will hopefully come to fruition over the next few months. First off the block is this one in which I’m going to present a simple development board for the STM32F042 in the easy(ish) to work with TSSOP20 package.


STM32F042 TSSOP20 0.65mm pitch package

This project came about because I’m using the STM32F042F6P6 (32Kb flash, 6Kb SRAM) in another project where I’m creating a USB device and the first thing I did is try to obtain a development board for it. I was hopeful that ST would have created one of their ‘discovery’ boards but no, there was only a ‘nucleo’ board available and that had one of the QFP packages on it.


The F042 nucleo board

The nucleo board would have probably been sufficient for my needs but I do prefer to work on the actual device that’s going to be used in the real project and I had a few ideas for features that I’d include that I wish would be included in other development boards but never seem to be.

Development board features

  • USB. The 042 series supports USB and although 32Kb is not a lot of space to include a USB driver and your application logic it does make sense to hook up those USB data lines and thereby enable USB device development.
  • Switching regulator. All the development boards that I’ve seen seem to use a low dropout regulator (LDO) to supply power to the MCU which means that they’re unable to supply much current to any peripherals that you’re prototyping. The discovery boards warn you not to draw more than 100mA and many of the 3rd party boards use one of the 1117 regulators which, with up to a 1A limit, look great on paper but the universally chosen SOT-223 package will burn up in smoke long before you get anywhere near that figure.
  • VDDA control.The discovery boards allow you to supply VDDA externally if required. I’d like to keep this ability.
  • Onboard 8MHz crystal. All the F0 series can be clocked from the internal high speed internal (HSI) 8MHz oscillator with an option to use an external 8Mhz crystal. I’ll include such a crystal on my board.
  • Onboard NPN transistor. I often need to use an NPN transistor as a low-side switch to control a load either requires too much current to power from a GPIO or is running from a different voltage level (e.g. 5V). I’ll include a simple transistor on this board configured ready to function as a switch.
  • A LED. Because, well, you know, blinky.

Schematic



Click for a PDF

The schematic is rather modular so let’s take a look at each section in detail.

The power supply

The 3.3V voltage for the board is supplied by a Texas Instruments LMR10515 adjustable switching buck (step-down) regulator. I’ve used this regulator a few times before and have found it to be a solid and reliable device that doesn’t require many external components and only costs about 50 pence from Farnell.

This regulator is capable of supplying up to 1.5A with an efficiency level of over 90% throughout most of its range. The input will be the 5V VBUS line from the USB plug after I’ve sanitised it to remove the gremlins that lurk therein.

It’s this efficiency level that allows switching regulators to deliver their peak current rating without burning up in a puff of smoke. The output inductor and schottky diode must both be chosen to match the desired peak current from the regulator. For the inductor I’ve chosen the Murata LQH44PN3R3MP0L (2.1A maximum current) and for the schottky I’m using an ST Micro STPS0520Z (0.5A maximum current).

In practice this means that my development board is limited to 500mA but you can use any schottky that will fit the SOD-123 footprint if you need a higher current supply up to the 1.5A maximum that the regulator can deliver.

The MCU

The MCU power and reset scheme is wired up according to ST’s recommendations. VDD gets a pair of 100nF and 4.7µF capacitors and VDDA gets a 10nF and 1µF pair. P3, a 4 pin header, receives a jumper across pins 1 and 2 to connect VDDA to the onboard 3.3V supply or the jumper can be removed to allow an external VDDA to be connected to pin 3.

C4 decouples the active-low reset pin to prevent any spurious resets from ruining your day. There’s no need for a pull-up to VDD because ST supply one internally.

The crystal is connected to the MCU via a pair of 0R ‘resistor’ bridges that can be removed if you’ve fitted a crystal but want to use the PF0 and PF1 pins as GPIO without fear of interference from the crystal itself.

If you’re considering USB device development and you’ve done this before then you may think that you’re going to need the external crystal to generate the accurate 48MHz clock required by USB to stay in sync with the host, but this is not the case. ST supply an internal ‘HSI48′ 48MHz clock specifically for use with the USB peripheral and with a bit of software configuration you can not only clock the MCU core from it but you can also constantly trim its accuracy from the USB Start of Frame (SOF) packets sent by the host to the device every 1ms. I’ll show you how to set up this crystal-less configuration later on.

Upon startup the MCU can boot from flash, SRAM or system memory (that’s where the boot loader is). The most common option is to boot from flash directly into your code and you select that by holding BOOT0 low during the exit from reset and standy modes.

But wait, doesn’t this waste the PB8 GPIO pin? No it doesn’t. If you always want to boot from flash then you can program the BOOT_SEL and nBOOT0 bits of theFLASH_OBR register to 0 and 1 respectively and then the MCU will ignore BOOT0 and you can use it as a GPIO pin.

Programming and debugging

ST include an embedded ST-Link/v2 chip on their discovery boards implemented within an STM32F1 series MCU that allows you to program and debug over the same USB line that you use to supply power.

That’s neat, and it means that you don’t have to buy a programmer for your board. It is, however, proprietary which means I can’t include it on this board. Instead, I include the standard 20-pin ST-Link/v2 header that you can attach a programming cable to.

I’ve already written an article about how to set up and use the ST-Link/v2 programmer using only free software.

The USB interface

I’ve opted to include an ST Micro USBLC6-2SC6 ESD protection device between the USB lines and the MCU. Without this the MCU would be vulnerable to ESD events on the line caused by handling of the plug or cable and could easily be damaged or destroyed.

Chances are you don’t even have the ID signal line in your cable (it’s for OTG cables only) but in common with ST’s configuration on their discovery boards I’m grounding it through a 100kΩ resistor.

C1, C2, C3 and FB1 form a filtering network to remove noise from the VBUS line before it becomes an input to the switching regulator. If you’ve never seen how much noise you can get on VBUS then I recommend that you take a look at this article that I wrote.

If you’re powering this board from a computer’s USB port then be mindful of the maximum amount of power that you can draw. This wikipedia article explains it well. Of course if you’re powering this board from a USB wall charger then the limit is set by that charger.

The USB socket itself is a mini-B size and has a very common standard footprint. Search ebay for these mini-B PCB sockets and you’ll see that they all have this footprint.

Power output

P4 is a pin header that can be used to access the power supplies on the board along with a generous helping of ground pins. You can’t have too many ground pins on a development board and I find it really frustrating when you receive a board to find it’s only got one or two ground pins. I’ve included four here and another one on the GPIO header.

NPN transistor

The base of the MMBT3904 transistor is connected via a 1kΩ resistor to PA7 so you can control it as a switch from the MCU. The maximum collector current for the MMBT3904 is 200mA. If you need more than that then you should substitute this part for another one in the SOT23-3 package that has a higher rating.

R9, a 100kΩ resistor, pulls the base down to ground so you don’t get spurious switching events during any periods when the gate is floating. The idea is that you connect your load to be driven to the LOAD pin.

GPIO

All the GPIO pins exposed by the TSSOP20 package are included here as well as the LOAD pin for the NPN transistor and an additional ground pin.

Bill of materials

Here’s the full bill-of-materials for this board, along with Farnell product code numbers to help you put together an order basket.

[1] These components must be rated in excess of the current that you plan to draw. My recommendations support a maximum of 500mA.

[2] 0603 SMD resistors are so cheap on ebay that I recommend you buy some there. I used green for the power LED and amber for the GPIO LED.

[3] The USB mini-B PCB connector is a common footprint that’s very cheaply available on ebay. See the high-resolution photograph in this article and compare to ebay auction photographs.

[4] Dual-row 2.54mm pin headers are very cheap on ebay.

Building the board

The board was laid out to fit within a 50mm square so that it could be manufactured by one of the discount Chinese prototyping houses such as Seeed, ITead, PCBWay and Elecrow. For this size of board I choose Elecrow and for US$9.90 plus delivery I can get ten copies in about two or three weeks.

Time passes. Two or three weeks worth of time as it happens…

I made a small mistake on the Gerbers for the USB connector. On the footprint I include a guideline on one of the mech layers to aid positioning of the connector at the board edge and I mistakenly included that mech layer on the Gerber export with the result being a small sliver of exposed copper at the board edge on both sides under the USB connector. It makes no difference to the viability of the board but I find it annoying because I know it shouldn’t be there!

I’ve included M3 sized screw holes that can be used for adding ‘feet’ to the board so it’s lifted above my work surface and if you look at the back you can see that there are some handy quick-reference tables that identify which pins are connected to the commonly used peripherals.

Now it’s time to build it. I don’t have a paste stencil for this board so I opted to build it in several stages. Firstly I tinned all the surface mount pads with solder. Secondly, I reflowed the larger surface mount components such as all the ICs, the inductor and the USB connector using my bluetooth reflow oven. Thirdly I attached all the smaller 0603 and 0805 components using hot air and tweezers and finally the through-hole components were soldered into place using an iron. A quick wash with hot water and fairy liquid followed by drying overnight and she’s ready to test.

Looking pretty sweet I think. But does it work? Let’s run through some tests to see what it can do.

Testing the functionality

The first test is simply to connect the USB cable from the board to a computer and then test the voltages to make sure the regulator is working. My multimeter read bang on 3.30V from the regulator output and the green power LED, D2, was lit at a nice subtle brightness. Another bugbear of mine is dev boards that include power LEDs configured at retina-burning levels.

Before moving on to a programming test let’s have a look at the residual noise on the board’s 3.3V supply.

It looks reasonable. Noise levels are within +/- 100mV. Let’s get on with some programming tests. I started up OpenOCD from a Cygwin terminal and got the expected output:

Open On-Chip Debugger 0.9.0 (2015-05-19-12:09)
Licensed under GNU GPL v2
For bug reports, read
        http://openocd.org/doc/doxygen/bugs.html
Info : The selected transport took over low-level target control. The results might differ
       compared to plain JTAG/SWD
adapter speed: 1000 kHz
adapter_nsrst_delay: 100
none separate
srst_only separate srst_nogate srst_open_drain connect_deassert_srst
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : clock speed 950 kHz
Info : STLINK v2 JTAG v17 API v2 SWIM v4 VID 0x0483 PID 0x3748
Info : using stlink api v2
Info : Target voltage: 3.243836
Info : stm32f0x.cpu: hardware has 4 breakpoints, 2 watchpoints

This means that the MCU is responding to the SWD debugging commands and is ready to program. Now to test the onboard features. I’ll use my stm32plus library for all these tests. Even though it does not directly support the F042 series it does support the F051 and with a few adjustments to startup code and linker scripts we should be able to get things going.

Blinky

The first thing we need to do is modify the linker script designed for the F051 to be compatible with the F042. The section at the top needs to be changed to reflect the 32Kb of flash and the 6Kb of SRAM in the F042. These are the changes:


/* End of 6Kb SRAM */
_estack = 0x20001800;

/* Generate a link error if heap and stack don't fit into RAM */

_Min_Heap_Size = 0;      /* required amount of heap  */
_Min_Stack_Size = 0x400; /* required amount of stack */

/* Specify the memory areas */

MEMORY
{
  FLASH (rx)      : ORIGIN = 0x08000000, LENGTH = 32K
  RAM (xrw)       : ORIGIN = 0x20000000, LENGTH = 6K
  MEMORY_B1 (rx)  : ORIGIN = 0x60000000, LENGTH = 0K
}

For now we do not need to modify the code where the core clock is set System.c because it’s already set up to use the PLL fed by the 8MHz HSI. The core clock will be 48MHz.

The onboard LED, D3, is hooked up to PB1. It’s a simple modification to the source code to flash this LED at 1Hz.

void run() {

  // initialise the pin for output

  GpioB<DefaultDigitalOutputFeature<1> > pb;

  // loop forever switching it on and off with a 1 second
  // delay in between each cycle

  for(;;) {

    pb[1].set();
    MillisecondTimer::delay(1000);

    pb[1].reset();
    MillisecondTimer::delay(1000);
  }
}

I fired it up and… success! The amber LED was flashing away at 1Hz. Programming, basic GPIO and the Systick peripheral are all working fine.

The transistor switch

This test is closely related to the basic blinky except this time I connected an external LED and series resistor to the LD (load) pin and change the code to control the blinking to use pin PA7.

It’s working as expected which validates that the NPN transistor is connected up correctly.

What about the external crystal?

I’m not done with the blinkenled just yet. Before I can move on I need to know if the external 8MHz crystal is working which means configuring it as the MCU clock source. Luckily this is really simple.

If you look inside the System.c startup file you’ll see that ST have provided a simple #define to select the clock source. To configure the HSE as the clock source we merely have to change the code to read like this:

//#define PLL_SOURCE_HSI   // HSI (~8MHz) used to clock the PLL, and the PLL is used as system clock source
#define PLL_SOURCE_HSE           // HSE (8MHz) used to clock the PLL, and the PLL is used as system clock source
//#define PLL_SOURCE_HSE_BYPASS  // HSE bypassed with an external clock (8MHz, coming from ST-Link) used to clock
                                 // the PLL, and the PLL is used as system clock source

Testing a timer

The pin that I’ve attached to the LED, PB1, is also the GPIO output for channel 4 of timer 3. It’s a simple task to set up that timer in PWM mode and then to create a quick demo that pulses the LED as smooth ‘heartbeat’.

void run() {

  Timer3<
    Timer3InternalClockFeature,       // the timer clock source is APB1
    TimerChannel4Feature<>,           // we're going to use channel 4
    Timer3GpioFeature<                // we want to output something to GPIO
      TIMER_REMAP_NONE,               // the GPIO output will not be remapped
      TIM3_CH4_OUT                    // we will output channel 4 to GPIO
    >
  > timer;

  /*
   * Set an up-timer up to tick at 12MHz with an auto-reload value of 1999
   * The timer will count from 0 to 1999 inclusive then reset back to 0.
   */

  timer.setTimeBaseByFrequency(12000000,1999);
  timer.initCompareForPwmOutput();
  timer.enablePeripheral();

  /*
   * It's all running automatically now, use the main CPU to vary the duty cycle up
   * to 100% and back down again
   */

  for(;;) {

    // fade up to 100% in 4ms steps

    for(int8_t i=0;i<=100;i++) {
      timer.setDutyCycle(i);
      MillisecondTimer::delay(4);
    }

    // fade down to 0% in 4ms steps

    for(int8_t i=100;i>=0;i--) {
      timer.setDutyCycle(i);
      MillisecondTimer::delay(4);
    }
  }
}

This worked as planned and you can see the pulsating heartbeat LED in the video linked in at the end of this article.

Testing USB

stm32plus currently only has support for USB on the F4 which means that to test the USB interface I’m going to have to hold my nose and dive into that horrendous unreadable mess that’s otherwise known as the STM32 HAL. Taking the ‘custom HID’ example as a starting point, I proceeded to adapt it from the F072 target to the F042 and here’s some lessons I picked up along the way.

Remap PA11 and PA12 to USB_DP and USB_DM

When the MCU starts up PA11 and PA12 are configured for GPIO. The USB D+ and D- lines are actually on PA9 and PA10 and you need to map these two pins in place of PA11 or PA12. If you fail to do this then the USB interrupt will never fire. Here’s how:

// Remap PA11-12 to PA9-10 for USB

RCC->APB2ENR |= RCC_APB2ENR_SYSCFGCOMPEN;
SYSCFG->CFGR1 |= SYSCFG_CFGR1_PA11_PA12_RMP;

Way back in this article I promised to show you how to clock the MCU from the internal HSI48 oscillator and then use the SOF frames sent every 1ms by the host to continuously trim the clock to stay in sync with the host. Clocking your MCU like this means that you don’t have to use an external crystal which cuts costs and reduces board space.

Here’s the replacement SetSysClock() function that you can plug into System.c.


void SetSysClock() {

  // enable flash prefetch buffer

  FLASH->ACR |= FLASH_ACR_PRFTBE;

  // enable HSI48

  RCC->CR2 |= RCC_CR2_HSI48ON;
  while((RCC->CR2 & RCC_CR2_HSI48RDY)==0);

  // disable the PLL

  RCC->CR &=~ RCC_CR_PLLON;
  while((RCC->CR & RCC_CR_PLLRDY)!=0);

  // select HSI48 as the USB clock source

  RCC->CFGR3 = (RCC->CFGR3 &~ RCC_CFGR3_USBSW) | RCC_CFGR3_USBSW_HSI48;

  // set flash latency = 1

  FLASH->ACR = (FLASH->ACR &~FLASH_ACR_LATENCY) | FLASH_Latency_1;

  // AHB

  RCC->CFGR = (RCC->CFGR &~ RCC_CFGR_HPRE) | RCC_CFGR_HPRE_DIV1;

  // HCLK source = HSI48

  RCC->CFGR = (RCC->CFGR &~ RCC_CFGR_SW) | RCC_CFGR_SW_HSI48;
  while((RCC->CFGR & RCC_CFGR_SWS)!=RCC_CFGR_SWS_HSI48);

  // PCLK1

  RCC->CFGR = (RCC->CFGR &~ RCC_CFGR_PPRE) | RCC_CFGR_PPRE_DIV1;

  // enable clock recovery system from USB SOF frames

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_CRS,ENABLE);

  // Before configuration, reset CRS registers to their default values

  RCC->APB1RSTR |= RCC_APB1RSTR_CRSRST;
  RCC->APB1RSTR &=~ RCC_APB1RSTR_CRSRST;

  // Configure Synchronization input */
  // Clear SYNCDIV[2:0], SYNCSRC[1:0] & SYNCSPOL bits */

  CRS->CFGR &= ~(CRS_CFGR_SYNCDIV | CRS_CFGR_SYNCSRC | CRS_CFGR_SYNCPOL);

  // Set the CRS_CFGR_SYNCDIV[2:0] bits according to Prescaler value
  // CRS->CFGR |= 0;

  // Set the SYNCSRC[1:0] bits according to Source value

  CRS->CFGR |= CRS_CFGR_SYNCSRC_1;

  // Set the SYNCSPOL bits according to Polarity value
  // CRS->CFGR |= 0;

  // Configure Frequency Error Measurement
  // Clear RELOAD[15:0] & FELIM[7:0] bits

  CRS->CFGR &= ~(CRS_CFGR_RELOAD | CRS_CFGR_FELIM);

  // Set the RELOAD[15:0] bits according to ReloadValue value

  CRS->CFGR |= 47999;     // (48MHz/1000) -1

  // Set the FELIM[7:0] bits according to ErrorLimitValue value

  CRS->CFGR |= (0x22 << 16);

  // Adjust HSI48 oscillator smooth trimming
  // Clear TRIM[5:0] bits

  CRS->CR &= ~CRS_CR_TRIM;

  // Set the TRIM[5:0] bits according to RCC_CRS_HSI48CalibrationValue value

  CRS->CR |= (0x20 << 8);

  // Enable Automatic trimming

  CRS->CR |= CRS_CR_AUTOTRIMEN;

  // Enable Frequency error counter

  CRS->CR |= CRS_CR_CEN;
}

With those modifications in place I was able to hack together a build for the ‘custom HID’ example and after a bit of gentle persuasion it actually worked. Here’s the device descriptor dump as reported by the ‘USBView’ Windows debugging utility:

Device Descriptor:
bcdUSB:             0x0200
bDeviceClass:         0x00
bDeviceSubClass:      0x00
bDeviceProtocol:      0x00
bMaxPacketSize0:      0x40 (64)
idVendor:           0x0483 (STMicroelectronics)
idProduct:          0x5750
bcdDevice:          0x0200
iManufacturer:        0x01
iProduct:             0x02
iSerialNumber:        0x03
bNumConfigurations:   0x01

When a USB device is inserted there is a flurry of very fast interrupt-driven data exchange between the host and the device as the host first queries for the device descriptor and then, based on what it receives, comes back with a sequence of further queries for the other standard descriptors. Only if all that goes well will the host accept the device and allow its descriptors to be queried in tools like ‘USBView’.

So now I know that everything on the board works. All the features have been tested and I can happily use it for development and testing on the F042 platform going forward.

Watch the video

There’s a short video to go with this article where I just walk through the board features and then briefly show the programming and demo code.

Lessons learned

When a project comes to a close and you have time to reflect then there’s always one or two things that you’d do differently and this one’s no different. Here are a few things that I’d do differently.

The ‘boot’ selector header is too close to the SWD header. With the SWD cable connected it would be a very tight fit to get a jumper across to select the RAM boot option.

If I were to shuffle a few components around I think I could probably stretch to a push-button on the board. It’s always nice to have a button.

The VDDA selection is a bit clunky. Selecting the internal 3.3V supply as the VDDA source with a jumper is obvious enough but it’s not obvious that to use an external VDDA you have to remove the jumper and connect your external supply to pin 3 in that header block. Pin 4 is effectively redundant.

Breadboard compatibility. If I increased the board size to the 10x5cm format then I’d have enough space to make the pin headers single row and thereby plug directly into a breadboard.

Get the Gerbers

Want to build this board yourself? If you can handle a 0.65mm pitch IC and a generous sprinkling of 0603 passives then you should find this a breeze to build. Head on over to my downloads page to get yourself a copy of gerbers that can be directly uploaded to Elecrow, ITead, Seeed or any other of your favourite prototyping houses.

Bare PCBs for sale

I’ve got quite a few of these blank boards left over from the batch that I received from Elecrow and I’m happy to sell them on a first-come-first-served basis.

Location
Worldwide delivery £3.50 GBP
UK only delivery £2.00 GBP

Final words

That’s all for now, I hope you’ve enjoyed this article and if you’d like to leave a comment then please do so in the comments section below. Alternatively if you got a bit more to say then please head over to the forum and speak your mind!


RFM69 to MQTT gateway using ESP8266

$
0
0

RFM69 to MQTT gateway using ESP8266
Martin / 1 week ago
I’ve mentioned my plans for this project during the IoT hangout session few months ago, it has finally materialized as working prototype. The blocker so far was the lack of ESP8266 RFM69 driver and free time on my end, so I’ve teamed up with Andrey Balarev to solve this. Andrey is an IoT enthusiast + embedded systems developer and has done excellent job in porting LowPowerLab’s RFM69 library for the ESP8266. He spent few weekends staring at the oscilloscope, re-writing SPI library code and managed to solve a number of challenges to get this library going. I’ve bundled his driver code with MQTT to get a beautifully working prototype that forwards RFM69 traffic to MQTT and vice versa. Few screenshots of the setup:

The prototype on veroboard
The prototype on veroboard
The RFM69 configuration UI
The RFM69 configuration UI
Serial debug output
Serial debug output
MQTT broker capture
MQTT broker capture

Some folks probably ask why the RFM69 and not RFM12B and why LowPoweLab’s library and not Jeelib, I’ve outlined my view on that before here. Basically with Jeelib we are forcing the RFM69 in artificial compatible mode and not taking fill advantage of the chip.

What I plan to add as functionality is payload serialization configuration, payload field name configuration and RPN based signal processing configuration so that JSON could be constructed/deconstructed from payloads in both directions.

It will be a replacement for the RFM2Pi project, a much more advanced standalone M2M gateway for the IoT.

I’ll build few PCBs and put some for sale in my shop as well. RFM69 library code will be shared at that point.


An iOS Developer on React Native

$
0
0

An iOS Developer on React Native

When I first caught wind of React Native, I thought of it as nothing more than a way for web developers to dip their feet into native mobile apps. The premise that JavaScript developers could write an iPhone app in JavaScript was definitely something that I thought was really cool, but I quickly shrugged off the idea of using it myself. After all, I had already been doing native iOS development as a hobby for many years, and professionally with Chalk + Chisel (formally Bolster) for almost two years at that point.

I had already made dozens of iOS apps — good apps that I was proud of. Apps built in Xcode and written in Objective-C, because that’s the way it’s always been. That’s what Apple gave us to make iOS apps, so that’s what I and every other developer used. Then, two years ago when Apple released the Swift programming language, I didn’t hesitate to try it out.

It was still in Xcode, and it was still (obviously) Apple-approved for developing iOS apps, so I dove right in and picked it up pretty — ahem — swiftly. I was content in my Apple ecosystem bubble. React Native seemed like a fun little experiment, but in my mind any real native app would still need to be written the real native way. It seemed like a waste of time for me to not only learn JavaScript (I had no experience), but an entirely new way of building apps when I was already beginning to master building them the “real” way.

Fast-forward a couple of months, and I’m confident enough to say I may never write an iOS app in Objective-C or Swift again.

We received a new mobile app project and I reviewed the requirements and designs. Just as I was about to click that beautiful blue Xcode icon to start a new project, our Interactive Director, Adam, walks over and says, “let’s do this one in React Native”.

He explained that part of our contract for this project was to have a clear path going forward to make this app available for Android as well . And although React Native was not yet available for Android, we knew Facebook was actively working on it. Theoretically, if we built the app in React Native for iOS, many parts of it would “just work” on Android by the time it was released.

Well, I wasn’t happy. I felt as if I was at the peak of my iOS development ability and was being asked to throw it all away. I doubted my own abilities to deliver a quality product on time given the inevitable learning curve. But even more than that, I doubted React Native in itself being capable of producing a quality product. Looking back, I don’t even think that doubt was unjustified. At the time, React Native had just come out as a beta. The documentation was lacking, the amount of open sourced React Native libraries and components was minuscule, and example code or Stack Overflow posts for reference were almost nonexistent.

I begrudgingly gave it a shot. But going in with my closed-mind attitude only did more harm. My first hurdle was learning Flexbox, React Native’s way of doing UI layout. Coming from the land of interface builder, laying out UI completely in code frustrated me beyond belief. I struggled to build even the most simple of views.

But it wasn’t just UI — everything was different. That was the biggest point of contention for me.

Every time I got stuck or didn’t understand something, I would tell myself “I could do this in 5 seconds in Objective-C”. Every time I would discover a bug in React Native (and there were a good number), I would think, “this bug doesn’t exist in Objective-C, why am I fighting with it?”

For a solid two weeks I was miserable at work. I had gone from feeling like an expert iOS developer to feeling like I’d never written a line of code in my life. It was defeating, until I took a weekend to clear my head. I took a step back and recognized that Adam had done a lot of research on React Native. I had to trust him as our Interactive Director to not be leading me down a bad path. I vowed to go into work Monday, put my head down, pretend Objective-C and Swift don’t even exist, and figure this thing out.


Learning to Love React

A few weeks ago, we submitted our first React Native app to the App Store. I’m extremely proud of how the app turned out, and I can’t wait to write our next one. In just a little over a month, consider me fully aboard the React Native train. What changed my mind?

The React Paradigm

In React, every piece of UI that is or ever will be lives in the render() method, and is controlled with “state”. Your render() method defines how the UI should look for each state, and upon calling setState(), React figures out what needs to change and does it for you. Imagine a simple view with a label that says “Hello World” and a button. Each click of the button needs to change the label between “Hello World” and “Goodbye World”. In Objective-C, I would need some ugly if statement in my button handler like

if ([label.text isEqual:@”Hello World”]) {
    label.text = @”Goodbye World”;
} else {
    label.text = @”Hello World”;
}

It works fine, but that UI code is completely disjointed from where I created the label in the first place (which could be in code or in interface builder). In React, we would define a buttonClicked bool in our state, our label in render() would look something like:

<Text>
    {this.state.buttonClicked ? ‘Hello World’ : ‘Goodbye World’}</Text>

and our button handler is as simple as:

this.setState({buttonClicked: !this.state.buttonClicked});

All the view code is in one place, and state controls all. This makes comprehending and debugging the code so much easier.

Flexbox

The UI layout tool that I hated so much at first is now one of my favorite things about React Native. I will admit that it is tough to grasp at first, but once you do it makes building UI’s for the variety of different screen sizes extremely fast and easy. I had become addicted to the visual aids of Interface Builder in Xcode. Autolayout now seems overly complex compared to Flexbox. The CSS-esque styling that Flexbox uses makes style reuse as easy as copy paste. And the best part of all allows you to tweak style values to perfection in no time…

Live/Hot Reload

That’s right. Seeing what your button would look like moved over 5 more pixels to the right is as easy as Command+S. React Native can be configured to automatically re-render the current view in the iPhone Simulator without rebuilding the Xcode project. This is huge because not only do you save time by not rebuilding, but you could be working on a view that is nested deep within the app and tweak the UI without having to navigate all the way back to that screen.

Android

It’s still not out yet, but it’s coming — and it’s going to be amazing. I was hesitant about React Native at first because I already liked doing native iOS development. I didn’t have any complaints about it. But I’ve also done native Android development, and it’s not great. React Native will be very welcome on Android, and I am counting down the days until it’s here. This will revolutionize mobile app development by being able to deploy to 2 platforms with 1 code base.

[Update: Since the publication of this post, React Native for Android has been released. To learn more about it, visit: https://facebook.github.io/react-native/]


Retrospective

Missing Xcode

I still miss Xcode, or really just an IDE in general. I’ve worked toward a pretty good React Native development setup, but it wasn’t easy. Sublime Text and a bunch of plugins later and I have good syntax highlighting and linting. Sublime can autocomplete based off other variables and things within the same file, but is lacking some of the robustness of Xcode’s autocomplete. I still have to leave the React documentation up all the time to use as a reference.

Little things like typing React.PropTypes.f and having the IDE not tell me whether I’m looking for ‘func’ or ‘function’ can be bothersome. I also miss Xcode’s version editor — which allowed me to compare a file side-by-side with that file at my last git commit and even undo specific changes on a per line basis. I realize a third party program could help me accomplish this, but one of the great things about IDEs is the all-in-one package.

To run a React Native project, I need to launch my terminal to start the npm packager, Chrome for the debugger, Sublime to edit my code, and ultimately Xcode to run the project and start the simulator. These are all minor complaints in the grand scheme of things, but still a con for me when it comes to React Native. I have high hopes that Nuclide (Facebook’s IDE) will alleviate some or all of these cons.

Bridging

Facebook hasn’t and isn’t going to port every API from iOS to React Native, so for the missing pieces they’ve provided a way to “bridge” things over to JavaScript. Again, when I first got into React Native, the documentation on this was really bad. Every time I realized I needed to bridge something, I wanted to give up on React Native altogether because naturally those things already work in Objective-C. But once they explained the bridging process in more detail, and provided good examples, it wasn’t as intimidating. It still is a hassle, but eventually I could see every bridge imaginable being made open source and available on npm. In fact, most iOS APIs already are.

Bugs, Documentation, Open Source Community

Most, if not all, of my initial complaints about React Native wouldn’t even exist if I started learning it today. Bugs are fixed daily, and new releases seem to pop up every week or so. The documentation still needs work, but has greatly improved. Facebook and the open source community in general are clearly very serious about developing this framework. It’s nice to see people actively engaged in React Native issues on GitHub and questions on Stack Overflow. If you are an iOS developer considering playing with React Native, know that you aren’t alone. React Native is wonderful, and you should try to embrace it with an open mind. Don’t pigeonhole yourself into what is comfortable like I did.

Step outside of your comfort zone and you may just find something even better than before.

Marc Shilling
is an interactive developer at Chalk + Chisel, a digital product agency, in Baltimore, MD.


LoNet 808 – Mini GSM + GPS Board

$
0
0

LoNet 808 – Mini GSM + GPS Board

Description

LoNet 808 is a mini board based on the latest SIM808 module, it offers 2G GSM and GPRS data along with GPS technology for satellite navigation. Also supports assisted-GPS (A-GPS) for indoor localisation.

The board features ultra-low power consumption, working current is low to 1mA when in sleep mode. That gives your the project incredibly long standby times. It uses a serial port communication, supports common 3GPP TS 27.007, 27.005 and SIMCOM enhanced AT commands.  Integrated with battery charging circuit, it is powered by 3.7V Lipo battery and can be charged by 5V micro-USB directly.

It comes with a mini GPS and GSM antenna, however a external Lipo battery is required.

113990107 0

Features

  • Quad-band 850/900/1800/1900MHz
  • GPRS multi-slot class12 connectivity: max. 85.6kbps(down-load/up-load)
  • GPRS mobile station class B
  • Controlled by AT Command (3GPP TS 27.007, 27.005 and SIMCOM enhanced AT Commands)
  • Supports charging control for Li-Ion battery
  • Supports Real Time Clock
  • Supply voltage range 3.4V ~ 4.4V
  • Integrated GPS/CNSS and supports A-GPS
  • Supports 3.0V to 5.0V logic level
  • Low power consumption, 1mA in sleep mode
  • Supports GPS NMEA protocol
  • Compact size 27mm x 46mm x 10mm
  • Standard SIM Card

GPS  Features

  • Receiver channels: 22 tracking / 66 acquisition
  • Coarse/Acquisition code: GPS L1
  • Tracking sensitivity: -165dBm
  • Cold start time: 30s (typ.)
  • Hot start time: 1s (typ.)
  • Warm start time: 28s (typ.)
  • Horizontal position accuracy: < 2.5m CEP
  • Power consumption – Acquisition: 42mA
  • Power consumption – Continuous tracking: 24mA
  • Update rate: 5Hz

Related Products

Hardware Interface

top

  1. Power Button – this is the hard power switch for the module. When the module is power up, you can turn on or turn off the module by pressing the button for 2s.
  2. Li-ion Battery – this is power supply for the module, input voltage is from 3.4V to 4.4V. It uses the JST-2.0mm connector, that make it convenient to connect to 3.7V Li-Po Battery.
  3. MicroUSB – the charging interface for Li-Ion battery, of input voltage range from 5V to 7V.
  4. GSM Antenna – this is an uFL GSM antenna connector, just connect it to a GSM antenna for receiving GSM signal.
  5. GPS Antenna – this is an uFL GPS antenna connector. You can connect either passive or active GPS antenna to it. Active GPS antenna runs at 2.8V voltage.
  6. Net Indicator – Red LED, it will tell the what status is about the module linking to network.
  7. Status Indicator – Green LED, it will tell whether the module is on, light when the module is running.
  8. Breakout Pin – see Pin Definitions for more details.
  9. SIM – Card Holder – SIM card holder for standard SIM card
  10. Power Supply Pin – used for power soldering and testing.

Pin Definitions

NAME I/O DESCRIPTION NOTE
BAT I/0 Power input / output 3.4V – 4.4V DC
GND I/0 Power ground / logic ground
VIO I Logic level reference 2.8V – 5.0V DC
DTR I Sleep mode controlled pin Pull high for sleep mode
PWR O Power switch Active low in 2s
RI O Event/ message pin
TXD O Transmit data UART output from SIM808
RXD I Receive data UART Input to SIM808
RST I Reset pin Active low

Pin Description

  • PWR – this is soft power switch for the module, you can pull it to high level for at least 2s to power up or power down the module.
  • RI – this pin will tell you whether the module is on and is there any calls and messages received. It will be pulled to high level when the module is on. And it will change to low for 120ms when a call or message is received.
  • RST – this is reset pin for the module. By default it has a high pull-up. If you absolutely got the module in a bad space, you can pull it to low level for 100ms to perform a hard reset.
  • RXD / TXD – Serial port, the module uses it to send and receive commands and data. TXD is output, and RXD is input. They can be connected to the 3.3V and 5V level.
  • VIO – this is the reference logic level for serial port of the module, the input voltage depends on the logical level of the miccontroller you use. If you use a 5V miccontroller like Arduino, you should have it be 5V, and a 3V logic miccontroller you should set it to 3V.
  • BAT – this pin is connected to Li-Ion battery pin, if you want to use only one Li-Ion battery as your power supply, you can use it to drive you microcontroller.
  • DTR – this is wake up pin for module in sleep mode. By default it has a high pull-up, and you can set the module into sleep mode by AT command “AT+CSCLK=1”. In the meantime, the serial port will be disabled. To wake up the module and enable serial port, you can pull this pin to low level for about 50ms.

Indicator LEDs

INDICATOR LEDS STATUS BEHAVIOR
Operating Status (Green) Off SIM808 is not running
On SIM808 is running
Network Status (Red) Off SIM808 is not running
64ms on/ 800ms Off SIM808 not registered to the network
64ms On/ 3000ms Off SIM808 registered to the network
64ms On/ 300ms Off PPP GPRS communication is established

Reference Circuit

Connect to Microcontroller

CONS1-01

Connect to PC

CONS2-01

Testing AT Command with Arduino

// this sketch is used for testing LoNet with Arduino

// Connect VIO to +5V
// Connect GND to Ground
// Connect RX (data into SIM800L) to Digital 11
// Connect TX (data out from SIM800L) to Digital 10

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  mySerial.begin(9600);

}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());

  if (Serial.available())
  {
    while(Serial.available())
    {
      mySerial.write(Serial.read());
    }
    mySerial.println();
  }
}

Set Baud and Enable Charging Function

It is recommended to execute this process when first time to use the module. In the Serial Monitor columns of tables, input of AT commands are in back, module returns values are in orange.

SERIAL MONITOR DESCRIPTION
AT
OK
Send command “AT” to synchronize baud rate. Serial port of module is by default set at auto-baud mode, and in this mode, it will not output any indications when the module is on.
AT+IPR=9600
OK
Set baud rate at 9600bps, supports baud rate from 1200bps to 115200bps.
AT+ECHARGE=1
OK
Send command “AT+ECHARGE=1” to enable battery charging function. By default the charging function is closed.
AT&W
OK
Save parameter setting.
AT+CPOWD=1
NORMAL POWER DOWN
Power down the module.
RDY
+CFUN: 1
GPS Ready
+CPIN: READY
Call Ready
SMS Ready
Turn on the module again by the power button, it will response status about GPS and GSM.
AT+CBC
+CBC: 1,96,4175
OK
Inquire charging status and remaining battery capacity.
AT+CSQ
+CSQ: 14,0
OK
Inquire GSM signal quality.

Get location with GPS

SERIAL MONITOR DESCRIPTION
AT+CGPSPWR=1
OK
Open GPS
AT+CGPSSTATUS?
+CGPSSTATUS: Location Not Fix
OK
Read GPS fix status, “Location Not Fix” means that positioning is not successful. For the first time to start, it will take at least 30s. GPS must be tested by the window or outdoor.
AT+CGPSSTATUS?
+CGPSSTATUS: Location 3D Fix
OK
GPS has fixed with 3D status.
AT+CGPSINF=0
+CGPSINF:
0,2234.931817,11357.122485,
92.461185,20141031041141.000,
88,12,0.000000,0.000000
Get the current GPS location information. Parameters formate: <mode>, <altitude>, <longitude>, <UTC time>, <TTFF>, <num>, <speed>, <course>
AT+CGPSOUT=32
OK
$GPRMC,043326.000,A,
2234.9414,N,11357.1187,E,
0.000,143.69,311014,,,A*50
Read NMEA $GPRMC data, of which, “2234.9414 N, 11357.1187 E” is the location coordinates. For more details about NMEA sentences, check this site.
AT+CGPSRST=0
OK
Reset GPS in Cold Start Mode.
AT+CGPSRST=1
OK
Reset GPS in Hot Start Mode.
AT+CGPSPWR=0
OK
Close GPS.

Downloads

Related Resources

Support

Any question, document mistakes and suggestions , please contact deray@deegou.com.

We are not good at programming,  for basis questions we will try to help. But for complex problem, we may not be able to help.

To the end, thank you for your reading.


C.H.I.P Simple GPIO Experiments

$
0
0

Simple GPIO Experiments

CHIP has several General Purpose Input/Output (GPIO) pins available for you to build around. If you want to access them in a very primitive way, just to confirm their existence, here’s some things to try.

How You See GPIO

There are eight (8) GPIO pins always available for connecting CHIP to the sense-able world. These are in the middle of the right header, U14, Pins 13-20, labeled XIO-P0 to P7:

How The System Sees GPIO

There is a sysfs interface available for the GPIO. This just means you can access the GPIO states in a file-system-like manner. For example, you can reference XIO-P0 using this path:

/sys/class/gpio/gpio408/

which you can see is somewhat unfortunate, since the sysfs names do not match the labels on our diagram! But is not too hard to translate. PinsXIO-P0 to P7linearly map to gpio408 to gpio415.

Some GPIO Switch Action

These lines of code will let us read values on pin XIO-P7. First, we tell the system we want to listen to this pin:

echo 415 > /sys/class/gpio/export

View the mode of the pin. It should return “in”:

cat /sys/class/gpio/gpio415/direction

Connect a jumper wire between Pin 20 (XIO-P7) and Pin 39 (GND). Now use this line of code to read the value:

cat /sys/class/gpio/gpio415/value

Some GPIO Output

You could also change the mode of a pin from “in” to “out”

echo out > /sys/class/gpio/gpio415/direction

Now that it’s in output mode, you can write a value to the pin:

echo 1 > /sys/class/gpio/gpio415/value

Enough IO

When you are done experimenting, you can tell the system to stop listening to the gpio pin:

echo 415 > /sys/class/gpio/unexport

Learn More

You can learn a bit more about GPIO and Linux here:https://www.kernel.org/doc/Documentation/gpio/sysfs.txt

Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.

Viewing all 759 articles
Browse latest View live