Category Archives: 无线电小组

(中文) 超声波雷达-创客开源 Arduino项目

//淘宝『创元素店』https://shop423015102.taobao.com/ //更新日期 2021/03/06 //MiniRadar 超声波雷达 程序 //本程序对应商品 https://item.taobao.com/item.htm?spm=a1z10.1-c.w4004-23815833841.8.4f231fe7qvLFZi&id=649834806872

//Github版链接: https://github.com/johnsonwust/MiniRadar

include

include

include "Ucglib.h"

//显示屏的lib 如果没有该lib请按Ctrl+Shift+I 从 库管理器中搜索 ucglib,并安装

define trigPin 6 //超声波模块的Trig口 6

define echoPin 5 //超声波模块的echo口 5

define ServoPin 3 //底座舵机端口 3

int Ymax = 128; //屏幕的竖向像素数 int Xmax = 160; //屏幕的横向像素数 int Xcent = Xmax / 2; //x中位 int base = 118; //基线高度 int scanline = 105; //雷达扫描线长度

Servo baseServo; Ucglib_ST7735_18x128x160_HWSPI ucg(/cd=/ 9, /cs=/ 10, /reset=/ 8);

void setup(void) {

  ucg.begin(UCG_FONT_MODE_SOLID); //初始化屏幕
  ucg.setRotate90();              //设置成横屏  如果屏幕显示方向是反的,可以修改函数 setRotate90 或 setRotate270

  pinMode(trigPin, OUTPUT);       //设置trigPin端口模式
  pinMode(echoPin, INPUT);        //设置echoPin端口模式
  Serial.begin(115200);             //设置串口传输率
  baseServo.attach(ServoPin);     //初始化舵机

  //欢迎屏幕
  ucg.setFontMode(UCG_FONT_MODE_TRANSPARENT);
  ucg.setColor(0, 0, 100, 0);
  ucg.setColor(1, 0, 100, 0);
  ucg.setColor(2, 20, 20,20);
  ucg.setColor(3, 20, 20, 20);
  ucg.drawGradientBox(0, 0, 160, 128);
  ucg.setPrintDir(0);
  ucg.setColor(0, 5, 0);
  ucg.setPrintPos(27,42);
  ucg.setFont(ucg_font_logisoso18_tf);  
  ucg.print("Mini Radar");
  ucg.setColor(0, 255, 0);
  ucg.setPrintPos(25,40);
  ucg.print("Mini Radar");
  ucg.setFont(ucg_font_helvB08_tf);
  ucg.setColor(20, 255, 20);
  ucg.setPrintPos(40,100);
  ucg.print("Testing...");
  baseServo.write(90);

  //测试底座的运行情况,注意检测底座位置和转动姿态,是否有卡住(或者导线缠绕)的情况。
  for(int x=0;x<180;x+=5)
      { baseServo.write(x);
        delay(50);
       }
  ucg.print("OK!");
  delay(500);

  //清屏
  //ucg.clearScreen();
  cls();
  ucg.setFontMode(UCG_FONT_MODE_SOLID);
  ucg.setFont(ucg_font_orgv01_hr);

}

