Saturday, May 18, 2013

Voltage Scaler (Voltage Divider)

Introduction

Sometimes you need to quickly and easily scale a voltage down to another voltage, within a circuit.

There's a two component circuit which can take in any voltage as its input, and have an exact percentage of that voltage as its output. If the input voltage doubles or triples, the output voltage doubles or triples as well.

Note: 1. This can only scale a voltage down, it can never scale up to voltage higher than its input. 2. The output will be much lower current than what is supplied to the input (Only low milli amps).

Applications

Some examples of situations where you'd need a voltage divider:
  1. Voltage from a 0-32 Volt sensor is too high for a 5 Volt micro-controller or a common 20 Volt meter to read without being damaged.
  2. A 12 Volt power supply is too high a voltage to power a 5 volt Micro-Controller, a sensor or an LED.

The circuit

Ingredients:
2 x Resistors (Any wattage, Resistance values determined by formula below).

Strange as it sounds, you really do only need two resistors. That's the easy part, the slightly difficult part is the calculation of their values (If you've used fractions, its easy as!).

Diagram:



OutputV = InputV/(R1Ohms+R2Ohms)*R2Ohms

Commonly Needed Combinations

For upto 32 volts input, scaled to 5 volts output: Scale 32 volts down to 15.625% (1/6.4).
 - R1=640 Ohms, R2=100Ohms. Are close enough.


For upto 5 volts input, scaled to 3.3 volts output: Scale 5 volts down to 66% (3/2).
 - R1=8.2K Ohms, R2=5.6K Ohms. Are close enough.



VBS Tricks (.vbs Script)

Introduction

These are some of my favourite .vbs scripts in existence. VisualBasic Scripts (.vbs files) can be written in notepad , just like batch files, but they have significant control over everything in a PC. As much control as a complete PC program - but without any fuss, and they can be run on PC's you have no administrator rights on. The only trade off i've found is that for every vbs script you run, there will be a copy of wscript.exe running in the 'Processes' tab of Task Manager. That's a pain if you're trying to be incognito.

What you'll need:
 - A PC with Windows XP/Vista/7 - that's it! this'll already have notepad on it - and that's all you'll need.

To run the script specified, do this:
  1. Copy the code given into a notepad file, then save the file as anything.vbs (Make sure you have '*.* All files' selected, otherwise the resulting file will be anything.vbs.txt).
  2. Double-Click the file you just made or,
  3. Create a batch file with the line 'start anything.vbs' in it, then run the batch file.

Terminate a running process/program

Change 'notepad.exe' in the line that says strProcessToKill = "notepad.exe"  to the name of the process you want to terminate. Tis will terminate all occurences of that .exe which are running at the time. Like a quick version of Task Manager - handy for software developers. To find the .exe program name of the process you want to terminate:
  1. Press Ctrl+Alt+Del, 
  2. Click Task Manager,
  3. In Task Manager, Click the tab called 'Processes'.
  4. Find the name of your process in the 'Description' column,
  5. Find its equivalent in the 'Image Name' column (This will end with '.exe').
'Terminate all processes involving the name <strProcessToKill>
Option Explicit
Dim strComputer,strProcessToKill, objWMIService, colProcess, objProcess
strComputer = "."
strProcessToKill = "notepad.exe"
Set objWMIService = GetObject("winmgmts:" _
   & "{impersonationLevel=impersonate}!\\" _
   & strComputer _
   & "\root\cimv2")
Set colProcess =
objWMIService.ExecQuery _
   ("Select * from Win32_Process Where
Name = '" & strProcessToKill & "'")
For Each objProcess in
colProcess
   msgbox "... terminating " &
objProcess.Name
   objProcess.Terminate()
Next

PC Speaking text

Displays a message box on the screen, where the user has to type in some text to be spoken. Only works on Windows PC's (They all contain Sound API which is used for this).

    Dim msg, sapi
    msg=InputBox("Enter your text for conversion:","Text-To-Speech Converter")
    Set sapi=CreateObject("sapi.spvoice")
    sapi.Speak msg

Run a Batch (.bat) file, with no command prompt window

This runs the batch file called 'testfile.bat', from the same folder as where this code is run.

    CreateObject("Wscript.Shell").Run "testfile.bat", 0, False

Run a Batch (.bat) file, with no command prompt window - drag n drop

This runs a batchfile, when you drag the batch file onto the vbs file which contains this code.


    CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False

Saturday, January 19, 2013

Delphi String Parsing Functions

Intro

To 'parse' a string of characters, is to filter it in some programmatic way, which allows you to get a piece or pieces of useful data from that string. 

Most of the time i create (and re-create) programming functions which allow me to parse HTML code from websites, after all HTML code is just one long string of characters. The kind of data you can extract is anything you'd find in an HTML webpage: E.g. Image links & Text values (Think ebay prices, tables, articles, javascript/css links etc).

Seeing as my memory is terrible, i have a bad habit of re-creating code, instead of just re-using what i have previously created. This post will serve not only as a tutorial for those of you who need to use these functions, but also as code documentation for my own future reference. I hope it is easy enough to understand :)

