Tuesday, July 19, 2011

Ultrasonic Position System

The ultrasonic position system uses ultrasonic transmitters/receivers to triangulate position of the robots used in GE423. Each of three transmitters uses a distinct frequencies: 23 kHz, 31 kHz, and 40 kHz. The 2812 DSP is used to measure signal timing and calculate position based on these values. The design of the electronics, as well as discussion of the software development is presented below.

The electronics were not intergrated with the 6713 DSP on the robot.
Note: To get around the issue of clock syncing, the robot will start in a known position, and calculate position for four cycles before proceeding. An alternative to this would be to add a fourth transmit frequency and use the 4th signal to sync the robot clock with the transmit clock.

1.0 Hardware

A wide variety of hardware was used for this project. The hardware was chosen based on availability and price. By no means is the solution presented "the best"or the only way to achieve the desired results, but it is a workable solution.

1.1 Ultrasonic Transmitters/Receivers

The ultrasonic sensor were purchased from Massa. The TR-89/B series where chosen because they come in 3 different frequencies, and they were stock parts. There is no pdf data sheet available on the Massa website, all information if available here. The main drawback of using Massa is there $500 minimum order, and the sensors aren't cheap at about ~$30 each.

1.2 Transmit Circuit

A schematic of the transmit circuit looks like:

Images of the perf-boarded transmit circuits:

Details on the components of the transmit circuit can be found in the subsection below:

1.2.1 Frequency Generation

The transmit circuit take from the Massa Website looks like:
Source:http://www.massa.com/datasheets/graphics/tr89_data.gif
Where R1 is a 10k 10 turn precision wound potentiometer, and U1 is a CD4039B NAND Schmitt Trigger. The tuning resistor R2 and L where left out to increase the transmit power around the base frequency. The potentiometer was adjusted until the frequency was the desired base frequency. A 1k resistor was added in parallel with the potentiometer to give a higher resolution. For the 40 kHz case, a smaller capacitor was required to reach the base frequency. Make sure to tune the circuit with the ultrasonic transducers attached, because the additional impedance will change the transmit frequency. The 12 Vdc was generated by a lab supply.
The output at point TP1, is a 12V peak to peak is a square wave at the desired frequency. The point TP1 was connected to the Driver Signal Circuit presented below.

1.2.2 555 Timer Circuit

The documentation for the 555 timer can be found here. An a picture of how it is wired can be 


 
seen below:
Source:http://www.williamson-labs.com/480_555.htm
Using the handy calculator for Ra, Rb, and C found here, Ra=100k ohm, Rb=200k ohm, and C=2.2 mircoF.

1.2.3 Driver Signal Circuit

The 35 Vdc supply is manufactured by Ultravolt, part number 1/4Aa24-P30. This supply is actually a 0-250 Vdc supply that uses a potentiometer to control voltage output.. The transistor used is an IRF520 n-channel MOSFET.

1.3 Receive Circuit

A block diagram of the receive circuit can be seen below:

And a picture of the perf-boarded receive circuit can be seen below:

Details on the components of the receive circuit can be found in the subsection below:


1.3.1 Low Signal Amp Circuit

An instrumentation amplifier made by Analog Devices was used to amplify the low signal output of the ultrasonic receivers. The actual part used was the AD620, one is recquired for each receive channel. Analog has a nice tool here, to size the gain resistor, Rg. Based on experiments, a gain value of 33 was chosen, resulting in a Rg of 1.5k ohm. The AD620 was wired as follows:
Source:http://www.analog.com/images/Product_Descriptions/3888333375812882340AD620_fbs.gif

1.3.2 Comparator Circuit

The analog comparitor used was part number LM339. The volatage divdier was powered using +5 Vdc to creat the digital level output signal. The output from each instrumentation amplifier was wired to the "+" terminal, and the "-" was wired to 3 volts. The 3 Vdc signal was created from the +15 Vdc supply using a voltage divider. The output of the comparitor was wired to a 5 Vdc via a 3k resistor.

2.0 Software

The timing of the hardware interrupts from the 2811 is calculated, and from the times, position is calculated in the 2D plane using a combination of least squared fit and Jacobian iteration.

2.1 Matlab Triangulation Code

The first algorithm was developed using Matlab. This code can be found here. The algorithm is not stable for all input parameters, a good set of test conditions are:
[x,y]=blah(.010,.012,.012)
[x,y]=blah(.009,.014,.012)
[x,y]=blah(.011,.011,.011)
Note the highly descriptive function named blah