void cls() { //清屏 ucg.setColor(0, 0, 0, 0);

for(int s=0;s<128;s+=8) for(int t=0;t<160;t+=16) { ucg.drawBox(t,s,16,8); // delay(1); }

}

int calculateDistance() { long duration; //trigPin断电 并 等待2微妙 digitalWrite(trigPin, LOW); delayMicroseconds(2); //trigPin加电 延时 10微妙 再断电 digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); //读取echoPin返回声波的传播时间(微妙) duration = pulseIn(echoPin, HIGH); //将回声时间转换成距离数值 return duration*0.034/2; }

void fix_font() { ucg.setColor(0, 180, 0); ucg.setPrintPos(70,14); ucg.print("1.00"); ucg.setPrintPos(70,52); ucg.print("0.50"); ucg.setPrintPos(70,90); ucg.print("0.25"); }

void fix() {

  ucg.setColor(0, 40, 0);
  //画基线圆盘
  ucg.drawDisc(Xcent, base+1, 3, UCG_DRAW_ALL); 
  ucg.drawCircle(Xcent, base+1, 115, UCG_DRAW_UPPER_LEFT);
  ucg.drawCircle(Xcent, base+1, 115, UCG_DRAW_UPPER_RIGHT);
  ucg.drawCircle(Xcent, base+1, 78, UCG_DRAW_UPPER_LEFT);
  ucg.drawCircle(Xcent, base+1, 78, UCG_DRAW_UPPER_RIGHT);
  ucg.drawCircle(Xcent, base+1, 40, UCG_DRAW_UPPER_LEFT);
  ucg.drawCircle(Xcent, base+1, 40, UCG_DRAW_UPPER_RIGHT);
  ucg.drawLine(0, base+1, Xmax,base+1);

  ucg.setColor(0, 120, 0);
  //画刻度表
   for(int i= 40;i < 140; i+=2)
   {

    if (i % 10 == 0) 
      ucg.drawLine(105*cos(radians(i))+Xcent,base - 105*sin(radians(i)) , 113*cos(radians(i))+Xcent,base - 113*sin(radians(i)));
    else

     ucg.drawLine(110*cos(radians(i))+Xcent,base - 110*sin(radians(i)) , 113*cos(radians(i))+Xcent,base - 113*sin(radians(i)));
   }

   //画一些装饰性图案 
   ucg.setColor(0,200,0);
   ucg.drawLine(0,0,0,18);
   for(int i= 0;i < 5; i++)
   {
      ucg.setColor(0,random(200)+50,0);
      ucg.drawBox(2,i*4,random(14)+2,3);
   }

   ucg.setColor(0,180,0);
   ucg.drawFrame(146,0,14,14);
   ucg.setColor(0,60,0);
   ucg.drawHLine(148,0,10);
   ucg.drawVLine(146,2,10);
   ucg.drawHLine(148,13,10);
   ucg.drawVLine(159,2,10);

   ucg.setColor(0,220,0);
   ucg.drawBox(148,2,4,4);
   ucg.drawBox(148,8,4,4);
   ucg.drawBox(154,8,4,4);
   ucg.setColor(0,100,0);
   ucg.drawBox(154,2,4,4);

   ucg.setColor(0,90,0);
   ucg.drawTetragon(62,123,58,127,98,127,102,123);
   ucg.setColor(0,160,0);
   ucg.drawTetragon(67,123,63,127,93,127,97,123);
   ucg.setColor(0,210,0);
   ucg.drawTetragon(72,123,68,127,88,127,92,123);

}

void loop(void) {

int distance;

fix(); fix_font(); //重绘屏幕背景元素

for (int x=180; x > 4; x-=2){ //底座舵机从180~0度循环

  baseServo.write(x);             //调整舵机角度

  //绘制雷达扫描线
  int f = x - 4; 
  ucg.setColor(0, 255, 0);
  ucg.drawLine(Xcent, base, scanline*cos(radians(f))+Xcent,base - scanline*sin(radians(f)));
  f+=2;
  ucg.setColor(0, 128, 0);
  ucg.drawLine(Xcent, base, scanline*cos(radians(f))+Xcent,base - scanline*sin(radians(f)));
  f+=2;
  ucg.setColor(0, 0, 0);
  ucg.drawLine(Xcent, base, scanline*cos(radians(f))+Xcent,base - scanline*sin(radians(f)));
  ucg.setColor(0,200, 0);
  //测距
  distance = calculateDistance();

  //根据测得距离在对应位置画点
  if (distance < 100)
  {
    ucg.setColor(255,0,0);
    ucg.drawDisc(distance*cos(radians(x))+Xcent,-distance*sin(radians(x))+base, 1, UCG_DRAW_ALL);
  }
  else
  { //超过1米以上的,用黄色画在边缘区域示意
    ucg.setColor(255,255,0);
    ucg.drawDisc(116*cos(radians(x))+Xcent,-116*sin(radians(x))+base, 1, UCG_DRAW_ALL);
  }

  //调试代码,输出角度和测距值  
  Serial.print(x); 
  Serial.print("    ,   ");
  Serial.println(distance); 

  if (x > 70 and x < 110)  fix_font();  //扫描线和数字重合时,重绘数字

  ucg.setColor(0,155,  0);
  ucg.setPrintPos(0,126);
  ucg.print("DEG: "); 
  ucg.setPrintPos(24,126);
  ucg.print(x);
  ucg.print("  ");
  ucg.setPrintPos(125,126);
  ucg.print("  ");
  ucg.print(distance);
  ucg.print("cm  "); 

} //ucg.clearScreen(); //清屏 如果arduino供电不足,可能会引起白屏(显示信号中断)可以用 cls();函数代替 ucg.clearScreen(); delay(50); cls(); //如有频繁白屏情况,可以使用该函数 。或者增加外部供电

fix(); fix_font(); //重绘屏幕背景元素

for (int x=1; x < 176; x+=2){
baseServo.write(x); //调整舵机角度

  //绘制雷达扫描线
  int f = x + 4;
  ucg.setColor(0, 255, 0);
  ucg.drawLine(Xcent, base, scanline*cos(radians(f))+Xcent,base - scanline*sin(radians(f)));
  f-=2;
  ucg.setColor(0, 128, 0);
  ucg.drawLine(Xcent, base, scanline*cos(radians(f))+Xcent,base - scanline*sin(radians(f)));
  f-=2;
  ucg.setColor(0, 0, 0);
  ucg.drawLine(Xcent, base, scanline*cos(radians(f))+Xcent,base - scanline*sin(radians(f)));
  ucg.setColor(0, 200, 0);
  //测距
  distance = calculateDistance();

  //根据测得距离在对应位置画点
  if (distance < 100)
  {
    ucg.setColor(255,0,0);
    ucg.drawDisc(distance*cos(radians(x))+Xcent,-distance*sin(radians(x))+base, 1, UCG_DRAW_ALL);
  }
  else
  { //超过1米以上的,用黄色画在边缘区域示意
    ucg.setColor(255,255,0);
    ucg.drawDisc(116*cos(radians(x))+Xcent,-116*sin(radians(x))+base, 1, UCG_DRAW_ALL);
  }

  //调试代码,输出角度和测距值  
  Serial.print(x); 
  Serial.print("    ,   ");
  Serial.println(distance); 

  if (x > 70 and x < 110)  fix_font();  //扫描线和数字重合时,重绘数字

  ucg.setColor(0,155,  0);
  ucg.setPrintPos(0,126);
  ucg.print("DEG: "); 
  ucg.setPrintPos(24,126);
  ucg.print(x);
  ucg.print("   ");
  ucg.setPrintPos(125,126);
  ucg.print("   ");
  ucg.print(distance);
  ucg.print("cm   "); 

} //ucg.clearScreen(); // delay(50); cls();

}

SIM900 GPRS GSM Arduino Shiled

欧美出口品质,国产价格,限时特价,限量促销,机不可失

 

原理图: http://i-element.org/makerstudio/GPRS/GPRS_GSM%20Shield%20v1.0%20sch.pdf

 

使用手册: http://i-element.org/makerstudio/GPRS/MakerStudio%20GPRS%20GSM%20Shield%20User%20Guide%20r1%20.pdf

 

Arduino使用范例代码: http://i-element.org/makerstudio/GPRS/GPRS_Shield.zip

 

芯片相关参考手册: http://i-element.org/makerstudio/GPRS/SIM900datasheeet.zip

(中文) 创客音乐频谱彩灯

Making Refinements to the Old Project

I put together the Color Organ Triple Deluxe over a year ago. It was a bare minimum version of color organ circuit using LEDs instead of incandescent lamps that traditional color organs use.

The circuit worked pretty well, considering the simplicity of the circuit. However I just kept feeling like this project deserves further refinements. So I went back to the drawing board (or breadboard) and took a hard look at the circuit...

The result? Please take a look at the video.

Step 1: The Problems & the Solutions

Picture of The Problems & the Solutions

The Problems

There were a few problems. The transistors in the circuit was biased in the way that it was supply voltage dependent, as well as device dependent - in other words, if the voltage was too high or too low, or the transistors had a bit of different characteristics, the circuit did not perform well.
The filter performance was also a bit poor - the separation between the frequency bands were not so great.

The Solutions

First, I changed the initial gain stage from single transistor design to two transistor design. It's a basic class-A common emitter amplifier followed by an emitter follower. They are direct coupled for optimum performance, as well as reduced part count (always important for me to design circuits with the least number of parts). Adding the emitter follower stage allowed the low output impedance needed for the filters to perform well. The biasing circuit was also revised to be less device and voltage dependent.

Second, the filters were refined to have better separations. Input and output impedance to the filters are better matched to achieve better efficiency as well.

Third, the LED driver circuits were given another transistor. Actually, in the original design, the output buffer and the LED driver was done by the same transistors. Now the filter outputs are buffered by emitter followers, then the filtered audio waves are rectified before going into the LED drivers.

Those changes made a huge difference. And I tweaked the component values obsessively to get the best performance. Sensitivity adjustment control is also added.

There are many additional parts compared to the earlier version, but the result is totally worth it. The LEDs now respond to music very, very nicely.

Step 2: Circuit

Picture of Circuit
Picture of Circuit
Picture of Circuit

Here are the circuit schematics, BOM, as well as the PCB layout. The filter response graph is also shown. Keep in mind that the graph is more of a perceptual one than actual.

The circuit is loosely based on the many vintage circuits before it, with a few improvements.

The input buffer/gain stage is designed to have low output impedance. This is important for the filter stages that follow. This stage is also designed to give high gain and maximum output signal level, since the filters are of passive type so will lose some signal.
(This amplifier stage took me the most time to design. I tried out many topologies and parameters. I think I found the best balance between simplicity, stability and performance. Unlike using op-amp, designing amplifier with transistors is an art of compromise.)

The use of emitter follower as rectifier is my original idea. (Q3, 5 and 7) Combined with the bias point set (by R8 and 9 and so on) right below the point the LED driver turns on makes this color organ very sensitive to the lower volume of audio input, while eliminating the diodes typically used here.

BOM

  • 3x 47 ohm - R4,17,20
  • 6x 150 ohm - R10,15,16,16b,21,21b
  • 2x 270 ohm - R11,11b
  • 1x 470 ohm - R6
  • 2x 1k ohm - R1,2
  • 2x 4.7k ohm - R7,12
  • 4x 10k ohm - R3,9,14,19
  • 3x 270k ohm - R8,13,18
  • 1x 1.2M ohm - R5
  • 1x 10k ohm potentiometer - VR1
  • 1x 4.7nF (0.0047uF) - C9
  • 2x 22nF (0.022uF) - C6,7
  • 1x 0.22uF EC - C3
  • 1x 1uF EC - C4
  • 3x 4.7uF EC - C5,8,10
  • 1x 10 uF EC 16V or higher - C2
  • 1x 47uF EC 16V or higher - C1
  • 8x MPS2222A or Equivalent - Q1-8
  • 6x Red LED (super bright type recommended) - D1-6
  • 6x Green LED (super bright type recommended) - D7-12
  • 6x Blue LED (super bright type recommended) - D13-18
  • 1x 3.5mm Stereo Jack - CN1
  • 1x DC Power Jack

All resistors are 1/8W (or higher) carbon film type, 5% precision. Small capacitors are film type, and 0.22uF and above are electrolytic type having voltage rating of 16V or higher.

Parts Substitutions

This type of analog circuits tend to be picky about the part values, so it's best not to change out resistor values, etc. unless you know what you are doing.

Resister and capacitor types are not very critical, so just use any type you might have. Using ceramic capacitors instead of film for example, is fine.

I used MPS2222A transistor, which can be substituted by number of general purpose transistors of similar specs. The ones I tested are 2N4400, 2N4401, and 2N3904.

Q1 is more critical than other transistors in this circuit. The biasing is adjusted for transistors having the hfe around 200. If you use different transistor, you might want to check the voltage at Q1 collector - the voltage here should be between 4.5 to 6V when 12V supply is applied. Adjust R5 or try different transistors for Q1 if it's too high or low.

PCB Layout
PCB layout is provided as PDF for home brew PCB makers. It's a single layer design, so it should be easy to make your own.

Kits and PCBs
Kits and PCBs of this project are available at my website.

Step 3: Assembly

Picture of Assembly
Picture of Assembly

There are 8 transistors, and many resistors, capacitors and LEDs, but the assembly is very straightforward as they are all familier through hole parts (and no ICs). In a way, Color Organ Triple Deluxe II is built like the circuits from the 70's. If you are like me, you will appreciate the modern-vintage feel of all discrete component design.

I recommend soldering the lower profile parts, first, then move on to taller and taller parts. I arranged the BOM in the order of soldering below:

Soldering Order

  • Resistors (bend the leads) (reference on color code)
    • 3x 47 ohm (yellow, violet, black, gold) - R4,17,20
    • 6x 150 ohm (brown, green, brown, gold) - R10,15,16,16b,21,21b
    • 2x 270 ohm (red, violet, brown, gold) - R11,11b
    • 1x 470 ohm (yellow, violet, brown, gold) - R6
    • 2x 1k ohm (brown, black, red, gold) - R1,2
    • 2x 4.7k ohm (yellow, violet, red, gold) - R7,12
    • 4x 10k ohm (brown, black, orange, gold) - R3,9,14,19
    • 3x 270k ohm (red, violet, yellow, gold) - R8,13,18
    • 1x 1.2M ohm (brown, red, green, gold) - R5
  • 1x 3.5mm Stereo Jack - CN1
  • Capacitors (watch the polarity of electrolytic capacitors - long leads go into the holes with "+" sign on the PCB)
    • 1x 4.7nF (0.0047uF) Film Capacitor - C9
    • 2x 22nF (0.022uF) Film Capacitor - C6,7
    • 1x 0.22uF Electrolytic Capacitor* - C3
    • 1x 1uF Electrolytic Capacitor* - C4
    • 3x 4.7uF Electrolytic Capacitor* - C5,8,10
    • 1x 10 uF Electrolytic Capacitor* - C2
    • 1x 47uF Electrolytic Capacitor* - C1
  • Transistors (polarity - make sure to orient them to the shape printed on the PCB)
    • 8x MPS2222A or Equivalent - Q1-8
  • LEDs (polarity - make sure to orient them to the shape printed on the PCB)
    • 6x Red LED - D1-6
    • 6x Green LED - D7-12
    • 6x Blue LED - D13-18
  • 1x DC Power Jack
  • 1x 10k (50k) ohm potentiometer - VR1

Notes on Solder Resin/Flux
Some solder resin/flux is electrically conductive. (resin or flux is inside solder wire to help solder to adhere to the joints) Some parts of Color Organ Triple Deluxe II are very sensitive to even a tiny amount of electrical leakage caused by soldering resin/flux. If the LEDs on Color Organ Triple Deluxe II stays lit without any sound signal coming in, you need to clean the PCB to remove the resin/flux.
"No Clean" type flux cause no problems (as the name implies), but more typical resin type flux can cause good amount of leakage, and cleaning might be required.
You can use an acid brush or an old toothbrush immersed in rubbing alcohol to scrub the back of the PCB. Rinse out the brush, wet with alcohol again and scrub another round or two until all the resin residue is gone. Make sure to dry the PCB completely before connecting to the power supply.

Step 4: Use

Picture of Use
Picture of Use
Picture of Use

Color Organ Triple Deluxe II is designed to run by 12V DC power supply. The circuit works pretty ok with 9V power, though. However 9V battery is not recommended as a power source because of the relatively high current draw (about 25mA at idle).

It's best to connect to a regulated 12V DC power supply. Be careful if you want to use a typical wall wart - they can output much higher voltage than they are rated - sometimes as high as 18V from a 12V one. Color Organ Triple Deluxe II can operate safely from up to about 15V power. (If you want to use non-regulated AC adaptor, try a 9V rated one - they typically produce around 13V).

Audio source can be any "line level" output from audio equipment, or headphone output from computer sound cards and iPod/MP3 players. If you want to listen to the music while using Color Organ Triple Deluxe II, you might need a splitter cable.

Connect Color Organ Triple Deluxe II to your audio source of choice, and give it a play. I found music with good amount of beats to give best results. Adjust the potentiometer (sensitivity level) according to the sound level.

The LEDs react to the sound volume in a pretty linear manner that it feels like the Color Organ is translating sound into light.

The light out of the LEDs are blinding bright. You can use Color Organ Triple Deluxe II as a wall wash - project the light towards walls or ceiling and dim the lights in the room.

You will discover a new joy of listing to music.

Arduino创客手表套件

Description:

The Solder : Time™ watch kit.

The Solder : Time is an original design watch kit that you solder and assemble yourself.  Delivered as a through-hole kit, you solder the components to the PCB, and enclose it all in four layers of laser cut acrylic.

Introduced at Maker Faire Bay Area in Mid 2011, an instant hit.  The supplied battery lasts a really long time, and the onboard Dallas RTC keeps impeccable time.  This is the first SpikenzieLabs Kit that is a 'wearable'.

Solder : Time is not only a wristwatch. Set it up as a desk clock, badge clip-it to your clothes, thread a chain, and you've got a pocket watch.

More advanced tinkerers will see the bottom side I2C lines broken out, for hacking, and integrating RTC into other projects. There are also pads on the backside of the PCB for DC supply, as well as an 'always-on' function.

Resistors:

Start by bending the leads to all three resistors to look like these in the photo.

Solder them in place and trim the leads. They go in either direction.

Clock crystal:

The crystal for the real time clock is the very small silver part with two leads.

Solder this as in the photo.

IC and Capacitors:

Note:

  1. 1.The notches on the two IC chips (RTC and PIC) must match-up with the notches printed on the white silk screen.

  2. 2.These two ICs are soldered directly onto the PCB. For best results, only apply heat from your soldering iron for 1 to 3 seconds per leg.

Solder the two orange-yellow capacitors in place.

Trim all leads.

LED:

Place the 4 digit 7 segment LED onto the PCB. Push flat, making sure all the legs go through the holes.

NOTE: Make sure that the LED is installed up-side right. Check that the decimal points are on the bottom as in this photo.

Solder and trim the leads.

You may want to peel the thin clear protective layer from the LED. Use your finger nail to lift an edge and then gently peel it off.

Button:

Push the button into the PCB. It should almost click into place.

Solder and trim the leads.

Assemble the watch body:

Battery holder:

The battery holder is very light and likes to move around as you solder it. Solder it in place with the open edge facing down.

Taping the battery holder in place, with masking tape, while soldering it works best.

Another way to solder the battery holder without tape is to heat the pad and battery holder by placing the tip of your soldering iron on the PCB’s battery pad and just barely touching the battery holder. After a second or two add some solder. Once one pad is soldered, do the other one, and come back to add more solder to the first one if required.

I’ve tried soldering a blob of solder onto one of the pads, and then heating the battery holder ... this didn’t work.

Building the circuit board: This is an easy to solder kit.

Peel the protective layer on the plastic parts:

In order to protect the plastic parts during manufacturing they come covered by a thin plastic / tape layer. These should be removed before you assemble the watch.

NOTE:

  1. 1.Only use something soft like your finger nail to scrape the edge of the protective layer and then peel it off.

  2. 2.VERY IMPORTANT: Some of the layers have very thin parts that can crack easily. The best way we have found to peel the protective layer off of these parts is to hold the part down evenly on a flat surface with one hand and peel with the other hand. Holding the part in the air while you peel may snap the part you are peeling. (Don’t worry after the watch is assembled and screwed together it is very strong.)

Stacking the watch:

With the battery in the battery holder start making a stack of parts.

Close up of button details:

Battery:

Slide the battery into the battery holder on the Solder : Time PCB with the CR2032 “+” label text facing up. When the battery goes into the holder the watch should turn on and display 12:00. If not, remove the battery and check your work. After about five seconds the display will go out, this is normal.

NOTE: As tempting as it may be, don’t touch the battery holder while soldering - you will burn your finger!

  1. 5.Place the front face of the Solder : Time on the top of the stack.

  2. 6.Using your fingers, screw the layers together with the included screws. Don’t tighten them fully until all four screws are installed (this will help you align the layers).

  3. 7.Almost done, slide the wrist band in from the bottom edge, under the bottom and up through the other hole in the bottom and out the top edge.

  1. 1.Start with the plastic watch back oriented with the two larger holes at the top and bottom and place the PCB over it.

  2. 2.Next, place the plastic PCB layer part around the PCB, with the open end facing down.

  3. 3.Place the plastic switch layer on top of the PCB layer plastic. The opening for the switch is on the right side.

  4. 4.Place the switch lever into the space on the right side of the Switch Layer. Make sure that the switch touches the Solder : Time button and does not bind. Test it, the Solder : Time should turn on when pressed and off after a few seconds when released.

How does it work ?:

Parts Selection:

When we came up with the idea for the Solder : Time, one of our big concerns was battery life. We knew that we would need a RTC and some type of micro-controller. After experimenting with a bunch of different RTCs we decided to go with the Dallas Semiconductors DS1337+. This RTC clock runs at over a range of voltages which included our required voltage of 3v. It has extremely low current when in standby mode and uses I2C to communicate with the master micro-controller.

For the micro-controller we chose the PIC16F631. This IC has only a few peripheral functions built in (with keeps the cost down), and since we didn’t need many this also saves some power. The PIC16F631 has a very low power sleep mode, has enough pins for our project (and only one spare one), and also runs at 3volts. The PIC16F631 does not have built in I2C, so we used a bit banged version to control the RTC.

Battery Life:

In order to maximize battery life, we also used a couple of tricks. For the I2C bus we used higher value pull-up resistors (10k vs 4.7k) to reduce current and for the one unused pin on the PIC we set it to be a low logic value output (Microchip’s spec sheets, recommend this as a power saving set up). In testing the watch’s current draw, we estimated that given the average power of a CR2032 battery, the watch should keep the time for five years, before needing a battery swap in stand-by mode. Overall battery life will depend on how often the display is turned on.

Seven Segment Display:

The LEDs: One of the objectives when designing the Solder : Time was to make sure that all of the segments of the digits had equal brightness. In some cases only two segments are lit, as is the case for the number “1”, When the “8” is on, all seven segments are lit. Battery power was also a concern, the battery we chose for this project is the CR2032 which is a 3v low current battery. Our solution was to light only one single segment at a time, this way if the digit being displayed was a “1” or an “8” all the segments would be equally bright and we wouldn’t over tax the battery by drawing too much current. (If you wave the watch in the dark, you may be able to see the flashing pattern.)

Use a timer:

To light only one segment at a time we used one of the internal timer peripherals in the PIC. A timer may also be used as a counter, but in this case we used it as a timer to time the on time of each segment. When the timer runs out, the PIC programming jumps into a interrupt routine. To display a number, the PIC looks up the segments in a table that stores the on and off values for the segments. It starts with the first segment of whichever number it is displaying and then turns the segment on (or not, if that segment isn’t on). After this, the program returns to the normal main loop of the program and waits for the timer to run out again. When it does, the PIC turns on the next segment of the current digit. Even if the segment of the current digit is not turned on, the timer still waits.

After all of the segments of a digit are displayed, the next digit is displayed, and after the last digit is displayed the colon is displayed and then it starts over at the first digit.

Flashing Colon:

There is a special case when displaying the colon. It flashes when in time setting mode. It took a few tries to get the flashing to look good and steady in the three states of the time setting mode; slow forward, fast forward and idle. To achieve a steady flash rate we used another timer. This timer simply toggles the colon on or off ever time that it times out, then when it is time to display the colon it is simply lit or not.

Sleep Mode:

For the Solder : Time’s sleep mode we use a manual counter variable. This variable is incremented every time the program goes through a loop, and when it over flows (gets too big for the size of the variables holder) a sleep flag is set and the watch goes to sleep. If the button is pressed before the watch goes into sleep mode, the sleep counter is reset to zero and counting starts again. This way, the watch will go to sleep consistently after about 5 seconds from the last time you pressed the button.

Before the watch goes to sleep it turns off the LEDs. The watch button is set to wake the watch up if it is pressed. Nothing is done to the RTC since it goes into stand-by mode when no data is being transfered and it simply keeps the time.

http://www.spikenzielabs.com/SpikenzieLabs/SolderTime.html

 

Beginner’s Guide to KiCad

Introduction

If you’re like me and you’ve decided to take the plunge from EAGLE PCB to KiCad it can be really jarring. EAGLE had many quirks and rough edges that I’m sure I cursed when I first learned it back in 2005. Since then EAGLE has become a second language to me and I’ve forgotten all the hard bits. So as you migrate to KiCad remember to take breaks and breathe (and say ‘Key-CAD’ in your head). You’ll be dreaming in KiCad in no time!

KiCad Logo

This tutorial will walk you through a KiCad example project from schematic capture to PCB layout. We’ll also touch on library linking, editing, and creation. We’ll also export our PCB to gerbers so the board can be fabricated.

While this tutorial is aimed at beginners I am going to use terms such as ‘schematic components’ and ‘polygon pours’. If something doesn’t make sense that’s ok, just take a moment to do a quick search. If you really get stuck please use the comments section on the right. We always want to improve our tutorials to make them easier.

KiCad Project Window

Download and Install KiCad

Let’s get started! Head over to KiCad’s download page and download the latest version of the software for your specific platform:

DOWNLOAD KICAD FOR YOUR OPERATING SYSTEM/DISTRIBUTION

Run KiCad

Once installed, run KiCad. A main navigation window will display where you will be able to open all the periphery programs like schematic capture and PCB layout.

KiCad main Project Window

Click the image for a closer look

The KiCad project window looks quite empty and sad. Let's open an example!

Setting Up a Project

The ZOPT2201 UV sensor designed originally in SparkX is a great I2C UV Index sensor and will serve as our starting example for this tutorial. Download the ZOPT220x UV Sensor Breakout designs for KiCad and unzip the four files into a local directory:

ZOPT220X UV SENSOR BREAKOUT KICAD BOARD FILES

Once the four files are located in a local directory (try looking in your downloads folder for …\ZOPT220x_UV_Sensor_Breakout-Tutorial), click File -> Open Project and open the ZOPT220x UV Sensor Breakout.profile.

Main Project Window

Click the image for a closer look

What are all these files?

  • *.pro - Main project file to keep track of the file structure.
  • *.cmp - Defines which footprints go with which schematic components.
  • *.kicad_pcb - The PCB layout.
  • *.sch - The schematic.

These four files are all you need to share a KiCad design with a fellow collaborator. You may also need to share a footprint file, which will be explained more later on in this tutorial.

You may have had your first critical-judgment-eye-squint. Why is there a file to define which footprints go with which schematic components? This is fundamental to KiCad and is very different from how EAGLE works. It’s not a bad thing, just different.

Setting Up Schematic Component Libraries

Double click on the schematic file with Kicad’s Eeschema schematic editor. You’ll probably get an error:

Library Error

Ignore this for now. Click ‘Close’.

Component Question Marks

The schematic will load with lots of components with question marks (i.e.??). KiCad is missing the link to the devices within this schematic. Let’s get them linked!

Linking Component Libraries w/ Eeschema

From within EeSchema, click on Preferences -> Component Libraries. This will open a new window. In the image below you can see that the project file contains information about where it should look for “Component library files”. Each project has its own connections to different file structures. We need to tell this project where to find the symbols for this schematic.

Linking KiCad Library

We will need the SparkFun_SchematicComponents.lib file. Download and store it in a local directory:

DOWNLOAD "SPARKFUN_SCHEMATICCOMPONENTS.LIB"

From the KiCad window, click the top ‘Add’ button. We’ll show you how to create your own schematic symbols in a bit.

Add SparkFun Schematic Component Libray

Navigate to the directory where you stored the SparkFun_SchematicComponents.lib file and click ‘Open’. This file contains all the schematic components.

Once you've added the SparkFun schematic components library file, you should see it added to the list.

Component Library Files with SparkFun Schematic Component Library

The astute will note the slightly different directory structure in the window:

C:\Users\Nathan...

and

C:\Users\nathan.seidle...

That's the difference between my home PC and my work PC. To avoid future errors when opening this schematic, let's remove the entry from the active library files. Highlight the C:\Users\Nathan... entry from the list and click on the ‘Remove’ button.

Click on ‘OK’ to close out the Component Libraries manager. Now close and re-open the schematic to refresh.

Schematic without ??

Congrats! No more ?? boxes. For more information about using schematic component libraries across multiple computers, check the next subsection about the “user defined search path.” Otherwise, let's start editing the schematic!

User Defined Search Path: Using Component Libraries on Multiple Computers

The schematic component libraries are assigned using KiCad's Component Library Manager. If you're like me and have schematic libraries shared across multiple computers, adding a “User defined search path” is helpful:

User Defined Search Path

In the image , I have “..\..\SparkFun-KiCad-Libraries” defined. This is the local relative path to a Dropbox folder. These component library paths are specific to this project and *.pro file. When I open this project on my laptop, it will first look for the files in the “C:\Users\nathan.seidle...” location. It will fail and then search the relative path of “ ..\SparkFun-KiCad-Libraries” and find the files. It allows me to share libs between computers and between GitHub repos without having to reassign the libraries every time I open the project on a different computer.

For now, you should continue with the tutorial. In the future, you may want to revisit this if you use KiCad across multiple computers.

Editing a Schematic

If I get you to do nothing else, I will get you to learn the keyboard shortcuts! Yes, you can click on the equivalent buttons. However, the speed and efficiency of KiCad really shines when muscle memory kicks in so start memorizing. Here are the keyboard shortcuts in KiCad’s Eeschema that we will be using frequently in this tutorial:

  • a - To add component.
  • c - Copy a component when the cursor is over another component.
  • w - To wire components.
  • v - Edit component value.
  • Esc - Escape mode or whatever command in progress and return to normal pointer mode.
  • ctrl+z - Undo. Use liberally to undo any mistakes.
  • ctrl+s - To save. Make sure to save often!

This breakout board needs a larger 4.7uF decoupling cap (because I say so). Let’s add it!

Adding Component to Schematic

Press ‘a’ to add a device to the schematic. This will open the component window. (If you are using a different tool you may need to click on the schematic as well):

Choose Component

There are hundreds of components (668 items according to the title bar). Feel free to dig around but to quickly find what we need type ‘cap’ into the field Filter:. Select the device labeled as C_Small from the device library. Then hit enter or click ‘OK’.

select C_Small

Place it on the schematic next to the 0.1uF cap.

Place in Schematic

After you place the capacitor, you'll notice you're still in placement mode. Hit the ‘Esc’ button on your keyboard to return to normal pointer mode. I find myself hitting escape twice a lot just to be sure I'm back in default state.

Copying Component

Once in default state put your mouse pointer on top of the 3.3V marker on the 0.1uF cap. Press ‘c’ to copy that device and place it above the new capacitor.

Copy C_Small

Do the same for the ground marker. Press ‘ctrl+s’ to save your work.

Wiring Components

Now let's wire them together. You guessed it, press ‘w’ but here's the catch: have your mouse pointer over one of the bubbles before you press ‘w’.

Wiring Schematic Components

Move your mouse to the other bubble and left click on the mouse to complete the wiring for GND. Remember if you mess up, press ‘Esc’ once or twice to return to default. Then move your mouse pointer to the bubble you want to connect and press ‘w’ and begin wiring 3.3V. The shortcut ‘w’ stands for wire.

Did something go wrong? Use ‘ctrl+z’ liberally to undo any mistakes.

Connected Capacitor

Power and ground are now connected to our capacitor.

Changing a Component Value

Let's change the value from C_Small to 4.7uF. Hover the mouse pointer over C_Small and press ‘v’ (for value change). Change C_Small in the Text field by typing 4.7uF. Then hit enter or click ‘OK’.

Change Capacitor Value

Congrats! You've just wired up your first schematic component. Press ctrl+s to save your work.

Annotate Schematic Components

But what about the C? designator?! Don't worry about it! One of the many benefits of KiCad is the ability to auto-annotate a schematic.

Click on Annotate Schematic Button

 

Click on the Annotate schematic components button.

Annotate Schematic Button

Use the default settings and simply click on Annotate button to confirm.

KiCad confirming annotation

KiCad confirming annotation

KiCad will ask you if you're sure, simply press return or click ‘OK’ again.

Updated Schematic Value and Designator

Capacitor with correct value and designator! We are all set. Time to edit the PCB.

Editing a PCB Layout

Before we start editing the PCB, here are the keyboard shortcuts in KiCad’s Pcbnew that we will be using frequently in this tutorial:

  • + - Press to switch next layer.
  • - - Press to switch to previous layer.
  • m - Move item.
  • b - Update ground polygon pours.
  • Delete - Remove a trace or component.
  • x - Route new track.
  • v - Add through via.
  • n - Next grid size. Use with caution. There will be tears if you use a grid outside of 50mils or 25 mils.
  • Page Up - Return to the top copper layer.
  • Esc - Escape mode or whatever command in progress and return to normal pointer mode.
  • ctrl+z - Undo. Use liberally to undo any mistakes.
  • ctrl+s - To save. Make sure to save often!

Generate Netlist

We’ve got our schematic, now let’s get the new 4.7uF cap placed on the board. From the schematic, click on the ‘Generate netlist’ button.

Generate Netlist Button

You'll see the following window:

Netlist Window

KiCad is powerful. And with this power, comes an overwhelming number of options. Lucky for us, we are just scrapping the surface so we don't need to fiddle with any of these options. Simply press enter or click ‘Generate’ to confirm this screen. KiCad will ask you where you want to save the netlist as a *.net file with the default location being the project folder. Again, press enter or click ‘Save’ to confirm.

Configuring Layer Colors

Return to the main project window and double click the *.kicad_pcb file.

KiCad_PCB File

Welcome to PCB editing. Of all the differences between EAGLE and KiCad it was the look within PCB layout that threw me off the most. Under the View menu you will find three other views: DefaultOpenGL, and Cairo. I prefer OpenGL. Lets switch Canvas to OpenGL for now.

Your mouse wheel does what you expect: Zoom In/Out and Pan by Clicking.

I don't like the layer colors! Ya, me either. To change the layer colors, on the right side menu use your mouse wheel to click on the green square next to B.Cu (bottom copper layer). I prefer the following layer colors:

  • Red 2 (Default) for F.Cu (Top Copper)
  • Blue 4 for B.Cu (Bottom Copper)
  • White for F.SilkS (Front Silk Screen)
  • Yellow 3 for B.SilkS (Bottom Silk Screen)
  • Gray 3 for Edge.Cuts (a.k.a board outline or dimensional layer in EAGLE)
  • Gray 2 (Default) for F.CrtYd (Denotes the total board space required on the top layer for the component)

Layer Colors

Pressing ‘+’ and ‘-’ will switch between top and bottom copper layers. This is useful when you need to view a certain layer.

PCB Layers Colored

It's all cosmetic but these layer colors make it easier for me to see what's going on.

Be sure to poke around the Render tab (next to the Layer tab), namely the Values and References check boxes.

Value and References

I find the Values and References extremely distracting when turned on so I leave them OFF. Many designers live and die by these values, so use as needed.

Adding a Footprint

Aren't we here to add a 4.7uF cap to the board? Where is it? It's nowhere, sorry.

What's going on? We failed to assign a footprint to the capacitor we added in the schematic. Remember, KiCad does not link schematic components to footprints the same way EAGLE does. We have to specifically connect a footprint to each schematic component that was added.

Navigate to back to schematic and click on the ‘Run CvPcb’ button to associate components and footprints:

Run CvPcb

If this is the first time you’ve run CvPcb you’ll get this warning:

CvPcb Warning

Simply click through it.

CVPcb Manager

Depending on how many libraries you have installed, this may take up to 30 seconds. We will make this better later in the tutorial but for now, be patient.

In the left column is all the footprint libraries that KiCad ships with. In the middle is the list of components in your schematic. On the right is any footprint that may work with the highlighted component in the middle. Your job is to double click on the footprint on the right that goes with the component in the middle.

To make life easier click on the ‘View selected footprint’ button.

View Selected Footprint

Now you can preview the footprint as you click down the list in the right.

Preview Footprint Window

In Windows, I press and hold the Windows button and press the left arrow and release. This will lock the CvPcb window on one side. Then select and lock the Footprint Preview Window to the right. This allows us to flip through footprints in the left window while seeing the preview on the right.

Highlight C2 in the middle column. Then double click the Capacitors_SMD:C_0603 in the right column. C2 should now be assigned a footprint.

Assign Schematic with Footprint

Re-Generate Netlist

Close the CvPcb window and click ‘Save and Exit’. We need to re-export the Netlist. Remember how to do that? Click the ‘Generate netlist’ button again, press enter twice. Open to the PCB editor either from the schematic or from the project window.

Reopen PCB Editor

Hey! It's still missing! We changed things, so we need to import the netlist! Remember how? Click on the ‘Read netlist’ button and you should see this window:

Read Netlist Window

Click ‘Read Current Netlist’ and ‘YES’ to confirm. You can also hit enter twice. You should see the new capacitor near the board.

Added Footprint Capacitor Near PCB

This is a decoupling cap so let's put it next to the 0.1uF cap that is already there. Start by hovering over the new cap and press ’m' for move.

Capacitor Footprint Moved

Left click to place the capacitor. Now press ’m' over the 0.1uF cap in the way by moving it to the left.

Capacitor 2 Footprint Moved

Press ‘b’ to update the GND polygon pours.

Updated Polygon Pours

We've got some traces to fix but this isn't too bad. Hover over the bits of traces that you want to remove and press ‘Delete’. Let's delete the trace and via that is under the capacitor's +3v3 terminal. If your pointer is over multiple items (as shown in the image below with the cursor over both the trace and capacitor), KiCad will pop up a menu to clarify your selection. This is basically asking you to pick which one you want to operate on.

Clarify Selection

If you ever run into a problem press ‘Esc’ to return to default pointer mode. If you ever delete something wrong press ‘ctrl+z’.

Deleted Trace Via

Once you've removed most of the offending traces, you can begin routing by pressing ‘x’.

Single click on the pad that has the gray air-wire and drag it to the pad that it needs to connect to. Single click again to lock the wire in place. Press ‘b’ to update the polygons.

Connect 3V3

In the image below, KiCad is trying to route this trace in an odd way. If we place the trace here it will create an acute angle which is generally bad (read up on “acid traps”). We want the trace to be a T intersection. We need to change the grid.

Odd Trace Routing

Well that’s annoying!

Press ‘n’ to go to the next grid size. I needed to hit ‘n’ only once to go to the 0.25mil grid to get this nice intersection, you may need to get to a finer grid. You can also find this in the menu options under “Grid: 0.0635mm (2.5mils).”

T Intersection

Nice T intersection!

In the image below, I am routing the GND air wires. This is not really needed because the polygon pour connects the two pads but it does illustrate how good the ‘magnetic’ routing assistance is in KiCad. It's very quick and easy to go from pad to pad.

Route Ground Air Wires

We have two air-wires left. To get these we'll need to place vias down to the bottom layer. Start by pressing ‘x’ and clicking on the start of the capacitor's air wire for GND again.

Routing Ground Air Wire Again

Bring the trace out.

GND Trace

When you've reached open ground press ‘v’ to create a via. Single click to place the via and KiCad will automatically start routing on the bottom layer. Press ‘Esc’ to stop laying down traces; the polygon pour will take it from here. Pressing ‘Page Up’ will take you back to the top layer.

GND Via

One air wire left!

To get this last air wire, you can try clicking on the GND pad of the 0.1uF cap but annoyingly KiCad won't start routing?! Why?! It's actually a good thing: the SDA trace is too close (overlapping actually) to the GND pad on the 0.1uF cap. By not letting you start routing KiCad is saying that trying to put a trace here would violate the DRC rules. What to do? Rip up the SCL and SDA lines to make some room.

Delete SCL and SDA Trace

Aha! Much better. Press ‘x’, click on the capacitor's GND terminal, bring the trace out, and press ‘v’ to drop a via in this area. Hit escape to stop routing (let the polygon take care of it). Finally, press ‘Page Up’ to return to the top layer view.

Capacitor 2 Via

Use the ‘Delete’ and ‘x’ buttons to re-route the SDA and SCL lines to finish up this board. Then press ‘b’ to update the polygons. The board should look similar to the image below.

Routed PCB

Routed with no air wires!

Congrats! We have finished routing the footprints. Now let's run the DRC to see if we're legal.

How to Remove a Component's Footprint from a PCB Layout

Before we continue let's go over the process for modifying or removing a component from a PCB layout. For example, let's say that you wanted to remove an extra capacitor or resistor from a design. You would do all the regular steps:

  1. Delete device from the schematic.
  2. Export the netlist by clicking the generate netlist button.
  3. Import the netlist into PCB Layout by clicking on the read netlist button.

The difference is a few import settings:

Delete Footprint from Netlist

During the netlist import the default settings are to ‘Keep’ exchange footprint and to ‘Keep’ extra footprints.

Here, we need to change two things:

  • Exchange Footprint -> Change: This will allow footprints to change
  • Extra Footprints -> Delete: This will remove any extra footprints that remain

You may also want to ‘Delete’ unconnected tracks to clean up any left over tracks from the component you removed.

Running Design Rule Check

Click on the ladybug with the green check mark on it to open the Design Rule Check (DRC) window.

DRC

Let's take a moment to talk trace width, trace spacing, and vias. In general, SparkFun designs boards with:

  • 10mil trace width
  • 10mil trace spacing
  • 20mil vias

We go smaller than this on many designs but if you're designing your first PCB, do not design it with 4mil traces and 8mil vias. You shouldn’t need to go that small on your first board.

Why design in 10mil trace/space when a fab house allows 8mil or smaller for the same price?

Making PCBs is tricky and for each increment of tolerance you remove you increase the chances that the PCB (proto or not) will be fabricated with an error. And those errors can be hard to identify. We design with 10mil trace/space in order to insure and reduce the probability that we’ll see PCBs with errors on the production floor. There’s nothing worse than troubleshooting a faulty product and asking yourself: “I’ve tried every rework and soldering trick in the book, is it the PCB that’s bad?”

That stated, we are seeing many PCB fab houses charge low prices for 7mil trace/space and 12mil vias. If you’ve got a complex board with tight layout challenges, it’s better use the smaller trace/space and vias. Save yourself the layout time and rely on the PCB fab house to correctly fabricate your board.

We generally use the KiCad defaults of:

  • Clearance: By Netclass
  • Min Track Width: 0.2mm = 0.0079mil
  • Min Via Size: 0.4mm = 0.0157mil

Press enter again to run the DRC with the default settings.

ErrType(): Via near track

Aw shucks! What's wrong with my board? The vias marked with red arrows are too close to the traces near by. The error message will show up in the window as an error indicating: “Via near track.” Fix them by ripping up (press ‘Delete’) any traces near the vias and re-route them (press ‘x’).

DRC Errors

After adjusting the traces causing the issues, re-run the DRC. These three flags should disappear.

Fixed DRC Markers

DRC markers have been cleared

Congrats! You've fixed those “Via near track” issues.

ErrType(): Pad near pad

But wait, we are not done yet! There are still two DRC error arrows left with the error indicating: “Pad near pad”. KiCad is trying to tell us the pads on this solder jumper are too close together. SparkFun has used this footprint for years and is comfortable with the design so let's change the Netclass clearance constraint.

More DRC Errors

Open the DRC rules from the Design Rules menu.

Design Rules

Here is where you can create specific rules for specific traces and classes of traces. The problem that we are running into is the Default Clearance is 0.079mil (0.2mm). If we decrease this to 7mil (0.01778mm), click ‘OK’, and re-run the DRC…

Clearance Defaults

DRC errors resolved! Now reducing the DRC clearances in order to get your board to pass DRC is not an ideal solution. We want the pads on the solder jumper to be close enough to be easily jumpered with solder so increasing the distance between the pads on the footprint would be counterproductive. In general, you should set your DRC rules and stick to them.

Cleared DRC Markers

Watch Your Airwires!

One last note about DRC: Leaving airwires on your PCB is a sure fire way to generate coasters (bad, unusable PCBs).

List Unconnected

From the DRC window there is a ‘List Unconnected’ button. This will show you the location of any unconnected traces (I had to rip up the SDA trace on the bottom right side of the PCB to show this error). It's very important that you check for airwires before ordering your PCBs. As you progress through your layout, I recommend focusing on the ‘Unconnected’ count at the bottom of the screen (circled in pink). If you think you are done routing a board but still show a few unconnected wires that you can't find, the DRC window will help you locate them.

Press ‘ctrl+s’ to save your work.

Well done. You've made it through design rule checking! Now it's time to order boards.

Exporting Gerbers

We added a component to the schematic, we modified the PCB layout, and we checked for errors. Now we are confident and ready to have our boards made! Time to export the gerber files.

Generate Drill and Gerber Files

Gerber files are the ‘artwork’ or the layers that the PCB fabrication house will use to construct the board. We’ve got a great tutorial on the different layers of a PCB so be sure to read up if all this is new to you.

Click on the ‘Plot’ button next to the printer icon in the top bar to open the ‘Plot’ window.

Plotter Button and Plot Window

In general, there are 8x layers you need to have a PCB fabricated:

  • Top Copper (F.Cu)+ Soldermask (F.Mask) + Silkscreen (F.SilkS)
  • Bottom Copper (B.Cu) + Soldermask (B.Mask) + Silkscreen (B.SilkS)
  • Board outline (Edge.Cuts)
  • Drill file

In the Plot window with the Plot format set for Gerber, be sure these Layers are checked:

  • ☑ F.Cu
  • ☑ B.Cu
  • ☑ B.SilkS
  • ☑ F.SilkS
  • ☑ B.Mask
  • ☑ F.Mask
  • ☑ Edge.Cuts

Additionally, click on ‘Generate Drill File’ button. You can use the defaults here as well. More on the PTH vs. NPTH check box in a minute. For now just click ‘Drill File’ or press enter to generate the drill file.

Drill File Generation

Click on ‘Close’ in the ‘Drill Files Generation’ window.

Click ‘Plot’ to generate the gerber files for the layers and then click ‘Close’.

Time to Review Your Gerbers

This is the last chance to catch any errors before paying real money. Reviewing the gerber layers often shows you potential errors or problems before you send them off to fab.

GerbView

Return to the main KiCad project window and open up GerbView by clicking on the button.

Once KiCad’s GerbView is open, click on File -> Load Gerber File. Select all the files shown and click Open.

Load Gerber File

Next, click File -> Load EXCELLON Drill File. Load your drill files by selecting the all the drill files shown and click ‘Open’. They should be in the same directory.

Drill Files

The layout looks very different but this is a good thing. You've been staring at your design for hours and it's hard for your brain to see issues. I generally do not change the layer colors unless I have to. I want the gerber review to be jarring and different from my layout practices so that I'm more likely to catch issues.

From this view, turn off all the layers but the Top Copper (layer 5). Additionally from the Render menu, turn off the Gridand DCodes. This will make the review less cluttered.

Top Copper Layer

Now step through the different layers by toggling them on and off. You're looking for irregularities and things that look out of place. Here are some things I look for:

  • Do any traces have weird routing that could be improved?
  • Do the vias line up with the top copper where they should?
  • Does the top solder mask make sense with the SMD IC’s footprint?
  • Are the via’s covered in soldermask (also called ‘tented vias’) or are they exposed?
  • Does the top silkscreen look good? Make sense? Everything aligned the way I want it? Are pin 1 indicators clear?

Turn On and Off Layers

Now turn everything off and repeat for the bottom layers.

Did you catch it? There are a handful of things wrong with this example.

  1. The bottom silkscreen is missing the GND indicator.
  2. The top GND silkscreen indicator is in italics.
  3. There are two drill files for some reason.

Leaving a silkscreen indicator off won't break your board but it's small defects like this that the gerber review is meant to catch.

Missing GND on Bottom

Whoops! Bottom silkscreen for GND is missing!

Homework:

Take a moment and return to the PCB layout window to edit the make these corrections.

  • Add the a silkscreen to the bottom layer for GND. To do this, select the bottom silk layer (B.SilkS) in Pcbnew. Click on Place -> Text, type “GND” in the Text: field, and click ‘OK’. You can also copy text on the bottom silkscreen layer by right clicking it, selecting Duplicate, and placing text next to the GND pad. Make sure to change text to GND by right clicking the text, selecting Properties, changing the text, and clicking ‘OK’.
  • Change the top GND indicator so it’s not italics. To do this, edit the text properties and change the Style: to Normal.
  • Plot new gerber files.
  • Review your work in GerbView to verify the fixes.

Now, we need to deal with the two drill files.

PTH vs NPTH

When generating the drill file for this design two files where generated:

  • *.drl - The standard EXCELLON drill file you need to send to PCB fab house.
  • *-NPTH.drl - The non-plated through hole drill file.

Non-plated through holes are holes on your PCB that do not have copper covering the vertical walls of the hole. This is sometimes required for advanced designs where thorough electrical isolation is needed. However, it is rare. While plated through holes (PTH) are common and cheap, NPTH requires an extra step in the PCB fabrication process and will often cost extra.

We don’t need NPTH for this design, so what happened? The ‘STAND-OFF’ footprint (i.e. used for the drill holes top of the board for mounting holes) was imported from the SparkFun Eagle library and KiCad seems to think it is a non-plated hole for some reason.

To correct this go back to the PCB layout, click on the Plotter, click ‘Generate Drill File’ and select the box that says ‘Merge PTH and NPTH holes into one file’. In a later section, we’ll go over how to edit the ‘STAND-OFF’ footprint to use a regular PTH hole.

Solder Paste Stencils

Are you doing SMD reflow? Need to order a stencil to apply the solder paste to your board? Turn on F.Paste in the Plot window to generate the top paste layer.

This *.gtp file is sent to a stencil fabricator to create the stainless steel or mylar solder paste stencil. If you’re unfamiliar with stenciling solder paste we have a fabulous tutorial.

We use OSHStencils for our proto stencils. The top paste layer is not needed to fabricate a PCB.

Order Your Board!

If you’re happy with your layout, let’s order some PCBs! Every fab house understand and works with gerber files, so navigate to the directory on your computer where your KiCad project resides.

Gerber Files to ZIP

Select and zip the following 8x files:

  • *.drl - Drill file
  • *.gbl - Gerber Bottom Layer
  • *.gbs - Gerber Bottom Soldermask
  • *.gbo - Gerber Bottom Silkscreen (Overlay)
  • *.Edge.Cuts.gm1 - Board Outline (Gerber Mechanical 1)
  • *.gtl - Gerber Top Layer
  • *.gts - Gerber Top Soldermask
  • *.gto - Gerber Top Silkscreen (Overlay)

You could zip all the files in the directory and send them off to your fab house but I don't recommend it. There are a tremendous number of PCB layout software packages generating all sorts of different file names and formats. It's often difficult to tell if *.cmp is a gerber file or something else. Does the customer care about the *.gtp file or is that just extra? It's better to give the fab house only what you want fabricated.

The final step? Order your boards! The gerbers are the universal way to communicate with a PCB vendor. There are hundreds if not thousands of PCB vendors out there. Shop around!

In addition to your gerbers, you'll need to specify via email or the PCB vendor's website various elements of the PCB:

  • What thickness PCB? 1.6mm is standard but 0.8mm is just as rigid and may help with 50 ohm trace impedance matching.
  • What color soldermask? Green is default but red looks awesome.
  • What color silkscreen? White is most common but other colors are available.
  • How many layers? This example is a 2x layer board meaning there is just a top copper and bottom copper. However, some designs need to have 4x, 10x, and even 16x layers to route the board. Additional layers increase the cost significantly.

The Soldermask Looks Big

If you had a look at the soldermask on this PCB and wondered why it looked odd, you're not alone. Let's compare the PCB's soldermask for KiCad (as shown in green) and Eagle (as shown in pink). You should notice two things:

  1. In the KiCad design, I have a pad on the main sensor that looks like it's slightly mis-placed. Pad 1 doesn't line up with the other pads. Weird. It's a problem that needs to be fixed, but the error won't kill the board.
  2. More importantly, the soldermask on the Eagle design has gaps between the pins on the connector and the sensor IC. This will help reduce solder bridging between pins. In the KiCad version, the mask apertures look too big.

KiCad Soldermask

KiCad Soldermask

Eagle Soldermask

Eagle Soldermask

In the image below, we can see the SMD Qwiic connector within Eagle. The default soldermask clearance is 0.1mm per side in Eagle.

Soldermask Clearance for Qwiic Connector

In KiCad's Pcbnew, open the ZOPT220x Breakout and click on Dimensions -> Pads Mask Clearance. KiCad's solder mask clearance has a default of 0.2mm per side. We recommend you change this value to 0.1mm. Most fab houses will use 0.1mm as their default as well. You will then need to re-export your gerbers and load them back into GerbView.

KiCad Pad Mask Clearance

Making the clearance smaller than 0.1mm will cause difficulties for the fab house to get the registration correct.

Creating a Custom KiCad Footprint Library

This section will show you how to create your own local custom footprints so that you can use them and connect them to schematic components using CvPcb. We’re going to assume you’ve already been through the previous sections of this tutorial; you should have KiCad downloaded and installed.

Open KiCad’s project manager and then click on the PCB footprint editor button.

PCB Footprint Editor

You may get the warning. That's ok, just click through it. This is KiCad's way of telling you it's going to create the default table of libraries that link to KiCad's extensive GitHub repos.

Warning

Click Preferences -> Footprint Libraries Manager. This will open the list of all the footprint libraries now accessible to you.

Footprint Libraries Manager

This is a tremendous list of libraries! Click ‘OK’ to close the manager.

PCB Footprint Libraries Tables

Let's poke around these libraries. Click on ‘Load footprint from library’ button and then ‘Select by Browser’. This is a handy tool for perusing the available footprints.

Load Footprint from Library

Navigate to the LEDs -> LED_CREE-XHP50_12V footprint. Here is an example footprint in LEDs library. Double click on this footprint to open it up in the editor.

Library Browser

Note the title bar of the editor window has changed. The active library is now LEDs and it is read only. Obviously KiCad wants to control their libraries; not just anyone can save to their repos. If we want to edit this footprint we need our own local copy.

Open Example Footprint

Let's create a local directory to keep all our local footprints. For this tutorial, please create a local folder called ‘C:\KiCadLibs\’ (or your platform's equivalent).

Now click on File->Save Footprint in New Library.

Save Footprint in New Library

I recommend using different directory names for different sets of footprints (resistors, connectors, LEDs, etc). Select the ‘KiCadLibs’ folder that was created and then type ‘\LEDs’. KiCad will create the new ‘LEDs.pretty’ directory with a file ‘C:\KiCadLibs\LEDs.pretty\LED_CREE-XHP50_12V.kicad_mod’. And we're off to the races. Except, not quite yet.

Save Footprint to Different Directory

Notice the title bar in the Footprint Editor still states the active library is LEDs and is read only. We need to switch the active directory to our local folder. I'm going to head you off: File->Set Active Directory doesn't work as it only gives you the list of libraries that KiCad ships with. Oh KiCad!

Before we can set our new footprint directory as active, we need to make KiCad aware of it. Re-open the Preferences -> Footprint Libraries Manager.

Add Footprint Libraries Wizard

Click on the ‘Append with Wizard’ button. You’ll be asked to locate the directory you want to add. In this case, we want to add the ‘Files on my computer’. Click on the ‘Next >’ button, select the directory we created (i.e. ‘C:\KiCadLibs\LEDs.pretty’. Click on ‘Next >’ a few times. When prompted ‘Where do you wish the new libraries to be added’, select ‘To Global library configuration (visible to all projects)’ and click ‘Finish’.

KiCad may throw an error because the ‘LEDs’ nickname is used twice. I renamed mine to ‘LEDs-Custom’ then click on ‘OK’ to close out the Footprint Libraries Manager.

Add Footprint Libraries Wizard Error

If you inspect the Footprint Editor tool bar again, you'll see the LEDs library is still active and read only. Now we can click on ‘File->Set Active Library’. Here is where KiCad shines - the Filter works well. Type LED and select the LEDs-Custom library.

Active Local Library

At last! We have an active local library. Now when you click ‘Save footprint in local library’ or press ‘ctrl+s’ KiCad will prompt you with a Save Footprint window with Name (annoyingly every time). Press enter and your modifications will be saved.

Now you can explore creating and editing footprints using the Footprint Editor.

After you’ve created your first footprint or two be sure to read KiCad’s KiCad Library Conventions (KLC). It’s a well documented system for creating community share-able footprints. Left to our own devices we will all create things a little differently; the KLC tries to get us all on the same page and SparkFun follows it.

In the future, if you’re creating a lot of footprints consider using git repo to manage the changes. At SparkFun, we use the following structure:

  • \SparkFun-KiCad-Libraries - A git repo directory containing all KiCad schematic component files (*.lib)
  • \SparkFun-KiCad-Libraries\Footprints - Contains directories of footprints
  • \SparkFun-KiCad-Libraries\Footprints\LEDs.pretty - Directory containing all the LED footprints (*.kicad_mod)
  • \SparkFun-KiCad-Libraries\Footprints\Sensors.pretty - Directory containing all the sensor footprints (*.kicad_mod)
  • etc.

By using a git repo, SparkFun engineers and our users can contribute schematic components and footprints.

Paring Down the KiCad Libraries

When opening CvPcb to assign footprints to the schematic components, it can take a very long time to load. This is because KiCad is pinging all the KiCad github repos and pulling down 93 libraries. To make this faster, we recommend removing the libraries that are either deprecated or libraries that you will never use.

Remove Libraries Deprecated or Never Used

It's quick and easy to remove a library: select a row in the Footprint Libraries Manager and click the ‘Remove Library’ button. If something goes wrong, don't panic! Simply click ‘Cancel’ in the manager window and the library manager will close without saving changes. If things go really wrong, you can always delete the ‘fp-lib-table’ file and restart KiCad. This will cause it to create the footprint table with the KiCad defaults.

The footprint libraries table file (on Windows 10) is located in your AppData. It should look similar to: ‘C:\Users\Nathan\AppData\Roaming\kicad\fp-lib-table’ .

Contents of fp-lib-table

The contents of ‘fp-lib-table’

Removing the deprecated libraries brings the default count down to 75 and CvPcb still takes an annoyingly long time to load. This is where you'll have to make some tough decisions. Do you plan to ever need the ‘Shielding-Cabinets’ library? Perhaps. Perhaps not. If I ever do need an RF shield for a design, it will most likely be a custom part or a part that is notin the library. So that one gets the toss.

SparkFun is taking a blended approach. We're becoming very familiar with the default KiCad libraries and using their footprints wherever it makes sense. When we find or use a package we like, we copy it over to the SparkFun-KiCad-Libraries GitHub repo. At the same time, we're continuing to leverage all our custom Eagle footprints that we've been using and creating for over a decade. We know and trust these footprints. I have had many PCBs ruined because I trusted someone else's footprint so I tend to be very paranoid. Use the community where you can but be very rigorous about checking them for correctness.

If you're needing a generic 2x5 pin male header, check the KiCad libraries. It should work fine. However, if you're using a more eclectic part, you may be better off creating the footprint from scratch. Even if the KiCad libraries contain the part, you'll want to check it against the datasheet very closely and do a one to one test print.

Using Eagle Footprints in KiCad

If you're familiar with Eagle, it can be scary to think all the time spent creating footprints will be lost when switching to KiCad. Don't fear! KiCad inherently reads Eagle footprints! Yep, it's built right in. Now don't get too excited. KiCad can't read your Eagle schematic components but we have a solution for that in a later section.

Eagle Footprint

The approach we are taking at SparkFun is to link to a local copy of all our classic Eagle Librarie Anytime we need one of the Eagle footprints, we copy and paste it into a modern KiCad library. We don't have to re-create the footprint but by moving it over to a KiCad library. We are able to then edit the footprint as needed. Furthermore, any new footprints are created from scratch and saved to the appropriate SparkFun KiCad library.

You should have already opened the PCB Footprint Editor at least once by now. This will have created a ‘fp-lib-table’ file that we will be editing shortly. Now to get started, be sure that KiCad is closed.

Download the SparkFun Eagle Libraries from GitHub.

SPARKFUN EAGLE LIBRARY GITHUB REPOSITORY

Unzip them into a local directory of your choice. I store our Eagle libraries in a DropBox folder so both my desktop and laptop can access the same set of files.

You could use the Footprint Libraries Manager located in the footprint editor but adding or removing many libraries becomes tedious; it's easier to edit the table file directly.

fp-lib-table

The contents of fp-lib-table

The ‘fp-lib-table’ tells KiCad where to find all the various libraries and what types of libraries they are (KiCad, github, EAGLE, etc).

We are going to edit this file to add in the SparkFun libraries as well as remove the deprecated libraries and libraries that SparkFun doesn't use.

Here are the files of importance:

  • original fp-lib-table - This is what KiCad creates by default. You don't really need to download it. It's just for reference.
  • sparkfun fp-lib-table - The list of SparkFun libraries. You don't need to download it, just for reference.
  • combined fp-lib-table - This is the combination of the original table, with extraneous libraries removed and SparkFun libraries added.

Download the ‘combined fp-lib-table’ to a local folder. Rename it to ‘fp-lib-table’. Now move the file to where KiCad expects it. The footprint libraries table file (on Windows 10) is located in the AppData folder similar to: ‘C:\Users\Nathan\AppData\Roaming\kicad\fp-lib-table’. You'll want to overwrite the file that is there.

Once the file is in place, re-open KiCad, open the PCB footprint editor, and finally the Footprint Libraries Manager. You should see a long list of libraries including the new SparkFun libraries.

Included SparkFun Libraries

The last step is to tell KiCad the local path to the SparkFun libraries. Currently it's a variable called SFE_LOCAL. We need to assign this to something. Close the Library Manager window, click on Preferences -> Configuration Paths. Click the ‘Add’ button. Edit the Name and Path fields.

In the image below, you can see I've set the ‘SFE_LOCAL’ variable to a local path of ‘C:\Users\nathan.seidle\Dropbox\Projects\SparkFun-Eagle-Libraries\’. Set this variable to wherever you locally stored the SparkFun Eagle Libraries.

Local Path Configuration

Congratulations! You can now see, use, and copy all the SparkFun Eagle libraries.

Included SparkFun Eagle Libraries

Creating Custom KiCad Schematic Components

Once you’ve learned to create your own schematic parts and custom footprints, you become unlimited by what technologies you can play with. Let’s get started!

From the main project window start the Schematic library editor.

Schematic Library Editor

This process is similar to how we started a custom footprint library. First, let's find a schematic symbol we want to start our custom library with. The photocell is just as common as it gets. Let's pull in the ‘R_PHOTO’ schematic component from the device library and use it to start our new custom schematic component library.

Start by clicking on the ‘Selecting working library’ (i.e. book) icon located in the upper left corner. Then select ‘device’to set the working library.

Select Device

Click on the ‘Load component to edit from current library’ button and type r_photo in the filter to quickly locate the photoresistor component. When located, click ‘OK’.

Load Component

Click on ‘Save current component to new library’ button

Save Current Component to New Library

I recommend you store this *.lib file in the same ‘C:\KiCadLibs\’ directory we stored the footprint library within. I called my lib file ‘CustomComponents.lib’ so that I know these are mine.

Save Custom Component

Once you click ‘Save’, a warning will pop up. This is just KiCad's polite way of letting you know that you can't access your library until you link to it. So let's do that.

Warning

Click on Preferences -> Component Libraries to view the current set of libraries. In the image below, we can see the stock schematic component libraries that ship with KiCad. Next to the ‘Component library files,’ click ‘Add’.

Component Libraries

Navigate to your ‘C:\KiCadLibs’ directory and then open ‘CustomComponents.lib’. It should now appear at the bottom of the Component library files list. Click ‘OK’ to return to the library editor.

Again, click on the ‘Select working library’ button but this time either scroll to your custom list or type ‘Custom’ to find the ‘CustomComponents’ library. Click ‘OK’.

Select Working Library

Then click on ‘Load component to edit from the current library’ button and we should see only the photoresistor schematic component. Double click on R_PHOTO to begin editing it.

R_PHOTO

Now at this point, we can add new symbols from scratch to our library and we can also copy from one library to another.

How to Copy a Component to Your Custom KiCad Library

KiCad is always changing and they've made leaps and bounds improvements but copying a schematic component from one library to another is still a bit wild.

For example, let's copy the CP2104 from the silabs library into our custom library. Start by setting the active library to the one that contains the part you want to copy by clicking on the ‘Select working library’ button. In our example, we want to set silabs as the active library.

Selecting silabs library into custom library

Load the CP2104 component by clicking on the ‘Load component to edit from the current library’ button.

Now set the active library to the library we want to copy the CP2104 into. For this example, that means that we need to click on the ‘Select working library’ button and set the active library to ‘CustomComponents’.

Custom Components

Click on the ‘Update current component in current library’ button to save the component in CustomComponents.lib. The ‘Save current library to disk’ button will become enabled and you can save this component to your custom library.

Load Component to Edit

To verify it's now in the library click on the ‘Load component to edit from the current library’ button. You should see your new shiny CP2104 in the list.

How to Delete a Component from Your Custom KiCad Library

Bad CP2104! Bad component.

To remove a component, be sure you've set your custom library as the active one. Let's try removing the component that we just added in our custom library CustomComponents.lib. If you have not already, click on ‘Select working library’ to set the active library to CustomComponents. Click on the ‘Delete component in current library’ (i.e. the trash can) button. You'll be prompted for which component you want to remove. Select CP2104 from the list.

Delete a Component from Custom Library

Click ‘OK’ and then ‘Yes’ to delete the component from the library. Click the ‘Current library to disk’ button and ‘Yes’ to save.

Shout out to Joan_Sparky! He is the best! (No relation)

KiCad Library Convention

Be sure to check KiCad's KiCad Library Convention once you get comfortable creating components. These conventions take into account a heap of industry specialized knowledge that we can all benefit from.

Resources and Going Further

Congratulations! That was a big tutorial and you made it through.

For more information related to KiCad, check out the resources below:

Now that you’ve learned how to modify schematics, PCB layouts, and libraries, it’s time to try out your skills on your own custom project. We recommend using the ZOPT220x UV Sensor Breakout KiCad files as the starting point for your next project. From this example project, you can delete or add devices as you need rather than starting from a blank canvas.

Also, check out SparkFun's Enginursday blog post about KiCad.

Enginursday: KiCad and Open-Source Design

FEBRUARY 25, 2016

Eagle to KiCad

If you are an EAGLE guru starting to get your feet wet with KiCad, be sure to checkout Lachlan’s Eagle to KiCad converter for converting your Eagle PCB layouts to KiCad. It’s not perfect but Lachlan has done a tremendous amount of groundwork.

Thanks for reading and if you have any comments or questions please ask them in the comments section.

 


cc

 Creative Commonstutorials are CC BY-SA 4.0

Original From:

https://learn.sparkfun.com/tutorials/beginners-guide-to-kicad/introduction

Getting Started with MicroPython and the SparkFun Inventor’s Kit for micro:bit

Getting Started with MicroPython and the SparkFun Inventor's Kit for micro:bit

CONTRIBUTORS: LIGHTNINGHAWK

FAVORITE2

Introduction to MicroPython

MicroPython is an open source interpreter for the Python programming language developed specifically for microcontrollers. In this experiment guide, we will show you how to get started using MicroPython with the popular micro:bit board and our SparkFun Inventor’s Kit for micro:bit.

SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

Out of stock KIT-14542

$49.95
Note: This experiment guide assumes you have experience with programming. If you have never used a programming language before, we recommend checking out the MakeCode version of this guide. MakeCode is a drag-and-drop editor that is great for beginners of all ages learning to program.

When you’re done with this guide, you’ll have the know-how to start creating your own projects and experiments with MicroPython for micro:bit!

Using MicroPython

MicroPython is just an interpreter, so it does not include a space to write and edit code. Luckily, there is an editor we can use to write our Python code. Before you get started, you’ll need to download Mu. Mu is a simple code editor for beginners that runs on Windows, OSX, Linux and Raspberry Pi.

A major benefit of using MicroPython is the interactive REPL. REPL stands for read-evaluate-print loop, which is a very long way to say you can execute code live without compiling it first and then uploading it after. To get the REPL working on Windows, you’ll need to have the Serial Driver for mbed installed.

The applications for Python are extensive, and the advantage to using Python over other programming languages include interacting with other languages and platforms, third-party modules, extensive support libraries, user-friendly data structures and, of course, it’s open source.

Some known issues with using Mu and micro:bit currently are not being able to import third-party modules, not being able to use interrupts, and not having a decent way to map numbers of one range to another. Since importing third-party modules is not supported, we will be copying and pasting the source code in the current Mu MicroPython file. As with learning any new language, Python requires time, patience, self-study and a lot of examples! Keep at it, and we will be here to help you along the way.

Project Files

To download all of the files needed to follow along with all of the experiments, click the button below.

DOWNLOAD THE PROJECT FILES!

Software Options

To use MicroPython with the micro:bit, there are a few different options.

  • Use the Online Editor
  • Code with Mu. Mu is used in this guide.
  • Download the Driver
  • uFlash for those users already running and familiar with Python 2.7 or 3.3+.

Suggested Reading

If you have never worked with electronics before, we recommend you be somewhat familiar with the concepts in the following tutorials:

  • Voltage, Current, Resistance, and Ohm’s Law — The most basic concepts in electronics and electrical engineering. Get very familiar with these concepts, as they will be used throughout your electronics adventure.
  • What is a Circuit? — In this guide, we will be building a variety of circuits. Understanding what that means is vital to understanding the Inventor’s Kit.
  • How to Use a Breadboard — First time working with a breadboard? Please check out this tutorial! It will help you understand why the breadboard is great for prototyping and how to use one.

Experiment 0: Hello, micro:bit!

Hello World: A programmer’s first program

A “Hello World” on the micro:bit is a little different. On most microcontrollers this program would be executed using a serial terminal. Instead of using a serial terminal, you can interact with your micro:bit using the built-in LED array. So, the “Hello World” for the micro:bit is to draw something using the LED array!

Let’s first run the program from the REPL, and then we will build a .py script and upload it to the micro:bit. Open Mu, and make sure your micro:bit is connected to your computer with a USB cable.

To open the REPL, click the icon, and you should see a second window appear at the bottom. Type help() and see what happens.

help menu

Click any of the images for a closer look.

From the REPL, type display.scroll("Hello World") and watch your micro:bit’s 5x5 LED array. Now close the REPL by clicking the REPL icon.

For the first MicroPython script, we are going to cover how to add comments, how to import a module, and how to create a loop that will run forever. At the top of the program (above), you’ll see three lines of comments. Comments are created by using the # sign and one space. You can access modules by using from and import. These words tell the interpreter which classes to import from which modules. In this case, we are importing everything from microbit. while True: is how to create a forever loop in Python. The colon is how Python blocks code the way Arduino uses a set of curly brackets. Everything indented under a colon will execute as a block of code.

Type the program above in your Mu editor, or download all the programs from this GitHub Repository. Save it, then click the Flash icon to program your micro:bit.

Let’s display an image next instead of text.

alt text

When typing display.show(Image...), let the helpful info box show you what images come built in. Then try to code your own custom image.

alt text

Experiment 1: Blinking an LED

Introduction

This is experiment 1 - blinking an LED. We get to the fun stuff: adding hardware and constructing circuits.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1X micro:bit Breakout with Headers
  • 1x LED
  • 1x 100Ω Resistor
  • 1x Jumper Wires

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

$4.95

35

micro:bit Board

micro:bit Board

In stock DEV-14208

$14.95

3

SparkFun micro:bit Breakout (with Headers)

SparkFun micro:bit Breakout (with Headers)

In stock BOB-13989

$5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

Out of stock PRT-12795

$1.95

2

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

$0.95

2

LED - Basic Red 5mm

LED - Basic Red 5mm

In stock COM-09590

$0.35

Suggested Reading

Before continuing with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Introducing the micro:bit Edge Connector

edge connector

To extend the functionality of the micro:bit beyond what is already on the board, we developed a breadboard adaptor. This adaptor board makes it much easier to use all of the pins available on the micro:bit edge connector in a more user-friendly way. We also broke out ground and VCC (3.3 volts) for your convenience.

The adapter board lines up with the pins of a breadboard. We recommend using a full-sized breadboard with this breakout to give you enough room to prototype circuits on either end of the breadboard.

Introducing the LED

alt text

A Light-Emitting Diode (LED) will only let current through in one direction. Think of an LED as a one-way street. When current flows through the LED, it lights up! When you are looking at the LED, you will notice that its legs are different lengths. The long leg, the “anode,” is where current enters the LED. This pin should always be connected to the current source. The shorter leg, the “cathode,” is the current’s exit. The short leg should always be connected to a pathway to ground.

LEDs are finicky when it comes to how much current you apply to them. Too much current can lead to a burnt-out LED. To restrict the amount of current that passes through the LED, we use a resistor in line with the power source and the LED’s long leg; this is called a current-limiting resistor. With the micro:bit, you should use a 100 Ohm resistor. We have included a baggy of them in the kit just for this reason!

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram and hookup table below to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Please note: Pay close attention to the LED. The negative side of the LED is the short leg, marked with a flat edge.

LED drawing

Components like resistors need to have their legs bent into 90° angles in order to correctly fit the breadboard sockets. You can also cut the legs shorter to make them easier to work with on the breadboard.

Bent resistor

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Running Your Script

alt text

Code to Note

pin0.write_digital(1) and pin0.write_digital(0)

You’ll see that is is not much different from the previous experiment except for the lines 8 and 10. pin0.write_digital(1) sends a HIGH value, ON or a voltage of 3.3V to pin 0 on the micro:bit. pin0.write_digital(0) sends LOW value, OFF or 0V to pin 0 of the micro:bit.

What You Should See

You should see your LED blink on and off at 1-second intervals. If it doesn’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the Troubleshooting section. Change the number in the sleep() and play with the LED blink rate.

Troubleshooting

LED Not Blinking

Make sure you have it wired correctly and the correct pin to ground. Remember, short pin to ground; long pin to signal.

Still No Success

A broken circuit is no fun. Send us an email, and we will get back to you as soon as we can: techsupport@sparkfun.com

Experiment 2: Reading a Potentiometer

Introduction

In this circuit you will work with a potentiometer. You will learn how to use a potentiometer to control the brightness of an LED by reading a sensor and storing its 0–1023 value as a variable, then using it as a brightness level for the LED.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x LED
  • 1x 100Ω Resistor
  • 7x Jumper Wires
  • 1x 10kΩ Potentiometer

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

$4.95

35

micro:bit Board

micro:bit Board

In stock DEV-14208

$14.95

3

SparkFun micro:bit Breakout (with Headers)

SparkFun micro:bit Breakout (with Headers)

In stock BOB-13989

$5.49
Trimpot 10K with Knob

Trimpot 10K with Knob

In stock COM-09806

$0.95

6

Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

Out of stock PRT-12795

$1.95

2

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

$0.95

2

LED - Basic Red 5mm

LED - Basic Red 5mm

In stock COM-09590

$0.35

Suggested Reading

Before continuing with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Introducing the Potentiometer

alt text

A potentiometer is a resistance-based analog sensor that changes its internal resistance based on the rotation of its knob. The potentiometer has an internal voltage divider enabling you to read the change in voltage on the center pin with a microcontroller (the micro:bit). To hook up the potentiometer, attach the two outside pins to a supply voltage (5V in this circuit) and ground. It doesn’t matter which is connected where, as long as one is connected to power, and the other to ground. The center pin is then connected to an analog input pin so the micro:bit can measure the change in voltage. When you twist the knob, the sensor reading will change!

Note: The potentiometer included in the kit has three marks on it that will help you figure out which breadboard rows the pins are plugged into.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram and hookup table below to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Running Your Script

alt text

Code to Note

pin2.read_analog()

In this program you are reading the voltage from the potentiometer, which is 0 to 3.3 volts on pin 2. The micro:bit reads that value as a 10-bit number, which is a value range from 0 to 1023 using the call pin2.read_analog(). We are saving that number to a variable called potVal.

pin0.write_analog()

As with the analog read, the analog write deals with a range of values, but instead of reading a pin as an input, the line pin0.write_analog() outputs an analog value to a pin. We see this as a brightness range with this LED, but it could be a tone from a buzzer, a motor speed, etc. We set our analog output to the variable we stored the potentiometer value in.

A “variable” is a placeholder for values that may change in your code. You can create a variable by simply typing a name and setting it equal to what you want. Python is a dynamically typed language. This means the type of variable is determined at runtime. So you do not need to worry about declaring your variable type.

What You Should See

You should twist the potentiometer. You will notice that the LED will get brighter or dimmer based on the position of the potentiometer. If you turn the potentiometer all the way one direction, it will be fully on, and the other end will be fully off.

Troubleshooting

Sporadically Working

This is most likely due to a slightly dodgy connection with the potentiometer’s pins. This can usually be conquered by holding the potentiometer down or moving the potentiometer circuit somewhere else on your breadboard.

Not Working

Make sure you haven’t accidentally connected the wiper (center pin), the resistive element in the potentiometer, to a wrong pin!

LED Not Lighting Up

LEDs will only work in one direction. Double check your connections.

Experiment 3: Reading a Photoresistor

Introduction

In Experiment 2, you got to use a potentiometer, which varies resistance based on the twisting of a knob and, in turn, changes the voltage being read by the analog input pin. In this circuit you’ll be using a photoresistor, which changes resistance based on how much light the sensor receives. You will read the light value of the room and have an LED turn on if it is dark and turn off if it is bright. That’s right; you are going to build a night-light!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1X micro:bit Breakout with Headers
  • 1x LED
  • 1x 100Ω Resistor
  • 7x Jumper Wires
  • 1x Photoresistor
  • 1x 10kΩ Resistor

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

$4.95

35

micro:bit Board

micro:bit Board

In stock DEV-14208

$14.95

3

Mini Photocell

Mini Photocell

In stock SEN-09088

$1.50

7

SparkFun micro:bit Breakout (with Headers)

SparkFun micro:bit Breakout (with Headers)

In stock BOB-13989

$5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

Out of stock PRT-12795

$1.95

2

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

$0.95

2

LED - Basic Red 5mm

LED - Basic Red 5mm

In stock COM-09590

$0.35
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

In stock COM-11508

$0.95

Introducing the Photoresistor

alt text

The photoresistor changes its resistance based on the light to which it is exposed. To use this with the micro:bit, you will need to build a voltage divider with a 10k ohm resistor, as shown in the wiring diagram for this experiment. The micro:bit cannot read a change in resistance, only a change in voltage. A voltage divider allows you to translate a change in resistance to a corresponding voltage value.

The voltage divider enables the use of resistance-based sensors like the photoresistor in a voltage-based system. As you explore different sensors, you will find more resistance-based sensors that only have two pins like the photoresistor. To use them with your micro:bit, you will need to build a voltage divider like the one in this experiment. To learn more about resistors in general, check out our tutorial on resistors and also our tutorial on voltage dividers.

Note: Make sure you are using the 10k ohm resistor in your voltage divider with the sensors in this kit. Otherwise, you will get odd and inconsistent results.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Running Your Script

alt text

Code to Note

if and else

If the light value variable that is constantly being updated in the forever loop is less than the calibration value minus 50, it is dark and the LED should turn on. The (-50) portion of the if statement is a sensitivity value. The higher the value, the less sensitive the circuit will be; the lower the value, the more sensitive it will be to lighting conditions.

The if and else statements are a simple way to set the control flow of your forever loop. If the logical statement tied to the if statement is True, then it will execute the code indented under the colon. If that statement is False, it will skip to the next statement, which is else. In this case, if the statement is True (the room is dark), then the micro:bit will turn on the LED on pin 16; else (if the room is bright), it will turn the LED off using a write_digital()command covered earlier.

calibrationval is a calibration variable. Your micro:bit takes a single reading of the light sensor before entering the forever loop and uses this value to compare against the lightVal variable in the forever loop. This value doesn’t change in the forever loop, as it is set before entering the forver loop. To update this value, you can press the RESET button on the back of your micro:bit or power cycle the board.

What You Should See

When the micro:bit runs the program, it will take a single reading from the light sensor and use that as a calibration value of the “normal” state of the room. When you place your hand over the light sensor or turn the lights off, the LED will turn on. If you turn the lights back on or uncover the light sensor, the LED will turn off.

Troubleshooting

LED Remains Dark

You may have been leaning over the light sensor when the code started. Make sure the light sensor is reading the normal light in the room at startup. Try resetting the micro:bit.

Still Not Quite Working

Double-check your wiring of the signal pin; sometimes you miss a breadboard connection by a row.

Experiment 4: Driving an RGB LED

Introduction

You know what’s even more fun than a blinking LED? Changing colors with one LED! In this circuit you’ll learn how to use an RGB LED to create unique color combinations. Depending on how bright each diode is, nearly any color is possible!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1X micro:bit Breakout with Headers
  • 1x Common Cathode RGB LED
  • 3x 100Ω Resistors
  • 5x Jumper Wires

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

$4.95

35

micro:bit Board

micro:bit Board

In stock DEV-14208

$14.95

3

SparkFun micro:bit Breakout (with Headers)

SparkFun micro:bit Breakout (with Headers)

In stock BOB-13989

$5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

Out of stock PRT-12795

$1.95

2

LED - RGB Clear Common Cathode

LED - RGB Clear Common Cathode

In stock COM-00105

$1.95

2

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

$0.95

2

Introducing the Red/Green/Blue (RGB) LED

alt text

The Red/Green/Blue (RGB) LED is three LEDs in one. The RGB has four pins with each of the three shorter pins controlling an individual color: red, green or blue. The longer pin of the RGB is the common ground pin. You can create a custom-colored LED by turning different colors on and off to combine them. For example, if you turn on the red pin and green pin, the RGB will light up as yellow.

But which pin is which color? Pick up the RGB so that the longest pin (common ground) is aligned to the left as shown in the graphic below. The pins are Red, Ground, Green and Blue — starting from the far left.

Note: When wiring the RGB, each colored pin still needs a current-limiting resistor in line with the micro:bit’s I/O pin that you plan to use to control it, as with any standard LED.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram and hookup table below to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

alt text

Code to Note

Using the random module

MicroPython comes with a random module to introduce a little unknown into your programs. There are a few ways you can use the random module beyond using it as a random number generator the way it is used in this experiment. To see the documentation, read the official docs on the random module.

In this experiment we are using random to generate a random number between 0 and 255

button_a.is_pressed() and button_b.is_pressed()

button_a and button_b represent the left and right buttons on the micro:bit respectively. There are three built-in functions that can be attached to button_a or button_b:

  • is_pressed() — Will return True if the button specified is pressed. If the specified button is not pressed, it will return False.
  • was_pressed() — Will return True or False depending on whether the specified button was pressed since start-up or since the last time this statement (method) was called.
  • get_pressed() — Will return the number of times the specified button has been pressed since the device started or since the last time the statement (method) was used. Once the method is used, it will reset to zero.

elif

The elif statement lets you check for multiple expressions that might be True. In this experiment we want to do different things whether button A pressed is True or button B pressed is True.

What You Should See

You should see your LED turn on red. If you press the A button on the micro:bit, the color will change to green, and if you press the B button, the color will change to blue.

Troubleshooting

LED Remains Dark or Shows Incorrect Color

With the four pins of the LED so close together, it’s sometimes easy to misplace one. Double check that each pin is where it should be.

Seeing Red

The red diode within the RGB LED may be a bit brighter than the other two. To make your colors more balanced, use a higher ohm resistor.

Experiment 5: Reading an SPDT Switch

Introduction

In this experiment you will use your first digital input: a switch. The SPDT (Single-Pole, Double-Throw) switch is a simple way to select between two options, especially when paired with an “if” state. You will use that switch to select which of the two LEDs will blink.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 2x LEDs (1 Red, 1 Yellow)
  • 2x 100Ω Resistors
  • 8x Jumper Wires
  • 1x SPDT Switch

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

$4.95

35

micro:bit Board

micro:bit Board

In stock DEV-14208

$14.95

3

SparkFun micro:bit Breakout (with Headers)

SparkFun micro:bit Breakout (with Headers)

In stock BOB-13989

$5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

Out of stock PRT-12795

$1.95

2

Mini Power Switch - SPDT

Mini Power Switch - SPDT

In stock COM-00102

$1.50
LED - Basic Red 5mm

LED - Basic Red 5mm

In stock COM-09590

$0.35
Resistor 100 Ohm 1/4th Watt PTH - 20 pack

Resistor 100 Ohm 1/4th Watt PTH - 20 pack

In stock COM-13761

$0.95

Suggested Reading

Before continuing with this tutorial, we recommend you be somewhat familiar with the concepts in these tutorials:

  • Switch Basics
  • Analog vs. Digital
  • Digital Logic

Introducing the Single-Pole, Double-Throw (SPDT) Switch

alt text

The Single-Pole, Double-Throw (SPDT) switch has a common pin in the middle and then two other pins that, depending on the location of the switch, are either connected to the common (center) pin or not. To read the switch in a similar way to a button, you connected the common pin to a digital General Purpose Input/Output (GPIO) pin on your micro:bit and the other pins to 3.3V and ground. It doesn’t matter which pin is which. When you move the switch, the common pin will either be HIGH (connected to 3.3V) or LOW (connected to ground).

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram and hookup table below to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail you will need to jump between the upper end and lower end.

Run Your Script

alt text

Code to Note

pin0.read_digital()

Just as the write_digital() statement turns a pin on (1) or off (0), the read_digital() statement determines the state of a pin, which is either HIGH (1) or LOW (0). By building a circuit that connects 3.3V or ground to a pin, we can detect if a switch is thrown or a button is pressed.

What You Should See

Depending on the state of the switch, a different LED will blink. If you move the switch to connect the signal pin to 3.3V (HIGH) then the LED connected to pin P15 will blink. If you flip the switch and ground the signal pin, then the LED on pin P16 will start blinking, and LED 1 will turn off.

Troubleshooting

Light Not Turning On

The wires for the switch are right next to each other. Make sure that signal is in the center with voltage and ground on the outside pins. If you connect ground and voltage, your board will short out and shut down.

Make sure your power LED is on. If it is off, pull the signal wire and see if that changes anything. If you short circuit your micro:bit board, it will turn itself off to protect the circuitry.

Underwhelmed

No worries; these circuits are all super stripped-down to make playing with the components easy, but once you throw them together, the sky is the limit.

Experiment 6: Reading a Button Press

Introduction

Up until now, we’ve focused mostly on outputs. Now we’re going to go to the other end of the spectrum and play around with inputs. In Experiment 2, we used an analog input to read the potentiometer. In this experiment, we’ll be reading one of the most common and simple inputs — a push button — by using a digital input. We will use it to cycle through different colors on the RGB.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x RGB LED
  • 3x 100Ω Resistors
  • 8x Jumper Wires
  • 1x Push Button
  • 1x 10kΩ Resistor

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

$4.95

35

micro:bit Board

micro:bit Board

In stock DEV-14208

$14.95

3

SparkFun micro:bit Breakout (with Headers)

SparkFun micro:bit Breakout (with Headers)

In stock BOB-13989

$5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

Out of stock PRT-12795

$1.95

2

LED - RGB Clear Common Cathode

LED - RGB Clear Common Cathode

In stock COM-00105

$1.95

2

Momentary Pushbutton Switch - 12mm Square

Momentary Pushbutton Switch - 12mm Square

In stock COM-09190

$0.50

4

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

$0.95

2

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

In stock COM-11508

$0.95

Suggested Reading

Before continuing with this experiment, we recommend you be somewhat familiar with the concepts in these tutorials:

Introducing the Push Button

alt text

A momentary push button closes or completes the circuit only while it is being pressed. The button has four pins, which are broken out into two sets of two pins. When you press down on the button and get a nice “click,” the button bridges the two sets of pins and allows current to flow through the circuit.

How do you know which pins are paired up? The buttons included in this kit will only fit across the breadboard ditch in one direction. Once you get the button pressed firmly into the breadboard (across the ditch), the pins are horizontally paired. The pins toward the top of the breadboard are connected, and the pins toward the button of the breadboard are connected.

Note: Not all buttons share this pin format. Please refer to the data sheet of your specific button to determine which pins are paired up.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram and hookup table below to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Run Your Script

alt text

Code to Note

Pins on the micro:bit are active-low, which means external buttons should be connected to the pin and to ground to trigger an event with a button. This cannot be changed in MicroPython the way it can be changed in MakeCode. We have also found that MicroPython has a very hard time with interrupts and can’t seem to run more than one thread at a time. With MakeCode, it is possible to run multiple threads.

pass

Since interrupts are very difficult in MicroPython, we decided to use pass. pass is a way to handle external triggers from a while loop without impacting the while loop. In this case, the external trigger is whether or not the button has been pressed. It is a kind of cheat to using interrupts. We can continuously poll pin 16 on the micro:bit to see if the button has been pressed or not.

iter

The iter()_method creates an object that can be iterated or incremented one element at a time until a specified end. At the end of the iteration, an exception is raised: “StopIteration.”

try and except

try and except allows a program to catch an unexpected (or expected in this case) error and handle the error however the programmer wants to. The error in this case would be how the iter function lets the program know it is past the last iterable value. The exception that is thrown by the iter method is “StopIteration.” We are “trying” next iter until the exception is thrown. Once the exception is thrown, we exit from try and move onto except, which will start the iterator over again.

What You Should See

When you press the button, the RGB will turn on to a color. When you press it again, the color will change, and another press will change the color once again. Press it one more time, and it will turn off. Every time you press the button, it increments a variable, and then we check against it to set the color. If the variable goes over the value of 2, we reset it to 0, which is off.

Troubleshooting

Light Not Turning On

The push button is square, and because of this it is easy to put it in the wrong way. Give it a 90-degree twist and see if it starts working.

Underwhelmed

No worries; these circuits are all super stripped-down to make playing with the components easy, but once you throw them together, the sky is the limit. Remember, though, that these are building blocks to the Iron Man suit.

Experiment 7: Reading the Temperature Sensor

Introduction

A temperature sensor is exactly what it sounds like — a sensor used to measure ambient temperature. In this experiment you will read the raw 0–1023 value from the temperature sensor, calculate the actual temperature and then print it out over the LED array on your micro:bit.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 3x Jumper Wires
  • 1x TMP36 Temperature Sensor

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

$4.95

35

micro:bit Board

micro:bit Board

In stock DEV-14208

$14.95

3

SparkFun micro:bit Breakout (with Headers)

SparkFun micro:bit Breakout (with Headers)

In stock BOB-13989

$5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

Out of stock PRT-12795

$1.95

2

Temperature Sensor - TMP36

Temperature Sensor - TMP36

In stock SEN-10988

$1.50

16

Introducing the TMP36 Temperature Sensor

alt text

The TMP36 is a low-voltage precision centigrade temperature sensor. It provides a voltage output that is linearly proportional to the Celsius temperature. It also doesn’t require any external calibration to provide typical accuracies of ±1°C at +25°C and ±2°C over the −40°C to +125°C temperature range. The output voltage can easily convert to temperature using the scale factor of 10 mV/°C.

If you are looking at the flat face with text on it, the center pin is your signal pin, the left-hand pin is supply voltage (3.3V in this tutorial), and the right-hand pin connects to ground.

Pro Tip: The TMP36 looks a lot like a transistor. Put a dot of fingernail polish on the top of your TMP36 so it’s easy to find.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Please note: The temperature sensor can only be connected to a circuit in one direction. See below for the pin outs of the temperature sensor — TMP36.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

alt text

Code to Note

str

We have already covered display.show() but we need to convert our number (temperature) to a string (type) before displaying it to the micro:bit 5x5 LED array. Type conversion in MicroPython is a snap with a simple str placed in front of the variable holding the temperature of type number.

CHALLENGE: How would you modify this code to get the temperature in degrees Fahrenheit?

What You Should See

When your micro:bit turns on, the temperature reading from the TMP36 temperature sensor will be displayed and scrolled across the LED array.

Troubleshooting

Temperature Value is Unchanging

Try pinching the sensor with your fingers to heat it up or pressing a bag of ice against it to cool it down.

Temperature Sensor is Really Hot!

You have wired it backward! Unplug your micro:bit immediately, let the sensor cool down and double check your wiring. If you catch it soon enough, your sensor may not have been damaged and may still work.

Experiment 8: Using a Servo Motor

Introduction

This experiment is your introduction to the servo motor, which is a smart motor that you can tell to rotate to a specific angular location. You will program it to rotate to a series of locations, then sweep across its full range of motion, and then repeat.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x Servo
  • 3x Jumper Wires

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

$4.95

35

Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

In stock ROB-09065

$8.95

10

micro:bit Board

micro:bit Board

In stock DEV-14208

$14.95

3

SparkFun micro:bit Breakout (with Headers)

SparkFun micro:bit Breakout (with Headers)

In stock BOB-13989

$5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

Out of stock PRT-12795

$1.95

2

Suggested Reading

Before continuing with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Introducing the Servo Motor

alt text

Unlike the action of most motors that continuously rotate, a servo motor can rotate to and hold a specific angle until it is told to rotate to a different angle. You can control the angle of the servo by sending it a PWM (Pulse Width Modulation) pulse train; the PWM signal is mapped to a specific angle from 0 to 180 degrees.

Inside of the servo there is a gearbox connected to a motor that drives the shaft. There is also a potentiometer that gives feedback on the rotational position of the servo, which is then compared to the incoming PWM signal. The servo adjusts accordingly to match the two signals.

In this experiment, the servo is powered through 3.3 volts on the red wire and ground on the black wire; the white wire is connected to pin P0.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Connect 3x jumper wires to the female 3-pin header on the servo. This will make it easier to breadboard the servo.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

alt text

Code to Note

One of the major drawbacks to using MicroPython with the micro:bit is that you can’t import third-party modules. Or at least, we haven’t had any luck flashing two Python files to the micro:bit. This code seems long because we had to paste the Servo Class code into our script. Ignoring the Servo Class code, let’s look at what’s happening inside the forever loop.

range

The range function generates a list of numbers. In this experiment we are generating a list from 0–90 that increases by 5.

Servo(pin0).write_angle()

The Servo Class is called in statement with pin 0 as its argument. The .write_angle() function is how the servo is moved — by the number specified in the parentheses mapped to degrees on the servo motor.

What You Should See

When powered up you should see the servo move to a single location (0 degrees) and then start to sweep to 180 degrees back and forth until you turn it off or tell it to go to a different angle.

CHALLENGE: How would you modify this code to get the servo to sweep to 180 degrees on button A pressed?

Troubleshooting

Servo Not Twisting

Even with colored wires, it is still shockingly easy to plug a servo in backward. This might be the case.

Still Not Working

A mistake we made a time or two was simply forgetting to connect the power (red and black wires) to 3.3 volts and ground (GND).

Experiment 9: Using a Buzzer

Introduction

In this experiment, we will again bridge the gap between the digital world and the analog world. We’ll be using a piezo buzzer that makes a small “click” when you apply voltage to it (try it!). By itself that isn’t terribly exciting, but if you turn the voltage on and off hundreds of times a second, the piezo buzzer will produce a tone. And if you string a bunch of tones together, you’ve got music! This circuit and set of code blocks will create a simple sound machine.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x Piezo Buzzer
  • 2x Momentary Push Buttons
  • 7x Jumper Wires

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

$4.95

35

micro:bit Board

micro:bit Board

In stock DEV-14208

$14.95

3

SparkFun micro:bit Breakout (with Headers)

SparkFun micro:bit Breakout (with Headers)

In stock BOB-13989

$5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

Out of stock PRT-12795

$1.95

2

Mini Speaker - PC Mount 12mm 2.048kHz

Mini Speaker - PC Mount 12mm 2.048kHz

In stock COM-07950

$1.95

5

Momentary Pushbutton Switch - 12mm Square

Momentary Pushbutton Switch - 12mm Square

In stock COM-09190

$0.50

4

Introducing the Piezo Buzzer

alt text

The buzzer is a small component with a piece of metal in it that moves when you apply a voltage across it. This motion causes a small sound, or “click.” If you turn the voltage on and off fast enough, you get different beeps, squeals, chirps and buzzes. You will use PWM to control the speed of turning the piezo on and off — and, in turn, the audio frequency coming out of the buzzer. Adjusting the PWM enables you to get legitimate notes out of the buzzer.

alt text

If you flip the buzzer over and look at the bottom, you will see that one pin has a (+) next to it. That pin gets connected to a signal from the P0 pin. The other pin should be connected to ground.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Run Your Script

alt text

Code to Note

music

MicroPython has an awesome music and sound module. We spent hours generating tones and writing songs in the REPL. As you learn to compose your own music on the micro:bit we highly recommend using the REPL to become familiar with all the sounds — plus the help() feature is nice when you want to see (hear) what you can do.

The music module has 21 melodies built in. To see a list, begin typing music.play(_... in the Mu editor, and the list should pop up.

To get an in-depth tutorial on the music module, click here.

music.play()

To play a tune you need to specify a note (A, C#, F), an octave (0–8) and a duration (how long the note will be played). For example, if the button on pin 15 is pressed, the note C in octave 4 will play for a duration of 8.

What You Should See

What you should see — well, nothing! What you should hear — each button has its own tune. Enjoy your sound machine and feel free to swap out the song and tunes of your choice. Add more buttons and play statements to make your custom piano!

Try it again but with a real speaker. At the press of a button you could play the funeral march, Happy Birthday or the Nyan Cat theme with much better audio!

Troubleshooting

No Sound

Given the size and shape of the piezo buzzer, it is easy to miss the right holes on the breadboard. Try double checking its placement.

Also, double check to make sure the push button is wired correctly. If you miswired it, then the circuit will never be completed, whether you press the button or not.

Experiment 10: Using the Accelerometer

Introduction

In this experiment you will look at combining the use of the accelerometer on the micro:bit to measure the orientation of the micro:bit and using it to control the angle of a servo.

Ready to shake, rattle and roll?

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x Hobby Servo
  • 3x Jumper Wires

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

$4.95

35

Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

In stock ROB-09065

$8.95

10

micro:bit Board

micro:bit Board

In stock DEV-14208

$14.95

3

SparkFun micro:bit Breakout (with Headers)

SparkFun micro:bit Breakout (with Headers)

In stock BOB-13989

$5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

Out of stock PRT-12795

$1.95

2

Introducing the Accelerometer

The accelerometer is a component that you won’t find in the kit’s bag of parts. Why? Because it is on the micro:bit itself! On the back of the micro:bit you can see a number of small chips. One of them is the accelerometer.

Accel closeup

An accelerometer is a sensor that measures the gravitational forces pulling on it in all three dimensions of the chip’s X, Y and Z axes.

alt text

Not only can an accelerometer measure the raw forces pulling on the chip and the object that the chip is sitting on, but it can also detect steps, shakes and other motions that have a specific pattern. On top of that, you can use an accelerometer to simply detect the orientation of the device. Did you ever wonder how your phone knows when you turn it from portrait to landscape? It is all because of the accelerometer in your phone!

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

alt text

Code to Note

Ignoring the servo class code again, we’ve got some new stuff!

accelerometer.get_x()

The accelerometer module comes with five built-in functions and recognizes 11 gestures. To see the full documentation, click here. The accelerometer.get_x() statement will return the acceleration measurement on the x-axis as a number between -1024 and 1024, depending on the direction.

Since the value stored in num needs to translated to an angle between 0-180 from a range between -1024 and 1024 it needs to be scaled. Adding 90 to the scaled value sets a range of angles for the negative accelerometer values from 0-89, and positive accelerometer values from 90-180.

What You Should See

At the beginning of the program the servo should move to 0 degrees and then react to the orientation of the micro:bit. If you hold the micro:bit flat, the servo will be at 90 degrees. Then if you tilt the servo to the left, it will move less than 90 degrees toward the value of 0. If you move it to the right, the servo will move toward 180.

Troubleshooting

This Seems Backward

You may be holding the micro:bit in a different orientation. Flip it around and try again!

Servo Isn’t Working

Double check your wiring! Remember, red to 3.3 volts, black to ground, and white to signal.

Resources and Going Further

MicroPython is a fun and exciting way to get started on your Python programming journey. Here are some more resources to help you along.

We produce a number of other kits and carrier boards that you can hook up to your micro:bit to help take your projects to the next level. Here is some further reading that may help you along in learning more about the world of electronics.

For more information on our micro:bit ecosystem, check out these tutorials:

micro:climate Kit Experiment Guide

A weather station kit that is built on top of the inexpensive, easy-to-use micro:bit and Microsoft MakeCode.

micro:bot Kit Experiment Guide

Get started with the moto:bit, a carrier board for the micro:bit that allows you to control motors, and create your own robot using this experiment guide for the micro:bot kit.

micro:arcade Kit Experiment Guide

We love games! We love writing games, building games and yes, even building game consoles. So we want to introduce to you the micro:arcade kit for the micro:bit!

micro:bit Breakout Board Hookup Guide

How to get started with the micro:bit breakout board.

Open Source!

All of our experiments and guides are licensed under the Creative Commons Attribution Share-Alike 4.0 Unported License. Feel free to remix and reuse our work. But please, share the love and give us attribution for our hard work!

To view a copy of the license, visit this link, or write to: Creative Commons, 171 Second Street, Suite 300, San Francisco, CA 94105, USA.

Using EAGLE: Schematic

Introduction

PCB design in EAGLE is a two-step process. First you design your schematic, then you lay out a PCB based on that schematic. EAGLE’s board and schematic editors work hand-in-hand. A well-designed schematic is critical to the overall PCB design process. It will help you catch errors before the board is fabricated, and it’ll help you debug a board when something doesn’t work.

This tutorial is the first of a two-part Using EAGLE series, and it’s devoted entirely to the schematic-designing side of EAGLE. In part 2, Using EAGLE: Board Layout, we’ll use the schematic designed in this tutorial as the basis for our example board layout.

1

Suggested Reading

If you’d like to follow along with this tutorial, make sure you’ve installed and setup the EAGLE software. Our How to Install and Setup EAGLE tutorial goes over this process step-by-step, and it also covers the basics of what EAGLE is and what makes it great. It also covers how to download and install the SparkFun EAGLE libraries we’ll be using in this tutorial. Definitely read through that tutorial before you continue on.

We’d also recommend you read and understand the concepts behind these tutorials:

Create a Project

We’ll start by making a new project folder for our design. In the control panel, under the “Projects” tree, right click on the directory where you want the project to live (by default EAGLE creates an “eagle” directory in your home folder), and select “New Project”.

2

Give the newly created, red project folder a descriptive name. How about “Bare Bones Arduino”.

3

Project folders are like any regular file system folder, except they contain a file named “eagle.epf”. The EPF file links your schematic and board design together, and also stores any settings you may have set especially for the project.

Create a Schematic

The project folder will house both our schematic and board design files (and eventually our gerber files too). To begin the design process, we need to lay out a schematic.

To add a schematic to a project folder, right-click the folder, hover over “New” and select “Schematic”.

4

A new, blank window should immediately pop up. Welcome to the schematic editor!

Adding Parts to a Schematic

Schematic design is a two step process. First you have to add all of the parts to the schematic sheet, then those parts need to be wired together. You can intermix the steps – add a few parts, wire a few parts, then add some more – but since we already have a reference design we’ll just add everything in one swoop.

Using the ADD Tool

The ADD tool – (on the left toolbar, or under the Edit menu) – is what you’ll use to place every single component on the schematic. The ADD tool opens up a library navigator, where you can expand specific libraries and look at the parts it holds. With a part selected on the left side, the view on the right half should update to show both the schematic symbol of the part and its package.

5

The ADD tool also has search functionality – very helpful when you have to navigate through dozens of libraries to find a part. The search is very literal, so don’t misspell stuff! You can add wildcards to your search by placing an asterisk (*) before and/or after your search term. For example if you search for atmega328 you should find a single part/package combo in the SparkFun-DigitalIC library, but if you search *atmega328* (note asterisks before and after), you’ll discover two more versions of the IC (because they’re actually named “ATMEGA328P”). You’ll probably want to get accustomed to always adding an asterisk before and after your search term.

6

To actually add a part from a library either select the part you want and click “OK”, or double-click your part.

Step 1: Add a Frame

The frame isn’t a critical component for what will be the final PCB layout, but it keeps your schematic looking clean and organized. The frame we want should be in the SparkFun-Aesthetics library, and it’s named FRAME-LETTER. Find that by either searching or navigating and add it to your schematic.

7

After selecting the part you want to add, it’ll “glow” and start hovering around following your mouse cursor. To place the part, left-click (once!). Let’s place the frame so its bottom-left corner runs right over our origin (the small dotted cross, in a static spot on the schematic).

8

After placing a part, the add tool will assume you want to add another – a new frame should start following your cursor. To get out of the add-mode either hit escape (ESC) twice or just select a different tool.

Step 2: Save (And Save Often)

Right now your schematic is an untitled temporary file living in your computer’s ether. To save either go to File > Save, or just click the blue floppy disk icon – . Name your schematic something descriptive. How about “BareBonesArduino.sch” (SCH is the file format for all EAGLE schematics).

As a bonus, after saving, your frame’s title should update accordingly (you may have to move around the screen, or go to View > Redraw).

Step 3: Adding the Power Input

Next we’ll add four different parts all devoted to our voltage supply input. Use the add tool for these parts:

 

Part Description Library Part Name Quantity
5.5mm Barrel Jack (PTH) SparkFun-Connectors POWER_JACKPTH 1
0.1µF Ceramic Capacitor SparkFun-Capacitors CAPPTH 1
Voltage Supply Symbol SparkFun-Aesthetics VCC 1
Ground Symbol SparkFun-Aesthetics GND 2

All of these parts will go in the top-left of the schematic frame. Arranged like this:

10

If you need to move parts around, use the MOVE tool – (left toolbar or under the Edit menu). Left-click once on a part to pick it up (your mouse should be hovering over the part’s red “+” origin). Then left click again when it’s where it needs to be.

Step 4: Microprocessor and Supporting Circuitry

Next we’ll add the main component of the design – the ATmega328 microprocessor – as well as some components to support it. Here are the parts we’ll add:

 

Part Description Library Exact Part Name Quantity
ATmega328P (PTH) SparkFun-DigitalIC ATMEGA328P_PDIP 1
¼W Resistors SparkFun-Resistors RESISTORPTH-1/4W 4
5mm LEDs SparkFun-LED LED5MM 3
0.1µF Ceramic Capacitor SparkFun-Capacitors CAPPTH 1
Voltage Supply Symbol SparkFun-Aesthetics VCC 2
Ground Symbol SparkFun-Aesthetics GND 4

To rotate parts as your placing them, either select one of the four options on the rotate toolbar – – or right click before placing the part. Place your microcontroller in the center of the frame, then add the other parts around it like so:

13

Step 5: Adding the Connectors

Three connectors will finish off our design. One 8-pin connector to break out the analog pins, a 6-pin serial programming header, and a 2x3-pin ICSP programming header. Here are the three parts to add for this step:

 

Part Description Library Exact Part Name Quantity
8-Pin 0.1" Header SparkFun-Connectors M081X08 1
2x3 AVR Programming Header SparkFun-Connectors AVR_SPI_PRG_6PTH 1
6-Pin Serial Programming Header SparkFun-Connectors ARDUINO_SERIAL_PROGRAMPTH 1
Voltage Supply Symbol SparkFun-Aesthetics VCC 2
Ground Symbol SparkFun-Aesthetics GND 2

Finally! Here’s what your schematic should look like with every part added:

14

Next we’ll wire net them all together.

Wiring Up the Schematic

With all of the parts added to our schematic, it’s time to wire them together. There’s one major caveat here before we start: even though we’re wiring parts on the schematic, we not going to use the WIRE tool – – to connect them together. Instead, we’ll use the NET tool – (left toolbar, or under the Draw menu). The WIRE tool would be better-named as a line-drawing tool, NET does a better job of connecting components.

Use NET not WIRE

Using the NET Tool

To use the NET tool, hover over the very end of a pin (as close as possible, zoom in if you have to), and left-click once to start a wire. Now a green line should be following your mouse cursor around. To terminate the net, left-click on either another pin or a net.

17

The hard part, sometimes, is identifying which part on a circuit symbol is actually a pin. Usually they’re recognizable by a thin, horizontal, red line off to the side of a part. Sometimes (not always) they’re labeled with a pin number. Make sure you click on the very end of the pin when you start or finish a net route.

Route the Power Input Circuit

Start back in the upper left, and route the power input circuit like so:

18

Whenever a net splits in two directions a junction node is created. This signifies that all three intersecting nets areconnected. If two nets cross, but there’s not a junction, those nets are not connected.

Route the ATmega328 Circuit

Next we’ll route the ATmega328 to its supporting circuitry. There’s LEDs, a connector, resistor, capacitor and VCC/GND symbols to route to:

19

Don’t forget to add nets between the LEDs, resistors, and GND symbols!

Making Named, Labeled Net Stubs

The remaining nets we have to make are not going to be as easy to cleanly route. For example, we need to connect the TXO pin on JP2 to the ATmega’s RXD pin, all the way on the other side. You could do it, it would work, but it’d be really ugly. Instead, we’ll make net “stubs” and give them unique names to connect them.

We’ll start by adding short, one-sided nets to each of the six pins on the serial connector. Begin by starting a net at a pin, just as you’ve been doing. Terminate the net by left-clicking a few grid-lengths over to the right of the pin. Then, instead of routing to another pin, just hit ESC to finish the route. When you’re done, it should look like this:

20

Next, we’ll use the NAME tool – (left toolbar, or under the Edit menu) – to name each of the six nets. With the NAME tool selected, clicking on a net should open a new dialog. Start by naming the net connected to the top, GND pin. Delete the auto-generated name (e.g. N$14), and replace it with “GND” (sans the quotation marks). This should result in a warning dialog, asking you if you want to connect this net to all of the other nets named “GND” (that would be every net connected to a GND symbol). Thanks for looking out for us EAGLE, but in this case Yes we do want to connect GND to GND.

After naming a net, you should use the LABEL tool – – to add a text label. With the LABEL tool selected, left-click on the net you just named. This should spawn a piece of text that says “GND”, left-click again to place the label down right on top of your net.

Follow that same order of operations for the remaining five net stubs. In the end, they should look like this (note the net connected to the TXO pin is named “RX”, and a “TX” net connects to RXI – that’s on purpose):

23

VCC should be the only other net that warns you that you’ll be connecting to other nets named “VCC” (anything connected to a VCC voltage node). For the other named nets, we’ll need to create this same stub somewhere else. Where exactly? Well, we need to add a “RX” and “TX” net on the ATmega328, and a “DTR” nearby as well:

24

Even though there’s no green net connecting these pins, every net with the same, exact name is actually connected.

We need to do a lot of the same to connect the 2x3 programming header to the ATmega328. First, wire up the connector like so (naming/labeling MOSI, MISO, SCK, and RESET):

25

Then, back to the ATmega328, add the same four named/labeled nets:

26

Phew – you’re done. Get excited, it’s about time to lay out a PCB! When your schematic is done, it should look a little something like this:

27


The schematic layout is done, but there are a few tips and tricks we’d like to share before moving over to the PCB layout portion of the tutorial.

Tips and Tricks

Names and Values

Every component on your schematic should have two editable text fields: a name and a value. The name is an identifier like R1, R2, LED3, etc. Every component on the schematic should have a unique name. You can use the NAME tool – on any component to change the name.

A part’s value allows you to define unique characteristics of that part. For example, you can set a resistor’s resistance, or a capacitor’s capacitance. The importance of a part’s value depends on what type of component it is. For parts like resistors, capacitors, inductors, etc. the value is a critical piece of information when you’re generating a bill of materials or assembly sheet. To adjust a part’s value parameter, use the VALUE tool – .

Verifying Connections

The SHOW tool – – is very useful for verifying that pins across your schematic are connected correctly. If you use SHOW on a net, every pin it’s connected to should light up. If you’re dubious of the fact that two like-named nets are connected, give the SHOW tool a try. SHOW-ing a net connected to GND, for example, should result in a lot of GND nets lighting up.

31

As an alternative to show, you can temporarily MOVE a part a part to make sure nets are connected to it. Use MOVE to pick a part up, and the nets connected to it should bend and adjust to remain so. Just make sure you hit ESC to notmove the part (or UNDO if you accidentally move it).

32

If all the nets connected to a part MOVE with it, all connections are good.

If a net isn’t moving along with the part, it’s not connected to the pin correctly. Double check to make sure you routed to the very end of the pin, and not a bit further:

33

If you have any nets incorrectly connected like above, DELETE – – it, and try re-netting.

Group Moving/Deleting/Etc.

Any tool that you use on a single component, can also be used on a group of them. Grouping and performing an action on that group is a two-step process. First, use the group tool – – to select the parts you want to modify. You can either hold down the left-mouse button and drag a box around them, or click multiple times to draw a polygon around a group. Once the group is made, every object in that group should glow.

After grouping, select the tool you want to use. The status box in the far bottom-left will have some helpful information pertaining to using the tool on a group:

Group move status box

In order to perform any action on a group, you have to select the tool, then hold down CTRL and right-click the group. After you CTRL+right-click, the tool will operate on the group just as it does a single component.

Copy/Paste

EAGLE’s Copy – – and Paste – – tools don’t work exactly like other copy/paste tools you may have encountered before. Copy actually performs both a copy and paste when it’s used. As soon as you copy a part (or any object on the schematic – name, text, net, etc.) an exact copy will instantly spawn and follow your mouse awaiting placement. This is useful if you need to add multiples of the same part (like GND nodes or resistors).

Paste can only be used to paste a group that has previously been copied to your clipboard. To use paste you first have to create a group, then (with the copy tool selected) CTRL+right-click to copy it, but hit ESC instead of gluing it down. This’ll store the copied group into your operating system’s clipboard, and you can use paste to place it somewhere. This tool is especially useful if you need to copy parts of one schematic file into another.

(note:the article is from the Sparkfun Community)

Working with Wire

Introduction

When someone mentions the word wire, they are more than likely referring to a flexible, cylindrical piece of metal that can vary in size from just a few millimeters in diameter to several centimeters. Wire can refer to either a mechanical or electrical application. An example of a mechanical wire could be a Guy-wire, but this this guide will focus on electrical wiring.

wire

Inside a stranded wire

Electrical wire is a backbone of our society. There is wire in houses to turn on lights, heat the stove, and even talk on the phone. Wire is used to allow current to flow from one place to another. Most wires have insulation surrounding the metallic core. An electrical insulator is a material whose internal electric charges do not flow freely and, therefore, does not conduct an electric current. A perfect insulator does not exist, but some materials such as glass, paper and Teflon, which have high resistivity, are very good electrical insulators. Insulation exists because touching a bare wire could allow current to flow through a persons body (bad) or into another wire unintentionally.

Recommended Reading:

Here are some topics you might want to explore before reading about wire:

Stranded vs Solid

Wire can come in one of two forms, stranded or solid core.

Solid Wire

Various colors of solid core wire

Solid wire is composed of a single piece of metal wire, also known as a strand. One very common type of solid wire is known as wire wrap. Stranded wire is composed of many pieces of solid wire all bundled into one group.

Stranded Wire

Various colors and sizes of stranded wire

Stranded wire is much more flexible than solid wire of equal size. For this reason, stranded wire is used when the wire needs to move around frequently, in a robot arm for example. Conversely, solid wire is used when little or no movement is needed, such as prototyping circuits on a breadboard. Using solid core wire makes it easy to push the wire into a breadboard. Trying to use stranded wire on a breadboard can be very difficult, as the strands want to separate as they are pressed in.

Wire Thickness

The term ‘gauge’ is used to define the diameter of the wire. The gauge of a wire is used to determine the amount of current a wire can safely handle. Wire gauge can refer to both electrical and mechanical. This tutorial will only cover electrical. There are two main systems for measuring gauge, American Wire Gauge (AWG) and Standard Wire Gauge (SWG). The differences between the two are not critical to this guide.

Wire Gauges

An approximate scale of several different gauges of wire

The amount of current that a wire can carry depends on a few different factors, for example the composition of the wire, wire length, and condition of the wire. In general, thicker wire can carry more current.

Amps to Gauge

An approximate wire thickness to current capability chart

Here at SparkFun we typically use 22 AWG wire for prototyping and breadboarding. When using a breadboard, the solid core is perfect because it fits nicely into the breadboard holes. For other prototyping/building involving soldering, the stranded core is #1, just be sure not to let too much current run through a single wire, it will get hot and could melt!

SparkFun carries a variety of both solid and stranded 22 AWG wire. Check it out!

How to Strip a Wire

Safe, durable electrical connections begin with clean, accurate wire stripping. Removing the outer layer of plastic without nicking the wires underneath is critical. If a wire does get nicked, the connection may break or an electrical short may occur.

Nice Wires

No nicks or gouges. These wires have been properly stripped

The Tool

A simple manual wire stripper is a pair of opposing blades much like scissors. There are several notches of varying size. This allows the user to match the notch size to the wire size, which is very important for not damaging the wires.

Wire Strippers - 30AWG (Hakko)
$9.95

     3

Although a knife would also strip the wires, it may also damage the wire by nicking the metal or cutting into it. Using a knife to strip wire is also really dangerous! The knife can easily slip and cause wicked injuries.

Stripping the Wire

Wire in Stripper

By simply squeezing the handles about ¼" from the end of the wire or the desired length, using the correct notch on the tool, and then twisting it slightly, the insulation will be cut free.

Wire After Strip

Then by pulling the wire strippers towards the end of the wire, the insulation should slide right off of the wire.

Tips, Tricks, and Hints

It is important to match the size of wire to the correct notch in the stripper. If the notch is too large, the wire will not get stripped. If the notch is too small, there is a risk of damaging the wire. Using an undersized notch means the strippers will close too far, digging into the wire underneath. With stranded wire, the tool will cut off the outer ring of wires, decreasing the total diameter of wire and reduce the strength of the wire. A nick in solid core wire will severely reduce the strength and flexibility of the wire. The likelihood of the wire breaking upon being bent increases significantly.

Damaged Wire

This wire was not stripped properly, there are gouges and missing strands

If a wire does accidentally get a nick in it, the best plan of action is to cut the damaged part of the wire off and try again.

How to Crimp an Electrical Connector

An electrical connector is a device for joining electrical circuits together using a mechanical assembly. The connection may be temporary or serve as a permanent electrical joint between two wires.

There are hundreds of types of electrical connectors. Connectors may join two lengths of wire together or connect a wire to an electrical terminal.

Connector Types

The Tool

The word crimping in this context means to join two pieces of metal together by deforming one or both of them to hold the other. The deformity is called the crimp.

crimped

The metal has been deformed to pinch the wire and hold it in place

In order to crimp connectors onto a wire, a special tool is required. Note: Pliers are not crimpers! Neither are hammers, vises, needle nose pliers or flat rocks. A good crimper when used correctly will make a cold weld between the wire and the barrel of the connector. If you were to cut a well executed crimp in half you would see a solid form of wire and connector. Using the wrong tool will not achieve a good crimp!

Why is this level of perfection required? A poor crimp leaves air pockets between the wire and connector. Air pockets allow moisture to collect, moisture causes corrosion, corrosion causes resistance, resistance causes heat, and may ultimately lead to breakage.

Crimper Tools

The top crimper will give better results, however the bottom one works just fine too

There are several different styles of crimpers available. The best crimper, shown on the top, has a built in ratchet. As the handles are squeezed together, it will ratchet and prevent the jaws from opening back up. When enough pressure has been applied, the ratchet will disengage and release the crimped part. This ensures enough pressure has been applied. This style of crimper also has a wide jaw to cover more surface area on the connector.

The crimping tool on the bottom can achieve nearly the same results, although it requires the user be be much more vigilant. This style of crimper is generally less sturdy. Attention must be given while crimping to ensure the jaws are lined up properly on the connector. Misalignment will cause a less than desirable crimp connection. Over time, wear and tear from normal usage can also cause the jaws to become separated and not close fully. Generally, squeezing it as hard as possible will be sufficient.

Crimp the Connector

There are several arguments for and against using solid core wire with crimp connections. Many believe crimping to solid core wire creates a weak point in the wire, which can lead to breakage. There is also a greater chance for a crimp connection to come loose with solid core wire because the wire will not conform to the terminal as well. If you must use solid core wire, it is a good idea to solder the wire in place after you crimp it.

First, the correct size wire must be chosen for the terminal size, or vice versa. Next, strip the wire. The amount of exposed wire should be equal to the length of the metal barrel on the connector, usually around ¼” or so. If the stripped wire fits up into the metal portion of the barrel with little or no free space, the connector is the right size.

Good Length

A good length of wire to barrel ratio

Remember: If the wire does not fit in the barrel, or is excessively loose, the wrong size of either wire or connector was chosen.

The wire should then be inserted until the insulation on the wire touches the end of the barrel.

Good Crimp Example

Good: The wire is sticking past the barrel just a little

The wire and terminal are then inserted into the crimper. The color of the terminal’s insulation needs to be matched with the same color on the crimping tool. So if the terminal’s insulation is red, use the spot marked by the red dot on the crimpers. Alternatively, if the crimper does not have color markings, use the gauge markings on the side.

The terminal should be sitting horizontal with the barrel side up. The tool is then held perpendicular to the terminal and placed over the barrel, nearest to the ring (or other connection type). To finish the crimp, the tool is squeezed with a considerable force. In general, it is almost impossible to ‘over crimp’ a connection.

crimped

After the crimp is completed, the wire and connector should still hold together after trying to pull them apart with great force. If the connection can be pulled apart, the crimp was not done correctly. It is better to have the crimp fail now, versus after it has been installed in its application. Below is a military spec chart for crimped connections.

Mil Spec Chart

Common Mishaps

Wrong size connector for the wire or wrong size wire for the connector.

bad crimp 1

Bad crimp. Connector was too small for the gauge of wire chosen.

Be cautious not to strip too much insulation off.

bad crimp 2

Too much insulation has been stripped off, too much bare wire exposed

It is also worth mentioning that, while not necessarily harmful, The wire should not be protruding too far past the barrel. If this happens, trimming the wire is recommended.

bad crimp 3

The excess bare wire should be trimmed off

Resources and Going Further

You should now be familiar with electrical wire and how useful it is in the world of electronics. Whether you’re prototyping, reworking, or building a final product, electrical wire can be your best friend.

Here are some other tutorials you can explore that involve electrical wire.

  • Wire is the most basic element when creating your own circuits.
  • Unsure which connectors to use? Have a look at Connector Basics to get what you need!
  • Want to start prototyping? Check out Breadboards to get going!

 


cc

 Creative Commonstutorials are CC BY-SA 4.0

Original From:

https://learn.sparkfun.com/tutorials/working-with-wire

WS2812 Breakout Hookup Guide

Preface

The WS2812 is an unassuming RGB LED with an integrated control circuit hidden underneath. We love the simplicity of this little IC/LED combo. It’s at the heart of a number of products including the the simple WS2812 Breakout Board.

WS2812B breakout

The LilyPad Pixel shares the same circuit as the breakout board, but it comes on a circular, purple LilyPad board. These are perfect for sewing onto clothing or other fabric, and embedding into an e-textiles project.

LilyPad Pixel ISO

Finally, the WS2812 serves as the heart and soul of a variety of LED strips. These strips come in four flavors: 5 meter sealed, 1m sealed, 5m bare, and 1m bare.

Addressable RGB Strip

What makes the WS2812 really special is the way its controlled. The IC embedded into the LED communicates via a very unique one-wire interface. With the help of some libraries, they’re really very easy to control. Plus they’re chain-able – the output of one LED can be connected to the input of another to create strips of hundreds of LEDs. The more boards you have linked together, the fancier your animations can be!

In this tutorial we’re going to get you familiar with the workings of the WS2812. We’ll go over some of the ways you might want to hook up to the breakout board, LilyPad, or strips. And we’ll close the tutorial out with some example Arduino code.

Required Materials

Stating the obvious: you’ll need a WS2812-based board or strip. The more the merrier! In the example hookup we’ll be linking together five breakout boards, but the example should be adaptable to the other products. Grab however many you think you’ll need for your project, regardless of how many you have, it’s not enough.

Aside from the star of the show, you’ll also need a microcontroller. Something that can send the series of 1’s and 0’s used to control the LEDs. Our go-to is the classic Arduino Uno, but any Arduino board should do. Or you can try to adapt the example code to your favorite microcontroller.

You’ll also need some way to connect between the board and an Arduino. You could use a combination of male headers and breadboard. Or you could just go with a few pieces of wire.

Tools

In order to get a good, solid, electrically-sound connection to the breakout boards, you’ll need to solder to the pins. That means you’ll need at least a basic soldering iron as well as solder. Check out our how to solder tutorial for help, if this is you first time soldering.

Suggested Reading

These boards aren’t too hard to use. If you’ve done anything with Arduino before, you’ll be prepared to work with the WS2812. If you’re not exactly sure what this “Arduino” thing is, or if you’re not familiar with the topics below, consider reading their tutorials:

WS2812 Overview

The WS2812 is much more than meets the eye. It may look like a common 5050-sized (5x5mm) LED, but there’s actually an integrated circuit embedded inside there too. If you look really hard, you can see the tiny black chip hidden in there, along with minuscule gold wires connecting the chip to the LED.

Zoom in on the IC

Pretty nifty view at the guts of the WS2812.

The LED itself is like any RGB (Red/Green/Blue) LED. The brightness of each color can be adjusted using pulse-width modulation to one of 256 different levels. That means there are 16,777,216 (2563) possible combinations of colors. You can produce any color from white to black (off), or salmon to sienna.

Breakout Board Pinout

The Breakout board mounts that multi-taltented LED onto a PCB, and breaks out the few pins required to control the LED.

Annotated WS2812 Breakout pinout

Four unique pins are broken out:

  • 5V – This should be a regulated supply voltage between 5V and about 7V. More than that could harm the LED, less than 5V will either reduce brightness, or it just won’t turn on.
  • GND – The common, ground, 0V reference supply voltage.
  • DI – Data from a microcontroller (or another WS2812 pixel) comes into this pin.
  • DO – Data is shifted out of this pin, to be connected to the input of another pixel or left floating if it is the last link in the chain.

Data Transmission Interface

Note: this stuff is ugly, and not critical to understand if you just want to use the breakout board. (That’s what libraries are for, right?!) It’s interesting to talk about, because the interface is so unique.

The communication interface between a microcontroller and the WS2812 is weird. It’s one wire, but it’s not like a standard, UART serial interface. This interface is very time-specific. Both a logic 0 and a logic 1 require a square pulse, and it’s the length of the pulse that defines which it is.

Data code chart

Timing diagram for a single bit of value 0 or 1.

The data is sent in a sequence containing 24 of those bits – 8 bits for each color – followed by a low “reset” pulse of at least 50µs.

Data bit order

A sequence of 24 timed-bits sets the color for each channel. 8-bits per channel. Green first, then red, then blue.

The larger the value of a specific color is, the brighter it will be. If every color is set to 0, the LED will be off. If every color is set to max – 255 – the LED will be as bright and white as can be.

This is all to say that the interface is very time-specific. To run the LEDs you’ll need a real-time processor, like an Arduino; microprocessors like those on the Raspberry Pi or pcDuino can’t give you a reliably-timed pulse. Even if one bit is less than a microsecond off, that could mean the difference between purple and maroon.

LilyPad Pixel

Want to embed the WS2812 LEDs into your clothing? We have a thing for that! The LilyPad Pixel Board is the e-textile version of the WS2812 Breakout. The functionality and pinouts are exactly the same, though the pins are in slightly different location to make threaded traces easier.

LilyPad Pixel

Rather than solder these boards, you can use conductive thread to connect them to other LilyPad boards. You can control individual LEDs, or chain them together to create a multitude of colors on your clothing. The examples in this tutorial use the WS2812 Breakout, but you can substitute the LilyPad Pixel for any of the breakout boards.

Addressable LED Strips

If you need an abundance of WS2812 LEDs in a slick, pre-assembled form factor these addressable LED strips might be for you.

LED strip overview

The LED strips come on a reel as shown above.

The WS2812 Addressable LED strips come in four product options, which vary by size and sealant. You can get them in either 1m or 5m lengths, and for each length the strip can be either covered by a waterproof sealant or left bare.

The waterproofed strips are rated IP65 – dust tight and protected from water jets.

Zoom in on LED strip

Each strip has 60 LEDs per meter, which are spaced about 1.65cm away from each other.

Connecting to the Strips

Each end of the LED strip is terminated with a set of three colored wires: red, yellow, and green. Two wires are for power, and the third transmits data either into our out of the strip:

Wire Color Function Notes
Red Vcc WS2812 power supply. Should be a regulated supply between 5V and 7V.
Yellow GND Ground. 0V.
Green Data In/Out Serial data in or out. Look at arrows and labels on strip to check which it is.

LED strip connectors

Each of the wire pigtails are terminated by a three-pin JST SM connector, which you can use to connect string strips together. For the first strip in a string, you can either connect to a mating connector, or cut and strip the wires, and connect them to your controlling device.

Hardware Hookup

The great thing about these LEDs is they’re super easy to chain together. Plus just one, single pin from your microcontroller is required to control an entire strip of LEDs. In this example we’ll link together five LEDs, but you should be safe to increase that ten-fold or even more.

Solder/Sew/Wire Something

The first assembly step for each of these products is creating a reliable, electrical connection from the LED to your control board. You’ll need to solder either headers or wires to your breakout boards. Or sew your LilyPad Pixel withconductive thread. Or strip and splice some wire to connect up the LED strips.

If you’re going to stick the boards into a breadboard or other prototyping board, straight male headers might be the best choice.

Breakouts breadboarded

WS2812 breakouts linked together on a breadboard. Hidden under each is a white wire that connects DO of one to DI of the next.

If you’re going to make a big strip of boards, you may need to opt for the stranded wire route.

Breakouts wired together

Link WS2812 boards together in a chain, by connecting DIs to DOs (don’t forget power too). Sorry, the fancy green boards aren’t available :(.

Select a Power Source

The WS2812 requires about 5V to work. It should operate at anywhere between about 4V to 7V, but 5V is readily-available on most boards. The 5V header on an Arduino board, for example, is a perfect voltage supply for the LEDs.

Also consider how much current your LED strip is going to pull. With every single LED on at full brightness, each breakout board can pull about 60mA (20mA per channel). Even with just ten breakout boards strung together, you’re looking at upwards of a possible 600mA. Yikes! If you’re stringing together a lot of these things, make sure your power supply can provide the necessary current-umph. If you end up using an external power supply, make sure you connect the power supply ground to your Arduino ground as well.

Connecting an Arduino

This hookup is fairly straightforward. You can power the breakout board(s) using the Arduino’s 5V and GND pins. Then all you need is to pick a free I/O pin to send data to the LED. Let’s go with pin 4. To link more breakouts together, simply connect the output pin of one to the input of the next. Make sure each breakout also gets some power delivered to it.

Five boards hooked up to an Arduino

Protect your WS2812’s!

In addition to the hookup above we recommend the following additions to help you get the most out of your WS2812-based devices:

Add a Big Smoothing Capacitor

Before connecting the WS2812 to a power source, connect a big capacitor from power to ground. A cap between100µF and 1000µF should be good.

1000uF cap

This cap will help to smooth out your power supply. The current draw of a WS2812 can vary wildly, and as current draw grows and shrinks it’ll be up to your power source to compensate. The cap will act as a “power reservoir” to store energy in case the supply dips.

Try to place this cap as close to your WS2812 as possible.

Add an In-Line Resistor On the Data Signal

Placing a small-ish resistor between your Arduino’s data output and the WS2812’s data input will help protect the data pin. A resistor between 220 and 470 Ω should do nicely.

330 Ohm resistor

Try to place the resistor as close to the WS2812 as possible.

Keep Wires Short!

Wires don’t conduct perfectly. They’ll inevitably induce some voltage loss, especially when they’re really long. Try to keep wires between your power supply, Arduino, and WS2812 as short as possible to minimize this loss.

Adding Firmware

For our example code, we’ll be making use of Adafruit’s fantastic NeoPixel library.

Click here to download a copy of both the example code, as well as the NeoPixel library. The library is located in the “Adafruit_NeoPixel” folder, and the example code is found in the “WS2812_Breakout_Example” folder.

You’ll need to install the library. For help there, check out our installing Arduino libraries tutorial.

With the library installed, open up WS2812_Breakout_Example.ino within Arduino. Before you upload the code, make sure you adjust the PIN and LED_COUNT definitions near the top of the sketch. These define which pin the first pixel is connected to, and how many total LEDs are linked up. Then upload away and enjoy the show!

Redboard controlling five breadboarded breakout boards

Using the NeoPixel Library

Setup

There are a few lines of code required to set up your sketch to use the library. First, call the constructor near the top of your code (before setup(), you’ll probably want it to be a global variable).

#define PIN 4
#define LED_COUNT 8

// Create an instance of the Adafruit_NeoPixel class called "leds".
// That'll be what we refer to from here on...
Adafruit_NeoPixel leds = Adafruit_NeoPixel(LED_COUNT, PIN, NEO_GRB + NEO_KHZ800);

The PIN and LED_COUNT parameters in that function call should be set, respectively, to the Arduino pin you’ve connected to the first breakout’s “DIN” pin and the total number of breakout boards you have linked up.

The rest of the setup is calling the leds.begin() function somewhere near the beginning of the setup() function.

Setting An LED

Setting an LED with the Adafruit NeoPixel library is a two step process. First, you have to set a pixel color using theleds.setPixelColor(position, color) command. The color parameter in that function can either be a 24-bit RGB color-code, or three separate bytes for each color. For example:

leds.setPixelColor(4, 0xFF00FF);    // Set fourth LED to full red, no green, full blue
leds.setPixelColor(4, 0xFF, 0x00, 0xFF)  // Also set fourth LED to full red, no green, full blue

Setting a pixel’s color does not equate to that pixel actually turning on though. For that, you need to callleds.show(). Note that when this function is called any LED that was previously set will turn on.

The Rest of the Code

After you’ve gotten the hang of using the NeoPixel library, the remaining parts of the sketch are finding ways to maniuplate the pixel colors. There are some fun functions in this example code, which create the classic “cylon” larson scanner, or draw a rainbow. We hope you can adapt them to make even more creative animations.

The included “WS2812_Definitions.h” file defines a huge list of standard colors. In there you’ll find anything from navyto saddle brown to ghost white.

Have fun!

Going Further and Resources

Resources

For more information on the LilPad Pixel Board, check out this other tutorial.

LilyPad Pixel Board Hookup Guide

SEPTEMBER 16, 2015

Add changing colors to your wearable projects using LilyPad Pixel Boards.

Going Further

Now that you’ve got the gist of the WS2812 Breakout board, how are you going to use it in a project? Need some inspiration? Check out these tutorials:

  • Using OpenSegment – The OpenSegment is a very large, 4-digit 7-segment display. If you’re on a blinky-high after playing with the WS2812 LEDs, this is another fun component to play with.
  • Getting Started with the LilyPad MP3 Player – If you’re into e-textiles (or even if you’re not, this thing is awesome), check out the LilyPad MP3 Player. Combine the LilyPad MP3 player with the WS2812 to make a nifty LED-music show.
  • Designing PCBs: Advanced SMD – If you’d like to lay out your own, custom PCB for the WS2812 LED/chip, check out this tutorial. It’ll walk you through every step required to design your very own circuit board using free software. You can use the WS2812 footprint from our parts library to get started.

Connector Basics

Introduction

Connectors are used to join subsections of circuits together. Usually, a connector is used where it may be desirable to disconnect the subsections at some future time: power inputs, peripheral connections, or boards which may need to be replaced.

Covered in This Tutorial

In this tutorial we will go over:

  • Basic connector terminology
  • Categorize connectors into distinguishable categories
  • Talk about the differences between connectors within those categories.
  • Show how to identify polarized connectors
  • Talk about which connectors are best suited for certain applications

Suggested Reading

You may find these concepts useful before starting on this tutorial:

Connector Terminology

Before we get started discussing some commonly used connectors, let’s explore the terminology used to describe connectors.

Gender - The gender of a connector refers to whether it plugs in or is plugged into and is typically male or female, respectively (kids, ask your parents for a more thorough explanation). Unfortunately, there are cases where a connector may be referred to as “male” when it would appear to be female; in the examples section, we’ll point a few of those out as we discuss individual component types and explain why that’s the case.

Male and female 2.0mm PH series JST connectors

Male (left) and female 2.0mm PH series JST connectors. In this case, gender is determined by the individual conductor.

Polarity - Most connectors can only be connected in one orientation. This trait is called polarity, and connectors which have some means to prevent them being connected wrong are said to be polarized, or sometimes keyed.

North America wall plug

A polarized North American wall plug. By having two different widths for the plug blades, the plug will only go into the outlet one way.

Contact - Contacts are the business portion of the connector. They are the metal parts which touch each other, forming an electrical connection. This is also where problems occur: the contacts can become soiled or oxidized, or the springiness required to hold the contacts together may fade with time.

ADH8066 mating connector

The contacts on this connector are clearly visible.

Pitch - Many connectors consist of an array of contacts in a repeated pattern. The pitch of the connector is the distance from the center of one contact to the center of the next. This is important, because there are many families of contacts which look very similar but may differ in pitch, making it difficult to know that you are purchasing the right mating connector.

.1" pin header connector examples

The pitch of the pins on the headers on a standard Arduino is .1".

Mating cycles - Connectors have a finite life, and connecting and disconnecting them is what wears them out. Datasheets usually present that information in terms of mating cycles, and it varies widely from one technology to another. A USB connector may have a lifetime in the thousands or tens of thousands of cycles, while a board-to-board connector designed for use inside of consumer electronics may be limited to tens of cycles. It’s important that you select a connector with a suitable life for the application.

Connector for GS406 GPS module

Mating connector for the GS406 GPS module. The connector’s datasheet indicates a maximum of 50 insertion cycles for this part.

Mount - This one has the potential for being confusing. The term “mount” can refer to several things: how the connector is mounted in use (panel mount, free-hanging, board mount), what the angle of the connector is relative to its attachment (straight or right-angle), or how it is mechanically attached (solder tab, surface mount, through hole). We’ll discuss this more in the examples section for each individual connector.

Comparison of different mounting methods for barrel-type connectors

A comparison of three different methods of mounting the same barrel connector: (left to right) board mount, inline cable mount, and panel mount.

Strain relief - When a connector mounts to a board or cable, the electrical connections tend to be somewhat fragile. It is typical to provide some kind of strain relief to transfer any forces acting on that connector to a more mechanically sound object than the fragile electrical connections. Again, there will be some good examples of this later on.

1/8" Headphone jack showing strain relief

This 1/8" headphone jack comes with a strain relief “boot” slid over the cable to prevent forces on the cable from being transmitted directly to the electrical joints.

USB Connectors

USB connectors come in two flavors: host and peripheral. In the USB standard, there is a difference between the two, and the connectors on cables and devices reflect this. However, all USB connectors will have some things in common:

  • Polarization - A USB connector can only nominally be inserted one way. It may be possible to force a connector in wrong, but that will result in damage to the device.
  • Four contacts - All USB connectors have at least four contacts (although some may have five, and USB 3.0connectors have even more). These are for power, ground, and two data lines (D+ and D-). USB connectors are designed to transmit 5V, up to 500mA.
  • Shielding - USB connectors are shielded, such that a metal shell which is not part of the electrical circuit is provided. This is important to keep the signal intact in environments with a lot of electrical “noise”.
  • Robust power connection - It’s important for the power pins to make connection before the data lines, to avoid trying to power the device over the data lines. All USB connectors are designed with this in mind.
  • Molded strain relief - All USB cables have plastic overmolding at the connector to prevent strain on the cable that could potentially damage the electrical connections.

Labeled image of USB extension cable

USB extension cable, with some of the common features of USB connectors labeled.

USB-A Connectors

USB-A female is the standard “host” connector type. This is found on computers, hubs, or any device intended to have peripherals plugged into it. It is also possible to find extension cables with a female A connector and a male A connector on the other end.

USB-A ports on a laptop computer.

Female USB-A ports on the side of a laptop. The blue connector is USB 3.0 compliant.

USB-A male is the standard “peripheral” connector type. Most USB cables will have one end terminating in a USB-A male connector, and many devices (such as keyboards and mice) will have a built-in cable terminated with a USB-A male connector. It’s also possible to find USB-A male connectors that are board mountable, for devices like USB memory sticks.

USB-A male connector examples

Two types of Male USB-A connectors, on a SparkFun Cerberus cable and an AVR Stick development board.

USB-B Connectors

USB-B female is a standard for peripheral devices. It’s bulky, but robust, so in applications where size is not an issue, it’s the preferred means for providing a removable connector for USB connectivity. It is usually a through-hole board mount connector, for maximum reliability, but there are panel-mount options for it as well.

USB-B connector on an Arduino Uno

Arduino boards, including this Uno, have long used the female USB-B connector, due to its low cost and durability.

USB-B male is almost exclusively found at the end of a cable. USB-B cables are ubiquitous and inexpensive, which also contributes to the popularity of the USB-B connection.

Male USB-B connector

USB-B male connector on the end of a SparkFun Cerberus cable.

USB-Mini Connectors

The USB-Mini connection was the first standard attempt to reduce the size of the USB connector for smaller devices. USB-Mini female is typically found on smaller peripherals (MP3 players, older cellphones, small external hard drives), and is usually a surface mount connector, trading robustness for size. USB-Mini is slowly being phased out in favor of the USB-Micro connector.

USB-Mini female connector

USB-Mini female connector on a Protosnap Pro Mini.

USB-Mini male is another cable-only connector. As with USB-B, it’s extremely common, and cables can be found cheaply almost anywhere.

USB-Mini male connector

USB-Mini male connector on the end of a SparkFun Cerberus cable.

USB-Micro Connectors

USB-Micro is a fairly recent addition to the USB connector family. As with USB-Mini, the primary concern is size reduction, but USB-Micro adds a fifth pin for low-speed signalling, allowing it to be used in USB-OTG (On-the-go) applications where a device may want to operate as either a host or a peripheral depending on circumstances.

USB-Micro female is found on many newer peripherals, such as digital cameras and MP3 players. The adoption of USB-micro as a standard charge port for all new cellular phones and tablet computers means that chargers and data cables are becoming increasingly common, and USB-Micro is likely to supplant USB-Mini in the coming years as the small-factor USB connector of choice.

USB-Micro female connector

USB-Micro female connector on a LilyPad Arduino USB board.

USB-Micro male is also a cable-only connector. There are generally two types of cables with USB-Micro male ends: one for connecting a device with a USB-Micro port as a peripheral to a USB host device and one for adapting the USB-Micro female port to a USB-A female port, to be used in USB-OTG capable devices.

USB-Micro male connector

USB-Micro male connector on the SparkFun Cerberus cable.

USB-A female to USB-Micro adapter

Adapter pigtail for using USB-OTG capable devices having only a USB-Micro port with standard USB peripherals. Note that not all devices supporting USB-OTG will work with this pigtail.

Audio Connectors

Another familiar connector group are those used for audio-visual applications–RCA and phono. While these can’t truly be considered to be of the same family, as the various USB connectors are, we’ll consider both of them to be in the same vein.

“Phone” Type Connectors

You’ll probably immediately recognize the 1/8" version of this connector as a the plug on the end of a pair of headphones. These connectors actually come in three common sizes: ¼" (6.35mm), 1/8" (3.5mm), and 2.5mm. ¼" size connectors find a lot of use in the professional audio and music community- most electric guitars and amplifiers have ¼" tip-sleeve (TS) jacks on them. 1/8" tip-ring-sleeve (TRS) is very common as the connector for headphones or audio output signals on MP3 players or computers. Some cell phones will provide a 2.5mm tip-ring-ring-sleeve (TRRS) jack for connecting to headphones that also include a microphone for hands-free communications.

The common availability of these connectors and cables makes them a good candidate for general purpose connectivity applications–for instance, long before USB, Texas Instruments graphing calculators used a 2.5mm TRS connector for a serial programming connector. It should be remembered that tip-sleeve connector types are not designed for carrying power; during insertion, the tip and the sleeve can be momentarily shorted together, which may damage the power supply. The lack of shielding makes them poor candidates for high-speed data, but low speed serial data can be passed through these connectors.

1/8" TRS phone plug

Headphone-type TRS phone plug, 1/8". Typically, tip and ring will carry the stereo audio signals while sleeve will be connected to ground.

1/8" TS phone plug

1/8" phone plug. Note the lack of a ring contact on this connector.

1/8" board mount headphone jack

1/8" board mount headphone jack with pins corresponding pin connections labeled. When no jack is inserted, an internal switch connects the tip and ring pins to the adjacent unmarked pins, allowing insertion detection.

RCA Connectors

Familiar as the home-stereo connector of choice for many decades, the RCA connector was introduced in the 1940s by RCA for home phonographs. It is slowly being supplanted by connections like HDMI in the audio-visual realm, but the ubiquity of the connectors and cables makes it a good candidate for home-built systems. It will be a long time before it is obsolete.

Female RCA connectors are usually found on devices, although it is possible to find extension or conversion cables with female jacks on them. Most RCA connectors are connected to one of four types of signals: component video (PAL or NTSC, depending on where the equipment was sold), composite video, stereo audio, or S/PDIF audio.

Female RCA plug, for video signals.

Female RCA connector, for video signals. Typically, NTSC or PAL video signal connectors will be yellow.

Male RCA connectors are usually found on cables.

Male RCA plugs

Male RCA plugs. Red and white are usually for audio applications, with red denoting the “right” audio channel.

Power Connectors

While many connectors carry power in addition to data, some connectors are used specifically to provide power connections to devices. These vary widely by application and size, but we will only focus on some of the most common ones here.

Barrel Connectors

Barrel connectors are typically found on low-cost consumer electronics which can be plugged into wall power via bulky AC wall adaptors. Wall adaptors are widely available, in a variety of power ratings and voltages, making barrel connectors a common means for connecting power to small projects.

The female barrel connector, or “jack”, can be purchased in several varieties: PCB mounted (surface mount or through hole), cable mount, or panel mount. Some of these connectors will have an additional contact that allows the application to detect whether a power supply is plugged into the barrel jack or not, thus allowing the device to bypass batteries and save battery life when running on external power.

Female barrel connector

Female barrel connector. When no plug is inserted, the “insertion detection” pin will be shorted to the “sleeve” pin.

The male barrel connector, or “plug”, is usually only found in a wire termination variety, although there are multiple methods of attaching the plug to the end of the wire. It’s also possible to get plugs that come pre-attached to a cable.

Male barrel plug

Unattached male barrel plug, for attachment to any power supply. Note that the sleeve connection is designed to be crimped onto the wire for extra strain relief.

Barrel connectors provide only two connections, frequently referred to as “pin” or “tip” and “sleeve”. When ordering, there are three differentiating characteristics of a barrel connection- inner diameter (the diameter of the pin inside the jack), outer diameter (the diameter of the sleeve on the outside of the plug), and polarity (whether the sleeve voltage is higher or lower than the tip voltage).

Sleeve diameter is most commonly either 5.5mm or 3.5mm.

Pin diameter is contingent upon sleeve diameter; a 5.5mm sleeve will have either a 2.5mm or 2.1mm pin. Unfortunately, this means that a plug designed for a 2.5mm pin will fit in a 2.1mm jack, but that the connection will be, at best, intermittent. 3.5mm sleeve plugs usually mate to a jack with a 1.3mm pin.

Polarity is the final aspect to consider; most often, the sleeve will be considered 0V and the tip will be a positive voltage relative to the sleeve. Many devices will have a small diagram indicating the polarity expected by the device; care should be taken to adhere to this, as an improper power supply may damage the device.

Plugs of both sleeve sizes are usually 9.5mm long, but longer and shorter ones do exist. All SparkFun products use a positive polarity 5.5mm sleeve and a 2.1mm pin; we recommend sticking to that standard where possible, as it seems to be the most common flavor found in the wild.

Barrel connector polarity label

Common polarity diagrams for AC adaptors with barrel plugs. Positive polarity (tip positive, sleeve 0V) is most common. Diagram courtesy Wikipedia user Three-quarter-ten.

“Molex” Connectors

Most computer hard drives, optical drives, and other internal peripherals get power through what is typically called a “Molex” connector. To be more accurate, it’s a Molex series 8981 connector–Molex is actually the name of the company which initially designed this connector back in the 1950s–but common usage has denuded that fact somewhat.

Molex connectors are designed to carry a lot of current: up to 11A per pin. For projects where a lot of power may be needed–a CNC machine, for instance, or a 3D printer- a very common method for powering the project is to use a desktop PC power supply and connecting the various system circuits through Molex connectors.

The Molex connector is one where the male/female terminology is a bit odd. The female connector is usually found on the end of a cable, and it slips inside of a plastic shell which surrounds the male pins on the male connector. Usually, the connectors are press-fit only, and very, very tight–they are intended to be connected and disconnected only a few times and, as such, are a bad choice for systems where connections will frequently be changed.

Male Molex connector

Male Molex connector. The gender of the pins inside the connector is what signifies the gender of the connector as a whole.

Female Molex connector

Female Molex connector on a project power supply.

IEC Connector

As with the Molex connector, this is a case where a generalized component name has come to be synonymous with a single, particular item. IEC connector usually refers to the power supply inlet which is commonly seen on desktop PC power supplies. Strictly speaking, that’s an IEC 60320-1 C13 (female) and C14 (male) connector.

IEC 60320-1 C14 male connector

C14 male IEC power inlet, on a DC project power supply. Note that, as with the Molex connector, the gender of the connector is defined by the pins within the hood.

C13 female IEC power connector

C13 female IEC power connector, on a fairly standard AC power supply cable. Cables with this end can be found all around the world, usually with the dominant local AC connector at the other end.

IEC connectors are used almost exclusively for AC power input. The nice thing about using one on a project is that IEC-to-wall cables are extremely common and available with localized wall plugs for most international locations!

JST Connector

At SparkFun, we frequently refer to “2.0mm JST Connectors”. This is yet another generalization of a specific product- JST is a Japanese company which makes high-quality connectors, and our 2.0mm JST connector of choice is the PH series two-position polarized connector.

All of SparkFun’s single-cell lithium-polymer ion batteries come standard with this type of JST connector, and many of our boards include this connector (or a footprint for it) as a power supply input. It has the advantage of being compact, durable, and difficult to connect backwards. Another feature, which can be an advantage or a disadvantage, depending on how you look at it, is that the JST connector is wicked hard to disconnect (although a carefully applied diagonal cuttercan be helpful!) once it’s mated. While this makes it unlikely to fail during use, it also means that disconnecting the battery for charging can damage the battery connector.

2-Pin JST male connector on a LilyPad Arduino USB board

2-Pin JST male connector on a LilyPad Arduino USB board. Again, as with the Molex, the pins inside the hood determine the gender of the connector.

Male and female 2-pin JST connectors

Male and female 2-pin JST connectors.

There are PH series connectors with more than two positions; SparkFun even sells them. However, our most frequent application is for the 2-position battery connection.

Pin Header Connectors

Pin header connectors comprise several different means of connection. Generally, one side is a series of pins which are soldered to a PCB, and they can either be at a right-angle to the PCB surface (usually called “straight”) or parallel to the board’s surface (confusingly referred to as “right-angle” pins). Such connectors come in a variety of pitches, and may have any number of individual rows of pins.

Right angle female header pin connector

Right-angle female header pin connection on an FTDI basic board.

The most commonly seen pin headers are .1" single or double row connectors. These come in male and femaleversions, and are the connectors used to connect Arduino boards and shields together. Other pitches are not uncommon; for instance, the XBee wireless module uses a 2.0mm pitch version of the same connector.

.1" pin header connector examples

.1" pin header connectors, male and female, on an Arduino Uno board.

A common variation on this part is a “machine pin” version. While the normal version is formed out of stamped and folded sheet metal, machine pin connectors are formed by tooling the metal into the desired shape. The result is a more robust connector, with a better joint and longer life, making it somewhat more expensive.

Female machine pin headers

Female machine pin headers. Note that these are designed to be snapped apart into smaller sections, while standard .1" female header pin connectors are not. It’s also important to note that not all non-machine pin header connectors will mate with the machine pin variety.

Cables made to connect to these pin headers are usually one of two types: individual wires with crimp connectors on them or ribbon cables with insulation displacement connectors. These can simply be clamped onto the end of a ribbon cable, which creates a connection to each one of the conductors in the ribbon cable. Generally, cables are only available as female gender and expect a male pin to mate with.

Crimp connected header cable

Six-position crimp-type cable. Each wire is individually stripped, a connector crimped to it, and then the connectors are inserted into the plastic frame.

2x5 insulation displacement connectors on a ribbon cable

2x5 insulation displacement connectors (IDC) on a ribbon cable. This type of cable can be quickly assembled because it does not require stripping of individual connectors. It also has polarizing tabs on each end, to prevent incorrect insertion in the mating board-side connector.

Temporary connectors

Screw Terminals

In some cases, it may be desirable to be able to connect bare, unterminated wire to a circuit. Screw terminals provide a good solution for this. They are also good for situations in which a connection should be capable of supporting multiple different connecting devices.

The downside of screw terminals is that they can come undone fairly easily, leaving a bare wire waving around in your circuit. A small dab of hot glue can address this without being too difficult to remove later.

Screw terminals are typically designed for a narrow range of wire gauges, and wires that are too small can be as big a problem as wires that are too big. SparkFun carries two types of screw terminal–a .1" pitch version and a 3.5mm version. Most screw terminals are highly modular, and they can easily be extended at the same pitch by simply connecting two or more smaller sections together.

3.5mm screw terminals


-> 3.5mm pitch screw terminals, showing the insertion point of the wire to be connected, the retention screw which holds the wire in place, and the modular connectors on the sides of the individual units allowing multiple pieces to be ganged together. <-

Banana Connector

Most pieces of power test equipment (multimeters, power supplies) have a very simple connector called a “banana jack” on it. These mate to “banana plugs”, crimped, sprung metal plugs, meant to make a single power connection. They are frequently available in a stackable configuration and can be easily connected to any type of wire. They are capable of carrying several amps of current and are inexpensive.

Banana plug

Stackable banana plug. Note that there are two different ways to plug in an additional banana plug.

Variable power supply with banana plugs

Extech variable bench supply with banana jacks on the front.

Alligator Clip

Named for obvious reasons, alligator clips are good for test connections to posts or bare wires. They tend to be bulky, easily cause shorts to nearby bare metal, and have a reasonably poor grip that can be easily compromised. They are primarily used for low-cost connections during debugging.

Alligator clips

“third hand” tool, which uses alligator clips to hold work pieces, holding a wire terminated with an alligator clip for electrical test. Note the plastic boot surrounding the alligator clip, to make it less likely to short to other connections.

IC Clip (or IC Hook)

For more delicate probing operations, there are a variety of IC clips on the market. These are sized to allow a user to clip them onto the pins of an IC without contacting adjacent pins; some of them are delicate enough to be clipped onto even fine-pitched SMD component legs. These smaller clips can be found on logic analyzers as well as test leads, which are great for prototyping or troubleshooting circuits.

Large IC clip

large IC clip on the end of a wire. This clip is still small enough to be connected to a single leg on a through-hole chip without causing a problem for adjacent pins.

Other Connectors

RJ-type Modular Connectors

Registered jack connectors are standard for telecommunications equipment into a local exchange. The names one normally hears associated with them (RJ45, RJ12, etc) are not necessarily correct, as the RJ designator is a based on a combination of the number of positions, the number of conductors actually present, and the wiring pattern. For example, while the ends of a standard ethernet cable are usually referred to as “RJ45”, RJ45 actually implies not only an 8 position, 8 conductor modular jack, it also implies that it is wired for ethernet.

These modular connectors can be very useful, since they combine ready availability, multiple conductors, moderate flexibility, low cost, and moderate current carrying capacity. While not originally intended to deliver a great deal of power, these cables can be used to deliver data and a couple of hundred milliamps from one device to another. Care should be taken to ensure that jacks provided for applications like this are not connected to conventional ethernet ports, as damage will result.

8p8c "RJ45" style modular jack

A standard 8p8c (8-position, 8-conductor) “RJ45” modular jack. Be aware that if you intend to use this type of jack to pass DC signals and power, you must avoid using connectors with built-in signal transformers.

D-sub Type Connectors

Named for the shape of their shell, D-subminiature connectors are a classic standard in the computing world. There are four very common varieties of this connector: DA-15, DB-25, DE-15, and DE-9. The pin number indicates the number of connections provided, and the letter combination indicates the size of the shell. Thus, DE-15 and DE-9 have the same shell size, but a different number of connections.

Female board-mount DE9 connector

Female DE-9 board-mount connector. Gender is defined by the pins or sockets associated with each signal, not the connector as a whole, making this connector female despite the fact that it effectively inserts into the shell of the mating connector.

DB-25 and DE-9 are the most useful to the hardware hacker; many desktop computers still include at least one DE-9 serial port, and often one DB-25 parallel port. Cables terminated with DE-9 and DB-25 connectors are widely available, too. As with the modular connector above, these can be used to provide power and point-to-point communications between two devices. Again, since the common usage of these cables does not include power transmission, it is very important that any repurposing of the cables be done cautiously, as a non-standard device plugged into a standard port can easily cause damage.

Resources and Going Further

You should now have a good idea which connectors are suited best for certain applications and which connectors will be useful to you in your next project. Please check out these other links to lean more about connectors.

  • Giant database of connectors and pinouts - Everything you never wanted to know about pretty much any connector, ever. A good site for basic info about connectors, but often quite shy on interface details.
  • Wikipedia article on registered jack connectors - More on the confusing world of the registered jack (RJ) connector, which is often misunderstood and misused.
  • Wikipedia article on D-subminiature connectors - As with the registered jack connector, misinformation abounds on the D-subminiature standard. Wikipedia has a great article about it.
  • Mouser electronics catalog - Browsing an electronics supplier catalog is often a great place to start looking for the name of an unidentified connector; Mouser’s enhanced online catalog is just as good as the print version, with fewer papercuts!

If you’d like top explore more SparkFun tutorials, check out these other offerings:

 


cc

 Creative Commonstutorials are CC BY-SA 4.0

Original From:

https://learn.sparkfun.com/tutorials/connector-basics