You are on page 1of 34

Sensors,

Signals,
Serial ports, and
Sockets
Or, How to Build a Linux-Based Robot
Without Going Crazy

Topics
Signals from sensors: key terms
UART
Serial port
TTL
USB
I2C
RS232

pySerial API

Topics
Message types:
Raw / binary / hex
Custom text
NMEA

Sockets: client / server


Conguring an ad-hoc wireless network
DHCP
ifcong / iwcong

Signals from Sensors


Sensors output data serially (one bit at a
Tme)
Computers process data in parallel (one
byte or word or more at a Tme)
UART: Universal Asynchronous Receiver /
TransmiVer : device on your computer that
converts serial i/o to parallel format usable
internally.

Serial Issues
BAUD rate: symbols/pulses per second
Typically treated as bits per second (bps),
but not necessarily the same
Usually have to specify for each device
(sensor)
Standard / common values are
4800, 9600, 19200,
38400, 57600,
mile Baudot
115200
hVp://www.z-ix.com/wp-content/uploads/2013/02/SerialCommunicaTon.png

(1845-1903)

Serial Issues
hVp://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmiVer

Byte size (almost always eight)


Parity bit: Final data bit can be opTonally
used as an error check
Stop bit(s): signals
end-of-byte:
typically, one bit
hVp://en.wikipedia.org/wiki/Parity_bit

Serial Port
Ambiguous usage: can refer to
DE-9 (DB-9) connector on the back of
an older PC / laptop:

Serial Port
Ambiguous usage: can refer to
DE-9 (DB-9) connector on the back of
an older PC / laptop:

The representaTon of such a device by


the operaTng system ...

Serial Ports on Popular OSs

Serial Ports on Popular OSs

Serial Ports on Popular OSs

Serial Signal Types: TTL (1961)


Transistor-Transistor Logic: internal signal in computer
Simple logic/voltage relaTonship: 0v = False;
+3v to +5v = True
Mostly seen in UARTs on microcontrollers & other
special-purpose devices
Power
Transmit (TX) out of USB
Ground

hVp://www.adafruit.com/products/954?gclid=CMaplr7Q_7YCFQsy4AodBEcAYQ

Receive (RX) into USB

Serial Signal Types: RS-232 (1962)


Most common PC UART signal for decades
Higher voltage range (+/-13v) gives greater robustness
than TTL
NegaTve voltage = True; PosiTve = False

hVp://www.usconverters.com/index.php?main_page=page&id=61&chapter=0

hVps://www.sparkfun.com/tutorials/215

2
Serial Signal Types: I C (1982)
Inter-Integrated Circuit
From Philips; developed as SMBus by Intel
Popular on robot sensors
Allows several "slave" (sensor) devices to be accessed by
same "master" (computer) via port (/dev/i2c-0) and
addresses (0x10, 0x12, ...)
Data (SDA) and clock (SCL) lines instead of TX and RX
AcTve state is 0v, so need a +5v source plus "pullup
resistors" to maintain idle state

hVp://en.wikipedia.org/wiki/File:I2C_data_transfer.svg

hVp://wiki.bozemanmakers.com/index.php/I2c

Serial Signal Types: USB (1995)


Universal Serial Bus: vast majority of modern devices
Variety of connector types
Standard / Mini / Micro
A (host/master) B (peripheral/slave)
OTG: "On The Go": Accepts A (make me a host) or B (make
me a peripheral)

Onen used as power source / charger


Some sensors are USB-
ready, but for many we
need an adapter.
hVp://en.wikipedia.org/wiki/Usb

Favorite USB adapters

FTDI USB standard-A / RS232 DB-9


(DigiKey, Amazon)

Devantech USB standard-B to I2C


(Acroname)

"FTDI Friend" USB mini-B /


RS232 header pins
(AdaFruit)

I like these adapters because the


drivers for them are already installed
(Linux, OS X) or are downloaded
automaTcally when you plug in the
adapter (Windows).