2.2 DSP C Code

The c code for the 2812 DSP is in the attached zip file. The code works as following:
  1. Hardware interrupt pin get triggered
  2. Record absolute clock time when pin transition occurs
  3. Go back to step 1,and once all three pins have been triggered:
    1. (only do this step the first time through the code) Assume robot stationary, acquire base transmit period for each frequency by averaging first 4 values, this step syncs the clocks of the transmitters to the robot
    2. Calculate time from transmitter to robot for each frequency
    3. Triangulate position of robot using least squared fit to data points
    4. Wait for fixed amount of time, ignore hardware interrupts during this time because of the nature of the transmit signal
    5. Go back to Step 1

3.0 Lessons Learned

  1. A resistor was needed in parallel with the tuning potentiometer to give better resolution
  2. A resistor was required in parallel with the US transmitter for the circuit to function because the transmitter is like a capacitor.

4.0 Acknowledgments

Various people and online resources aided in this project:
  • GE423 Lab Instructor: Dan Block
  • GE423 TAs: Dave Johnson, Daniel Herring
  • My officemate: Steve Tschopp
  • Misc. Consultation: Tim Cargol
  • Misc Websites:
    • http://ourworld.compuserve.com/homepages/Bill_Bowden/555.htm
    • http://www.williamson-labs.com/480_555.htm
    • http://www.massa.com
    • http://www.digikey.com (source for datasheets)

Car Wireless Alarm Circuit Diagram

This FM radio-controlled anti- annexation anxiety can be acclimated with any agent accepting 6- to 12-volt DC accumulation system. The mini VHF, FM transmitter is adapted in the agent at night back it is anchored in the car balustrade or car park. The receiver assemblage with CXA1019, a distinct IC-based FM radio module, which is advisedly accessible in the bazaar at reasonable rate, is kept inside. Receiver is acquainted to the transmitter's frequency. Back the transmitter is on and the signals are actuality accustomed by FM radio receiver, no hissing babble is accessible at the achievement of receiver.


Appropriately transistor T2 (BC548) does not conduct. This after-effects in the broadcast disciplinarian transistor T3 accepting its advanced abject bent via 10k resistor R5 and the broadcast gets energised. Back an burglar tries to drive the car and takes it a few metres abroad from the car porch, the radio articulation amid the car (transmitter) and anxiety (receiver) is broken. As a aftereffect FM radio bore gene-rates hissing noise. Hissing AC signals are accompanying to broadcast switching circ- uit via audio transformer. These AC signals are rectified and filtered by diode D1 and capacitor C8, and the consistent absolute DC voltage provides a advanced bent to transistor T2.

Appropriately transistor T2 conducts, and it pulls the abject of broadcast disciplinarian transistor T3 to arena level. The broadcast appropriately gets de-activated and the anxiety affiliated via N/C contacts of broadcast is switched on. If, by chance, the burglar finds out about the wireless anxiety and disconnects the transmitter from battery, still alien anxiety charcoal activated because in the absence of signal, the receiver continues to aftermath hissing babble at its output. So the burglar anxiety is fool-proof and awful reliable.

Hot Water Level Indicator

Notes:
Save fuel bills and the economy of the planet with this circuit. SW1 is a normally open press button switch which allows you to view the level of hot water in a hot water tank. When pressed the voltage difference at the junction of the thermistor and preset is compared to the fixed voltage on the op-amps non-inverting input. Depending on the heat of the water in the tank, the thermistors resistance will toggle the op-amp output to swing to almost full voltage supply and light the appropriate LED.
Construction:
Masking tape was used to stick the bead thermistors to the tank. Wires were soldered and insulated at the thermistors ends. A plastic box was used to house the circuit. Battery life will probably be 4 to 5 years depending on how often you use the push switch, SW1.
Sensor Placement:
Thermistors NTC1-4 should be spread evenly over the height of the tank. I placed NTC1 roughly 4 inches from the top of my tank and the others were spaced evenly across the height of the hot water tank. As hot water rises the lowest sensor indicates the fullest height of hot water and should be about 8 to 10 inches from the bottom of the tank.
Calibration:
With a full tank of hot water adjust P1-4 so that all LED's are lit. As hot water rises, the sensor at the bottom of the tank will be the maximum level of hot water. "Hot" can be translated as 50C to 80C the presets P1-4 allow adjustment of this range.
Parts:
I have used a quad version of the LM324 but any quad opamp can be used or even four single op-amps.
R2-R5 I used 330ohm resistors, but value is not critical. Lower values give brighter LED output.
NTC1-4 The thermistors maximum resistance must roughly equal the resistance of the fixed resistor and preset. As negative temparature coefficient (NTC) thermistors are used, then their resistance decreases for increases in temperature. I used a thermistor from the Maplin Catalogue. Cold resistance was around 300K, hot resistance 15k. Alternative thermistors may be used with different resistance ranges, but the presets P1 to P4 must also be changed as well.
R7-10 series resistance, only required if your thermistors resistance is several ohms at the hottest temperature.
P1 - P4 Chosen to match the resistance of the thermistor when cold.
R1 & R6. These resistors are equal and bias the op-amp inverting input to half the supply voltage. I used 100k.