Necessary Functions

Example case of finding substringwewant within MainString:

MainString = Now is the winter of our discontent.
StringA = the
StringB = our
substringwewant = winter of

All string parsing functions rely on being able to find a substringwewant of characters within a larger, MainString of characters. Before that can be done, they rely on finding two substrings within a main string. StringA, a sequence of characters immediately before the substringwewant  and StringB, a sequence of characters immediately after the substringwewant  Once StringA & StringB are located, it is reasonably straight forward to extract the text between them, using existing programming functions (Copy(),Pos() & PosEX()). This is done in stages:
  1. Locate StringA, within the MainString: The Pos() function is perfect for this, it takes two parameters (String A, Main String) and gives us the index of String A within the main string. The function would be written like this: Pos(StringA,MainString);.
  2. Locate StringB, within the MainString (Search only characters after StringA s position): The PosEx() function is perfect for this, even more so than regular Pos(). The reason why, is that PosEx() takes a third parameter - an offset parameter, which tells the function to start looking for String B only after a certain number of characters into the main string. In this case, we want PosEx() to only look for StringB, AFTER the location of StringA. Doing this offset search has the following benefits, it: a) saves doubling up checks on the characters before StringA and the search is therefore much faster, and b) Makes sure you only find the single occurence of StringB immediately after StringA, and not another, random occurence of StringB).
  3. Get the length of StringA: This is done simply by putting StringA into a function called Length(StringA), which returns a number indicating StringA's length.
  4. Get the characters between StringA & StringB: The function called Copy() is what we will use for this (As well as the information gathered in the previous steps). Copy() returns text from within MainString, after it takes three parameters: MainString,Index,Count. Where: 
    1. Index = 1 + the location of the last character in StringA = 1 + Length(StringA).
    2. Count = StringBlocation - Index.
Ahh! So much complexity, for what seemed like such a straightforward task - getting a substring from within a main string. Unfortunately all of these steps are necessary, just to extract one substring from a mainstring. If you have to programmatically extract tens or hundreds of substrings from a mainstring, this process very soon becomes very boring which makes it easy to stuff up. I've done it hundreds of times AND stuffed up heaps along the way. I decided to pile all this into one programming function (CopyBetween()) which takes four parameters - and does the lot!

Get text between two strings (CopyBetween())

CopyBetween() returns the string between StringA and StringB after it takes four parameters: FirstString (StringA), SecondString (StringB), SourceString (MainString) and Offset (The number of characters at the start of MainString to ignore in the searches).

Uses
  StrUtils; //Neccessary for Pos() and PosEx() functions.


function CopyBetween(FirstString: String; SecondString: String; SourceString: String; Offset: Integer = 1): String;
var
  FirstStringLength,index1,index2:Integer;
begin
  // Store the length of the prefix text (FirstString).
  FirstStringLength := Length(FirstString);
  // Store the location of the prefix text (FirstString).
  index1 := PosEx(FirstString, SourceString, Offset);
  // Store the location of the suffix text (SecondString).
  index2 := PosEx(SecondString, SourceString, index1+FirstStringLength);
  // Return the text between the two strings.
  Result := Copy(SourceString,index1+FirstStringLength,index2-(index1+FirstStringLength));
end;

Copy the above function into your code somewhere, and put the Windows & StrUtils declaration in your uses section (At the top your code) or download the source code file at the bottom of this page.

Find out if strings occur in the correct order (IsInOrder())

Sometimes, before you can go ahead and get text from between two strings, you have to know if both strings occur in the order expected, E.g: StringA occurring before StringB, and not after string StringB.
Here is a function which returns true, if the strings occur in order, or false, if the strings do not occur in order.
It takes four parameters: OccursFirst (StringA), OccursSecond (StringB), SourceString (MainString) & Offset (The number of characters at the start of MainString to ignore in the searche).

Uses
  StrUtils; //Neccessary for Pos() and PosEx() functions.