pySerial API
hVp://pyserial.sourceforge.net/pyserial_api.html
Simple, powerful interface to serial port:

Serial() constructor
read()
write()
close()

Basic steps:

Google the specs for your device or adapter


Download the device driver from the manufacturer's
website (onen not necessary)
Plug in the device and nd its com-port
Start coding!

pySerial Example:
TruPulse 360 Laser Rangender

hVp://soluTons.seilerinst.com/Portals/1/Mapping%20PDFs/TruPulse_360-B_Users_Manual_2nd_EdiTon_Englis

# trupulse.py
import serial
import sys
DEVICE = '/dev/tty.usbserial-FTGNM22Z'

# or /dev/ttyUSB0 or COM9, etc.

device = serial.Serial(DEVICE, 4800)


while True:
c = device.read(1) # read one byte
sys.stdout.write(c) # print the byte as an ASCII character, no spaces
device.close()

Data Formats
ASCII
NMEA (or other industry standard)
Plasorm-specic

Binary
Images
Sounds
Numbers

import serial
import sys

Handling Binary Data

DEVICE = '/dev/tty.usbserial-FTGNM22Z'
device = serial.Serial(DEVICE, 38400)
while True:
c = device.read(1)
sys.stdout.write('0X%02X\n' % ord(c)) # Output as two-digit hexadecimal
device.close()

Binary Data: Byte Order


Typically, LSB: Less (Least) Signicant Byte rst
So if we're reading two-byte words:
0X00
0XE2
0X58
0XFE
...

0XE200
0xFE58
...

Then interpret words according to standard in docs


(two's complement xed-point, IEEE754 oat, ...)

Sockets
Socket: a mechanism allowing a process (execuTng
program) can talk to other processes on the same
computer or across the planet
A "low-level network interface"; i.e., what
underpins the internet!
Standard is Berkeley (BSD) Sockets
Client/server model
Server listens at a specied address on a specied port
Client connects to the socket at that address/port

# server.py
import socket
HOST = '137.113.118.74'
PORT = 20000

# dijkstra.cs.wlu.edu
# Low numbers are reserved for SSH, HTTP, SQL, et al.

sock = socket.socket()
try:
sock.bind((HOST, PORT)) # Note tuple!
except socket.error, msg:
print('bind() failed with code ' + str(msg[0]) + ': ' + msg[1])
sock.listen(1)

# handle up to 1 back-logged connection

client, address = sock.accept()


print('Accepted connection')
while True:
try:
msg = raw_input('> ')
if len(msg) < 1:
break
client.send(msg)
except:
print('Failed to transmit')
break
client.close()
sock.close

# client.py
import socket
HOST = '137.113.118.74'
PORT = 20000
sock = socket.socket()
try:
sock.connect((HOST, PORT)) # Note tuple!
except socket.error, msg:
print('connect() failed with code ' + str(msg[0]) + ': ' + msg[1])
while True:
try:
msg = sock.recv(80) # Maximum number of bytes we expect
if len(msg) < 1:
break
print(msg)
except:
print('Failed to receive')
break
sock.close()

CreaTng an Ad-Hoc WiFi


Network:
The Easy Way

CreaTng an Ad-Hoc WiFi Network,


The Hard Way
As root, do the following (e.g. by puvng sudo
in front of each command):

1. Set up the network

ifconfig
ifconfig
iwconfig
ifconfig

wlan0
wlan0
wlan0
wlan0

down # could be wlan1


address 192.168.2.2 netmask 255.255.255.0
mode ad-hoc essid my-ad-hoc-network
up

CreaTng an Ad-Hoc WiFi Network:


The Hard Way
2. Create or edit /etc/udhcpd.conf to contain:
start
end
interface
max_leases

192.168.2.3
192.168.2.254
wlan0
64

3. Create the leases le:


touch /var/lib/misc/udhcpd.leases
4. Run the dhcp server:
udhcpd /etc/udhcpd.conf

Puvng It All Together


Sensor

USB Adapter

Server

Client

You might also like