Water Level Indicator Alarm


This ambit not alone indicates the bulk of baptize present in the aerial catchbasin but additionally gives an anxiety back the catchbasin is full.
The ambit uses the broadly accessible CD4066, mutual about-face CMOS IC to announce the baptize akin through LEDs.
When the baptize is abandoned the affairs in the catchbasin are accessible circuited and the 180K resistors pulls the about-face low appropriately aperture the about-face and LEDs are OFF. As the baptize starts bushing up, aboriginal the wire in the catchbasin affiliated to S1 and the + accumulation are shorted by water. This closes the about-face S1 and turns the LED1 ON. As the baptize continues to ample the tank, the LEDs2 , 3 and 4 ablaze up gradually.
The no. of levels of adumbration can be added to 8 if 2 CD4066 ICs are acclimated in a agnate fashion.
When the baptize is full, the abject of the transistor BC148 is pulled aerial by the baptize and this saturates the transistor, axis the buzzer ON. The SPST about-face has to be opened to about-face the buzzer OFF.
Remember to about-face the about-face ON while pumping baptize contrarily the buzzer will not sound!

Sunday, March 27, 2011

Electronic mosquito repeller using CD4047


Description.
Here is the circuit diagram of an ultrasonic mosquito repeller.The circuit is based on the theory that insects like mosquito can be repelled by using sound frequencies in the ultrasonic (above 20KHz) range.The circuit is nothing but a PLL IC CMOS 4047 wired as an oscillator working at 22KHz.A complementary symmetry amplifier consisting of four transistor is used to amplify the sound.The piezo buzzer converts the output of amplifier to ultrasonic sound that can be heard by the insects.

Circuit diagram with Parts list.

Notes.
Assemble the circuit on a general purpose PCB.
The circuit can be powered from 12V DC.
The buzzer can be any general purpose piezo buzzer.
The IC1 must be mounted on a holder.

Electronic Mosquito Repeller Circuit


This circuit produces a tone above the human audible range and this is supposed to keep the mosquitoes away. You need a piezo diaphragm that will respond to 15kHz and these are very difficult to find. 

This electronic mosquito repellent schematic circuit diagram based on the 555 timer IC is a simple and useful mosquito repellent circuit . This mosquito repeller circuit generate an ultrasonic sound with a high output frequency that  allows spreading mosquitoes within a wide radius . The circuit is quite simple and require few external components . The oscillation frequency is given by the value of the R1, R2 and C1 components and can be modified changing the value of components or replacing the R2 fixed resistor with a variable resistor ( potentiometer ) .
The actual oscillation frequency of this electronic mosquito repeller circuit is around 45 KHz ( 46.5 KHz) so you need to use a good high frequency speaker , you can use a piezo speaker .

The circuit can be supplied from a 9 V DC power supply  . This repeller circuit can be used for almost any animal , it works on  : cats , dogs , rats  . Even if you don’t hear the sound generated by device don’t worry  because the high frequency is less audible by the human ear .

60W inverter using transistors


Description.
Here is the circuit diagram of a fully transistorized inverter that can drive up to 60W loads. Transistors Q1 and Q2 forms a 50Hz astable multivibrator. The output from the collector of Q2 is connected to the input of the Darlington pair formed by Q3 and Q4.Similarly the output of Q1 is coupled to the input of the pair Q5 and Q6. The output from the Darlington pairs drive the final output transistors Q7 and Q8 which are wired in the push pull configuration to drive the output transformer.
Circuit diagram.