function IsInOrder(OccursFirst: String; OccursSecond: String; SourceString: String; Offset: Integer = 1): Bool;
var
  index1,index2: Integer;
begin
  // Store the location of the first string text.
  index1 := PosEx(OccursFirst,SourceString,Offset);
  // Store the location of the second string text.
  index2 := PosEx(OccursSecond,SourceString,Offset);

  // If the second string is after the first string,
  if(index2 > index1)then
  begin
    // Return true.
    Result := True;
  end
  // Otherwise,
  else
  begin
    // Return false.
    Result := False;
  end;
end;

Copy the above function into your code somewhere, and put the Windows & StrUtils declaration in your uses section (At the top your code) or download the source code file at the bottom of this page..

Source code file (DParseUtils.pas):
 - http://www.filehosting.org/file/details/413075/DParseUtils.pas

Any suggested modifications, edits, additions or constructive criticism welcome in the comments section below :)




Sunday, October 21, 2012

LEDs and their Alter-Egos

What we know already

LED (Light Emitting Diodes) emit light when current is passed through them. They only conduct current in one direction (Like diodes). If you hook up positive and negative to them backwards, they won't conduct enough current to glow and they won't burn out either.

Some fun first off

Multi-meters can power LEDs! 
Theory first:
  1. LEDs are silicon based devices, as such need to have a minimum voltage put into them first (Usually about 0.6 Volt), before they'll conduct current and start to glow.
  2. Multi-meters can test diodes/LEDs resistance by putting out a voltage (Through the meter probes) into the LED/diode, causing the LED/diode to turn on and conduct current.
  3. In the case of a diode, this just means you can measure its electrical resistance, and therefore know if it works.
  4. In the case of LEDs, however, this will cause the LED to emit light.
How to do it:
  1. Any meter which has a diode range can do this. The diode range is just a picture of a diode (Image above). Find the option on your multi-meter, and select it.
  2. Get an LED (Any colour, any size, two wire, preferably not a special flashing one),
  3. Separate the LED wires a little,
  4. Put your meter probes on the LED wires (In my experience: Connect the red positive probe to the wire going to the LEDs smallest internal electrode, and the black negative probe to the wire going to the LED's largest internal electrode). Note: If you get the wires the wrong way around, just swap them back. The LED doesn't suffer any damage from having the wrong polarity of wires applied to it.
  5. Tah-dah! The LED now lives up to its name and emits light! :D 
Remember this little test in the future, its a great way to test an LED's: 1. Alive/Dead state, 2. Colour, and 3. Whether it's a special flashing LED.


An LED's Alter-Ego

LED's not only emit light, when current is passed through them. They also emit voltage when light is passed into them. To test this, we do something similar to the above process, with a few exceptions.
Theory first:
  1. LED's emit voltage proportional to the strength of the light - the stronger the light, the higher the voltage. Note: The current you'd get from LED's emitted voltage would be VERY small, so you cannot power anything big, directly. Rather, use a transistor amplifier stage or the analogue input of a micro-controller (Arduino, Parrallax, Propeller etc) - as any of these use very little current to turn on.
  2. When obtaining electricity from an LED, as compared with putting voltage in, there is no minimum light threshold before voltage will be emitted - the smallest amount of light will emit the smallest voltage.
How to do it:
  1. Any meter which has a DC volt range is what we want. I'd recommend the 20v range - as the output from the LED will be 1.5-ish volts (1500mv-ish). Find the option on your multi-meter, and select it.
  2. Get an LED (Any colour, any size, two wire, preferably not a special flashing one),
  3. Separate the LED wires a little,
  4. Put your meter probes on the LED wires (In my experience: Connect the red positive probe to the wire going to the LEDs smallest internal electrode, and the black negative probe to the wire going to the LED's largest internal electrode). 
  5. Point the LED toward a light source and tah-dah again! You should now be getting some voltage readings. Clouded sky = about 1.6v, Dim lit loungeroom = 1.4v, Sunny sky = UNTESTED.
Note: If you get the wires the wrong way around, in this case, the test will work just the same, except your meter will tell you its backwards - no harm done.

I find its always great fun to discover somethings hidden functionality. Especially when it's something as common as an LED.

Applications for LED Alter-Ego

  1. Sun tracking circuit: Using two LEDs to signal servos and their transistors to point a solar collecting device toward the sun.
  2. Dark room, got lit alarm: Use one LED's emitted voltage to set off a light/siren (Via a transistor amplifier first, ofcourse) when someone enters a room, and turns on a light.

If you think of some extra applications for this ability - let me know in the comments section below :)