Notes.
The circuit can be assembled on a vero board.
T1 can be a 230V primary to 9-0-9V, 6A secondary transformer.
Transistors Q4, Q6, Q7 and Q8 must be fitted with heat sinks.
Use a 12V, 7Ah battery for powering the inverter.
Slight adjustments can be made on the value of R3 and R4 to get exact 50Hz output.

Simple 100W inverter circuit


Description.
Here is the circuit diagram of a simple 100 watt inverter using IC CD4047 and MOSFET IRF540. The circuit is simple low cost and can be even assembled on a veroboard.

CD 4047 is a low power CMOS astable/monostable multivibrator IC. Here it is wired as an astable multivibrator producing two pulse  trains of 0.01s which are 180 degree out of phase at the pins 10 and 11 of the IC. Pin 10 is connected to the gate of Q1 and pin 11 is connected to the gate of Q2. Resistors R3 and R4 prevents the loading of the IC by the respective MOSFETs. When pin 10 is high Q1 conducts and  current flows through the upper half of the transformer primary which accounts for the positive half of the output AC voltage. When pin 11 is high Q2 conducts and  current flows through the lower half of the transformer primary in opposite direction and it accounts for the negative half of the output AC voltage.

Circuit diagram.
Notes.
B1 can be  a 12V/ 6Ah lead acid battery.
Q1 and Q2 must be fitted to a proper heat sink.
T1 can be a 9-0-9 V primary, 230V secondary, 150VA transformer .
Do not expect much from this circuit. The is very simple one suitable for low grade applications.

How to make an Inverter- Simple 40 Watt Inverter


How to make an Inverter

Description:This is the schematic of a simple 40W , 12 volts to 220 Volts inverter.You don’t believe, this is simple and cheap and working for me for last 4 years.The heart of the circuit is a CD 4047 IC which is wired as an astable multi vibrator here.Resistance and Capacitance at pin 1&2 determines the out put frequency.Here it is set to 60Hz.Due to this a two 180 degree out of phase ,120 Hz , 50% duty cycle waveforms will appear at pin 10 & 11.These waves are amplified by the complementary symmetry amplifier made of transistors BC 337 & TIP 3055 to drive the out put transformer.Don’t get feared of the technical terms, just wire it on a all purpose PCB.It is simple and will work.Don’t worry about the transformer windings ,buy a 220-110-0 primary,12-0-12 secondary , <50W transformer.You can select output voltage of 110V or 220V by a two way switch using such a transformer.Don’t worry if you don’t have such a transformer, a simple 220 to 12-0-12 will also do the trick sacrificing the 110V option or vice versa.The best way to get a transformer is to break all useless electronic devices in your trash.Most probably you will find the transformer or more components needed here!

Simple Inverter Circuit Diagram:


Tips First wire to oscillator part only.Then check out put Pin 10 &11 of CD4047 to obtain the required wave forms ( two 120Hz ,180 degree out of phase,50% duty cycle waves. Then connect transistors ,transformer and load (25 W bulb for test).See it working!.

555 Timer IC Pin configuration



The 555 Timer IC is available as an 8-pin metal can, an 8-pin mini DIP (dual-in-package) or a 14-pin DIP.
This IC consists of 23 transistors, 2 diodes and 16 resistors. The explanation of terminals coming out of the 555 timer IC is as follows. The pin number used in the following discussion refers to the 8-pin DIP and 8-pin metal can packages.



Pin 1Grounded Terminal. All the voltages are meas­ured with respect to this terminal.
Pin 2: Trigger Terminal. This pin is an inverting input to a comparator that is responsible for transition of flip-flop from set to reset. The output of the timer depends on the amplitude of the external trigger pulse applied to this pin.
Pin 3: Output Terminal. Output of the timer is avail­able at this pin. There are two ways in which a load can be connected to the output terminal either between pin 3 and ground pin (pin 1) or between pin 3 and supply pin (pin 8). The load connected between pin 3 and ground
supply pin is called the normally on load and that connected between pin 3 and ground pin is called the normally off load.
Pin 4: Reset Terminal. To disable or reset the timer a negative pulse is applied to this pin due to which it is referred to as reset terminal. When this pin is not to be used for reset purpose, it should be connected to + VCC to avoid any possibility of false triggering.
Pin 5: Control Voltage Terminal. The function of this terminal is to control the threshold and trigger levels. Thus either the external voltage or a pot connected to this pin determines the pulse width of the output waveform. The external voltage applied to this pin can also be used to modulate the output waveform. When this pin is not used, it should be connected to ground through a 0.01 micro Farad to avoid any noise problem.
Pin 6: Threshold Terminal. This is the non-inverting input terminal of comparator 1, which compares the voltage applied to the terminal with a reference voltage of 2/3 VCC. The amplitude of voltage applied to this terminal is responsible for the set state of flip-flop.
Pin 7 Discharge Terminal. This pin is connected internally to the collector of transistor and mostly a capacitor is connected between this terminal and ground. It is called discharge terminal because when transistor saturates, capacitor discharges through the transistor. When the transistor is cut-off, the capacitor charges at a rate determined by the external resistor and capacitor.
Pin 8: Supply Terminal. A supply voltage of + 5 V to + 18 V is applied to this terminal with respect to ground (pin 1).

555 Timer IC Working Principle

Block Diagram of 555 timer IC:

Comparator 1 has a threshold input (pin 6) and a control input (pin 5). In most applications, the control input is not used, so that the control voltage equals +2/3 VCC. Output of this comparator is applied to set (S) input of the flip-flop. Whenever the threshold voltage exceeds the control voltage, comparator 1 will set the flip-flop and its output is high. A high output from the flip-flop saturates the discharge transistor and discharge the capacitor connected externally to pin 7. The complementary signal out of the flip-flop goes to pin 3, the output. The output available at pin 3 is lowThese conditions will prevail until comparator 2 triggers the flip-flop. Even if the voltage at the threshold input falls below 2/3 VCC, that is comparator 1 cannot cause the flip-flop to change again. It means that the comparator 1 can only force the flip-flop’s output high.
To change the output of flip-flop to lowthe voltage at the trigger input must fall below + 1/3 Vcc. When this occurs, comparator 2 triggers the flip-flop, forcing its output lowThe low output from the flip-flop turns the discharge transistor off and forces the power amplifier to output a high. These conditions will continue independent of the voltage on the trigger input. Comparator 2 can only cause the flip-flop to output low.
From the above discussion it is concluded that for the having low output from the timer 555, the voltage on the threshold input must exceed the control voltage or + 2/3 VCC. They also turn the discharge transistor on. To force the output from the timer high, the voltage on the trigger input must drop below +1/3 VCC. This also turns the discharge transistor off.
A voltage may be applied to the control input to change the levels at which the switching occurs. When not in use, a 0.01 nano Farad capacitor should be connected between pin 5 and ground to prevent noise coupled onto this pin from causing false triggering.
Connecting the reset (pin 4) to a logic low will place a high on the output of flip-flop. The discharge transistor will go on and the power amplifier will output a low. This condition will continue until reset is taken high. This allows synchronization or resetting of the circuit’s operation. When not in use, reset should be tied to +VCC.

USB Battery Charger controller circuit using LM3622

From USB Battery Charger controller circuit using LM3622

Saturday, March 26, 2011

555 timer calculator (monostable and astable operation)

This 555 timer IC calculator can calculate frequency, duty cycle, and high and low output of timer IC operation on both monostable and Astable. This Calculator script was written by Robert Davis of Goldsmith College
555 timer IC
555 timer Pin number and designation:
pin 1- ground or common pin
pin 2- trigger pin
pin 3- output pin
pin 4- reset pin
pin 5- control pin
pin 6- threshold  pin
pin 7- discharge pin
pin 8- positive supply






555 MONOSTABLE OPERATION
Acts as one shot  pulse generator of output high duration of  T=RC ln(3)


555 timer monostable













R:


C:




T Output High (Seconds) =



555 TIMER ASTABLE OPERATION
555 timer astable operation


This operation has an output of continuous pulses of specified frequency and and duty-cycle.


R1:


R2:


C:








T1 Output High (Seconds) =


T2 Output Low (Seconds) =


T Total Period (Seconds) =


Frequency (Hz) =


Duty (%High) =

Simple LED Emergency Light Circuit


This LED emergency light project is simple, cheap and easy to build. The circuit do the charging of the battery and when the main source is not available such as in brownouts, the white LEDs automatically turn on. 
Initially, the voltage output  from 220V to 12V converter is fed to the input of LM317 regulator. Then this voltage is regulated down to 7.37V using 240 ohms and 1.2K resistor combination (see LM317 Calculator).
At this instant, the battery is in charging mode and the transistor Q1 is off. Indicator LED serves two purpose, one primarily is to give us idea that the battery is charging and another is to ensure that the Q1 is off.
During brownouts, the transistor Q1 is on and delivers current to 16 white LED of about 20mA each, thus a fully charged battery (6V/4.5Ah) can last up to 14 hours.

The charger has no built in over-current control but still it protects the battery from overcharging since the charging voltage is set only to 7.4V.


Project materials:
1pc - transformer - 220V to 12V-0-12V , center tap 12VA
16pc - 120 ohms resistor 1/4 W
16pc - white LED min 3V@30mA
1pc - red LED
1pc - 1000uF/25V electrolytic capacitor
3pc - 1N4001 diode
1pc - LM317 regulator
1pc - 1.5K resistor 1/4W
1pc - 240 ohms resistor 1/4W
1pc - 1.2k resistor 1/4W
1pc - 9012 pnp transistor or any of much higher capacity
1pc - 6V 4.5ah battery

Automatic LED Emergency Light



Description
This is the circuit diagram of a low cost emergency light based on white LED.The white LED provide very bright light which turns on when the mains supply is not there.The circuit has an automatic charger which stops charging when the battery is fully charged.

The IC LM 317 produces a regulated 7 V for the charging of Battery.Transistor BD 140 drives the out put.Transistor BC 548 and Zener diode controls the charging of the battery.

Tips
It is always better to connect a heat sink with BD 140.Before using the circuit out put of LM317 must be set to 7V by adjusting the potentiometer.

Wednesday, March 23, 2011

4069 Latching Relay Driver



Uses of Optoisolators

Consist of an LED (usually Infra-red) and a phototransistor close-coupled in a DIL IC package. Commonly used to isolate two sections of a circuit for safety reasons.

An example where you want to swap your case power or drive activity LED for something with a bit more bling, without endangering the motherboard. The optoisolator diode is connected in place of the case LED.




Non-Latching (Momentary) Switches.


The most common are push-button, but toggle switches too may be spring-loaded to return to one position after activating. In the catalogues, an (ON)-OFF description means it's only ON while you're holding the lever in place. With push-button, they're more often described as 'momentary-on' (push to make) or 'momentary-off' (push to break).

Here's how the two types could be used together to control ON-OFF action by latching a relay, a very common system on industrial control gear.

Relay Latching Circuit

The relay needs to have two or more poles (the switches) which can be change-over (double-throw) or single-throw types. 

The "On" switch S2 is a push-to-make (momentary on) type, and allows power through to the relay coil when pressed. This becomes an electro-magnet and pulls all the relay switches over to the 'no' (normally-open) position. (With relays, 'normally-open' and 'normally-closed' refer to the switch positions with no power applied to the coil.)

Relay switch Sw2 now keeps power running to the relay coil after the "On" button has been released, latching the relay into the 'on' position.

Relay switch Sw1 is used to switch power to whatever load you have attached, (Extra relay switches would be used, for example, to control a 3-phase electric motor.)

Pressing the "Off" button S1, a push-to-break (momentary off) type, breaks the power circuit, deactivating the relay electro-magnet and sending its switches back to the 'nc' (normally-closed) position.

The diode D1 gives an easy path to any voltage spike produced when the relay coil turns off (back-EMF) protecting any sensitive equipment on the same circuit.

8051 Tutorial Part-1 - Serial Communication


One of the 8051s many powerful features is its integrated UART, otherwise known as a serial port. The fact that the 8051 has an integrated serial port means that you may very easily read and write values to the serial port. If it were not for the integrated serial port, writing a byte to a serial line would be a rather tedious process requring turning on and off one of the I/O lines in rapid succession to properly "clock out" each individual bit, including start bits, stop bits, and parity bits.
However, we do not have to do this. Instead, we simply need to configure the serial ports operation mode and baud rate. Once configured, all we have to do is write to an SFR to write a value to the serial port or read the same SFR to read a value from the serial port. The 8051 will automatically let us know when it has finished sending the character we wrote and will also let us know whenever it has received a byte so that we can process it. We do not have to worry about transmission at the bit level--which saves us quite a bit of coding and processing time.

Setting the Serial Port Mode
The first thing we must do when using the 8051s integrated serial port is, obviously, configure it. This lets us tell the 8051 how many data bits we want, the baud rate we will be using, and how the baud rate will be determined.
First, lets present the "Serial Control" (SCON) SFR and define what each bit of the SFR represents:

    BitNameBit AddresExplanation of Function
    7SM09FhSerial port mode bit 0
    6SM19EhSerial port mode bit 1.
    5SM29DhMutliprocessor Communications Enable (explained later)
    4REN9ChReceiver Enable. This bit must be set in order to receive characters.
    3TB89BhTransmit bit 8. The 9th bit to transmit in mode 2 and 3.
    2RB89AhReceive bit 8. The 9th bit received in mode 2 and 3.
    1TI99hTransmit Flag. Set when a byte has been completely transmitted.
    0RI98hReceive Flag. Set when a byte has been completely received.
Additionally, it is necessary to define the function of SM0 and SM1 by an additional table:

    SM0SM1Serial ModeExplanationBaud Rate
    0008-bit Shift RegisterOscillator / 12
    0118-bit UARTSet by Timer 1 (*)
    1029-bit UARTOscillator / 64 (*)
    1139-bit UARTSet by Timer 1 (*)
(*) Note: The baud rate indicated in this table is doubled if PCON.7 (SMOD) is set.
The SCON SFR allows us to configure the Serial Port. Thus, well go through each bit and review its function.
The first four bits (bits 4 through 7) are configuration bits.
Bits SM0 and SM1 let us set the serial mode to a value between 0 and 3, inclusive. The four modes are defined in the chart immediately above. As you can see, selecting the Serial Mode selects the mode of operation (8-bit/9-bit, UART or Shift Register) and also determines how the baud rate will be calculated. In modes 0 and 2 the baud rate is fixed based on the oscillators frequency. In modes 1 and 3 the baud rate is variable based on how often Timer 1 overflows. Well talk more about the various Serial Modes in a moment.
The next bit, SM2, is a flag for "Multiprocessor communication." Generally, whenever a byte has been received the 8051 will set the "RI" (Receive Interrupt) flag. This lets the program know that a byte has been received and that it needs to be processed. However, when SM2 is set the "RI" flag will only be triggered if the 9th bit received was a "1". That is to say, if SM2 is set and a byte is received whose 9th bit is clear, the RI flag will never be set. This can be useful in certain advanced serial applications. For now it is safe to say that you will almost always want to clear this bit so that the flag is set upon reception of any character.
The next bit, REN, is "Receiver Enable." This bit is very straightforward: If you want to receive data via the serial port, set this bit. You will almost always want to set this bit.
The last four bits (bits 0 through 3) are operational bits. They are used when actually sending and receiving data--they are not used to configure the serial port.
The TB8 bit is used in modes 2 and 3. In modes 2 and 3, a total of nine data bits are transmitted. The first 8 data bits are the 8 bits of the main value, and the ninth bit is taken from TB8. If TB8 is set and a value is written to the serial port, the datas bits will be written to the serial line followed by a "set" ninth bit. If TB8 is clear the ninth bit will be "clear."
The RB8 also operates in modes 2 and 3 and functions essentially the same way as TB8, but on the reception side. When a byte is received in modes 2 or 3, a total of nine bits are received. In this case, the first eight bits received are the data of the serial byte received and the value of the ninth bit received will be placed in RB8.
TI means "Transmit Interrupt." When a program writes a value to the serial port, a certain amount of time will pass before the individual bits of the byte are "clocked out" the serial port. If the program were to write another byte to the serial port before the first byte was completely output, the data being sent would be garbled. Thus, the 8051 lets the program know that it has "clocked out" the last byte by setting the TI bit. When the TI bit is set, the program may assume that the serial port is "free" and ready to send the next byte.
Finally, the RI bit means "Receive Interrupt." It funcions similarly to the "TI" bit, but it indicates that a byte has been received. That is to say, whenever the 8051 has received a complete byte it will trigger the RI bit to let the program know that it needs to read the value quickly, before another byte is read.

Setting the Serial Port Baud Rate
Once the Serial Port Mode has been configured, as explained above, the program must configure the serial ports baud rate. This only applies to Serial Port modes 1 and 3. The Baud Rate is determined based on the oscillators frequency when in mode 0 and 2. In mode 0, the baud rate is always the oscillator frequency divided by 12. This means if youre crystal is 11.059Mhz, mode 0 baud rate will always be 921,583 baud. In mode 2 the baud rate is always the oscillator frequency divided by 64, so a 11.059Mhz crystal speed will yield a baud rate of 172,797.
In modes 1 and 3, the baud rate is determined by how frequently timer 1 overflows. The more frequently timer 1 overflows, the higher the baud rate. There are many ways one can cause timer 1 to overflow at a rate that determines a baud rate, but the most common method is to put timer 1 in 8-bit auto-reload mode (timer mode 2) and set a reload value (TH1) that causes Timer 1 to overflow at a frequency appropriate to generate a baud rate.
To determine the value that must be placed in TH1 to generate a given baud rate, we may use the following equation (assuming PCON.7 is clear).

    TH1 = 256 - ((Crystal / 384) / Baud)
If PCON.7 is set then the baud rate is effectively doubled, thus the equation becomes:

    TH1 = 256 - ((Crystal / 192) / Baud)
For example, if we have an 11.059Mhz crystal and we want to configure the serial port to 19,200 baud we try plugging it in the first equation:

    TH1 = 256 - ((Crystal / 384) / Baud)
    TH1 = 256 - ((11059000 / 384) / 19200 )
    TH1 = 256 - ((28,799) / 19200)
    TH1 = 256 - 1.5 = 254.5
As you can see, to obtain 19,200 baud on a 11.059Mhz crystal wed have to set TH1 to 254.5. If we set it to 254 we will have achieved 14,400 baud and if we set it to 255 we will have achieved 28,800 baud. Thus were stuck...
But not quite... to achieve 19,200 baud we simply need to set PCON.7 (SMOD). When we do this we double the baud rate and utilize the second equation mentioned above. Thus we have:

    TH1 = 256 - ((Crystal / 192) / Baud)
    TH1 = 256 - ((11059000 / 192) / 19200)
    TH1 = 256 - ((57699) / 19200)
    TH1 = 256 - 3 = 253
Here we are able to calculate a nice, even TH1 value. Therefore, to obtain 19,200 baud with an 11.059MHz crystal we must:

    1. Configure Serial Port mode 1 or 3.
    2. Configure Timer 1 to timer mode 2 (8-bit auto-reload).
    3. Set TH1 to 253 to reflect the correct frequency for 19,200 baud.
    4. Set PCON.7 (SMOD) to double the baud rate.
Writing to the Serial Port
Once the Serial Port has been propertly configured as explained above, the serial port is ready to be used to send data and receive data. If you thought that configuring the serial port was simple, using the serial port will be a breeze.
To write a byte to the serial port one must simply write the value to the SBUF (99h) SFR. For example, if you wanted to send the letter "A" to the serial port, it could be accomplished as easily as:

    MOV SBUF,#A
Upon execution of the above instruction the 8051 will begin transmitting the character via the serial port. Obviously transmission is not instantaneous--it takes a measureable amount of time to transmit. And since the 8051 does not have a serial output buffer we need to be sure that a character is completely transmitted before we try to transmit the next character.
The 8051 lets us know when it is done transmitting a character by setting the TI bit in SCON. When this bit is set we know that the last character has been transmitted and that we may send the next character, if any. Consider the following code segment:

    CLR TI ;Be sure the bit is initially clear
    MOV SBUF,#A ;Send the letter A to the serial port
    JNB TI,$ ;Pause until the TI bit is set.
The above three instructions will successfully transmit a character and wait for the TI bit to be set before continuing. The last instruction says "Jump if the TI bit is not set to $"--$, in most assemblers, means "the same address of the current instruction." Thus the 8051 will pause on the JNB instruction until the TI bit is set by the 8051 upon successful transmission of the character.

Reading the Serial Port
Reading data received by the serial port is equally easy. To read a byte from the serial port one just needs to read the value stored in the SBUF(99h) SFR after the 8051 has automatically set the RI flag in SCON.
For example, if your program wants to wait for a character to be received and subsequently read it into the Accumulator, the following code segment may be used:

    JNB RI,$ ;Wait for the 8051 to set the RI flag
    MOV A,SBUF ;Read the character from the serial port
The first line of the above code segment waits for the 8051 to set the RI flag; again, the 8051 sets the RI flag automatically when it receives a character via the serial port. So as long as the bit is not set the program repeats the "JNB" instruction continuously.
Once the RI bit is set upon character reception the above condition automatically fails and program flow falls through to the "MOV" instruction which reads the value.