Go Down

Topic: Gator/Arduino Compatible PLC (Part I) (Programmabl (Read 11 times) previous topic - next topic


Mar 12, 2010, 09:47 pm Last Edit: Mar 12, 2010, 10:15 pm by ArduinoAndy Reason: 1
Being in the electronics controls industry for over 30 years, I can answer this one.

A Programmable Logic Controller (PLC) has four major units ...

#1. Central processing unit (CPU) -- microprocessor, memory and power supply.
#2. Programmer/Monitor
#3. I/O modules (input and output modules) (in most cases isolated)
#4. Racks and Chassis.

This PLC defination was made before the use of microcontrollers came to the market.

To qualify as a PLC does not require the use of RLL - Relay Ladder Logic.
Modern PLC systems use flowcharts and or a combination of the IEC-1131 programming languages.

8-) 8-) 8-)
"Never trust an Internet bully who insults and makes fun of your level of intelligence."


Even so, I think it would be cool to have ladder logic in there somewhere; it would probably have to be as a front-end preprocessor to the C code. While I realize that the Arduino and C can do everything and more that ladder-logic can, the fact that it is old-school, and there are a number of people who understand it still around, might make it useful in something like this; if a front-end pre-processor was available, then they could code and use that to translate over to AVR C...

I will not respond to Arduino help PM's from random forum users; if you have such a question, start a new topic thread.


The only decent RLL control language translation, I have seen, were done on a 8051 microcontroller, which has Boolean hardware instructions. The AVR Arduino has none.
:( :( :(  
"Never trust an Internet bully who insults and makes fun of your level of intelligence."


A modern PLC is best used with Strutured Text, one of the IEC1131 languages. And thats very close to the Arduino, I have transalated some of my ST libs to the Arduino and it wasn't hard at all.

In my opinion, ladder is gone. No kids want to learn it any more. Its just nostalgia for us oldies.

My suggestion is to create the PLC shield with 24VDC digital IO:s, 4-20mA analog IO:s and keep the programming as an Arduino.


I will agree with you on keeping the programming on the Arduino.

As for building a PLC shield, with mechanical and solid state relays switching AC and DC would be a definate design flaw. The switching noise will kill the microcontroller. You would never be able to get it to work properly.

If you include just 24 VDC digital I/O then you will be quite limited on the applications you could create with the PLC shield. Besides you still need a watchdog timer for safety and protection.

On your suggestion in using 4-20ma analog I/O (250 dropping resistors), the cost of the external 4-20 ma. transducers would be prohibitive.

"Never trust an Internet bully who insults and makes fun of your level of intelligence."


Mar 14, 2010, 01:19 am Last Edit: Mar 14, 2010, 01:42 am by ArduinoAndy Reason: 1
PLC software programming and hardware tips.  (Part III)

"Design for reliability and program check for the worst"

Programmable logic controllers use "relay ladder logic" (RLL) as a preferred PLC programming control language. The Arduino "C" functions, made for programming the Arduino and compatible boards, is extremely easy to use. The Home Automation "Gator" PLC uses the same "C" functions.

The PLC scan sequence includes "input scan", "user program scan" and "output scan", which works in the microcontroller's main Loop(). Reading the inputs (analog or digital), CPU processing the inputs by "if, then, else statements" and other comparison logic and then outputing the results to PLC outputs is all that takes place during each complete "PLC Scan" pass in the main loop(). All PLC scan sequence routines are polled and interrupts are not allowed, which could halt the CPU.

We tried to closely mimic a modern PLC by timing each task in the control sketch software. If a input or control action takes too long, in execution, the PLC will halt and an error is generated. The extremely useful Arduino function millis() command which is used throughout our control software to detect any delays in the overall PLC scan sequence performance.  

On reset, reboot or power on reset, the system startup routines <setup()> thoroughly checks for any device or peripheral failure. The system watchdog will not be reset and no control output action will take place until all system devices and peripherals are 100% operational. Simple diagnostic checks like I/O board logic power (checked by polling a spare input photo isolator), I2C addressing checking and a 2 second RTC update checking is all that is needed to verify that all devices are functional and 100% working. Even in the main PLC scan sequence, we run a system diagnostic check on every scan.

I2C bus is the weakest link, on this PLC and on any Arduino. Our design spec. requires a I2C real time clock and we had to make sure the I2C bus was reliable. When a I2C device like a RTC loses its 5 Volt power source, has a loose wire, or fails, or has a low battery or just hangs, the microcontroller I2C master hangs or waits for a response (forever) from the slave I2C device. We checked for this I2C device failure by installing an external WatchDog to prevent any control output(s) from functioning until the I2C failure is fixed.
Note: The I2C/TWI wire library should be rewritten to include a instruction "skip" on any I2C bus timeout failure - if possible ????

Most PLCs have LED lights to easily indicate visually what control I/O actions are being executed. LED lights for the inputs and outputs on the digital I/O board makes troubleshooting a snap. Software generated (Pin 13) red LED for uploading, PLC running, and PLC scanning also helps. The "relay power LED" and the "logic power LED" along with the +5 VDC power supply LED also help in troubleshooting PLC problems. The Watchdog has a red flashing LED to indicate watchdog "time out" and also has a yellow LED for watchdog reset (software controlled LED). By observing all LED status indications, this PLC can be easily troubleshot without meters and diagnostic tools.

During power on reset, the BlinkM cycles thru the rainbow of colors and also flashes green on the I2C bus check completion. The BlinkM is used as the PLC system annunciator. Green is system running and Red is system stopped or failure. You probably need sun glasses on to read this LED PLC system status annunciator - this RGB LED is bright!

Software delays should not be used except during the setup or startup bootup. The PLC scan time should not be slowed down by unnecessary software delays. In our applications, we need every bit of real time for both the PLC scan and the IOBridge scan loops, so the use of any software delays are prohibited. Also, by having extra 4 MHz on the Gator/Gator+ (@ 20 MHZ) provides for a faster PLC scan sequencing.

Most serial LCDs are slow but having one helps in system diagnostics. The LCD we are using takes over 100 ms. to display our LCD data, which slows down the PLC scan. We only display diagnostic data on the LCD when there is a error, failure or fault but never use it as a "running data" information display due to its slow speed.
Note: The Arduino has a receive buffer but does not have a transmit buffer, which slows down all transmited bytes to the LCD! <--- The Arduino design team, one day, should add this variable Tx buffer!

Ambient temperature and light changes affects the readability of all LCD displays. Since the  LCD display, we are using, has software controlled brightness and contrast control, then we used a LM34/35 temperature and ambient light sensor (TEMT6000) to adjust the LCD brightness and contrast to different ambient conditions.

There are four ways we show PLC faults, errors and failures to the end user. Each way is dependent on where, how and when a failure has occured in the PLC.
The first way is by the 1st USB serial comm. port via laptop serial terminal program.
The second way, if the I2C bus passes diagnostics, the numerous software colors generated by the RGB BlinkM I2C LED system annunciator.  Green = System OK & Red = System Failure
The third way is by the 4x20 LCD serial terminal information display.
The fourth way is to observe on board LEDs on all of the electronic sub modules.

The PLC RTC, (Macetech.com) "ChronoDot" DS3231 is an extremely accurate real time clock. In fact, Maxim-IC claims its DS3231 to be "the industry's most accurate real time clock?"
On daylight savings time changeovers in March and November of each year (In the USA), we decided to preprogrammed in all of the projected DST dates for ten years, which would keep us from resetting the RTC time every year (twice). The lithium battery would run low (8 years) before we would change the time again.
Note: This precision "ChronoDot" RTC is good for +- 1 minute per year!

Power distribution on the PLC requires "clean" and "dirty" power supplies. The internal +5 VDC switching power supply provides "clean power" to the A/D devices, I2C bus devices, the LCD and the "logic power" for the Parallax I/O board. This +5 VDC should NOT be used for any external device to the PLC. Doing so could induce noise and halt the Gator microcontroller. The "clean" +12 VDC supply input power that feeds the Watchdog, the I/O board relay power, the input of the +5 VDC power and the Gator supply voltage input should NOT also be used to externally power other devices. By obtaining very inexpensive switching +5 VDC and 12 VDC power supplies(Sparkfun) with LED indicators, should be done to power the external PLC devices and the photo isolator inputs. Do not power the photo inputs with the "clean" 12 VDC supply voltage!

Note: The external "dirty" power supplies are very noisey due to inductive switching of solenoids, relays and other loads that are connected to the PLC.

Note: The Parallax Digital I/O Board darlington driver (UN2803) has internal noise supression diodes to reduce the inductive switching noise generated by the on board mechanical relays.

Note: The Gator/Gator+ also has extra built-in ESD, overvoltage and overcurrent I/O pin protection, which greatly increases the runtime reliability of the Home Automation Gator PLC.  

Note: Notice the huge capacitors on the Parallax Digital I/O Board (1000 uf), the Watchdog board (1000 uf) and the I2C bus board (330 uf) ... they are installed to filter out any noise spikes generated by the PLC sub modules.

Wiring a PLC requires special thought. Keep the AC loads as far as possible away from the DC loads. On the PLC panel (picture above) the farthest right hand corner of the Digital I/O board should be wired for only AC loads.

Summary: Any microcontroller can be used as a "programmable logic controller" to control external devices, but not having the proper designed photo isolation on the digital inputs, isolation on the digital outputs, watchdog safety protection, clean and dirty power distribution, noise suppression, board filter protection, control software that checks for task timing and also does system diagnostics then having a microcontroller to control external devices would be a waste of money due to system unreliabilty and poor runtime performance. Better have several spare Arduinos laying around for replacement!  

8-) 8-) 8-)    
"Never trust an Internet bully who insults and makes fun of your level of intelligence."


Mar 14, 2010, 08:47 pm Last Edit: Mar 14, 2010, 09:55 pm by ArduinoAndy Reason: 1
PLC Analog / Digital Interface Bus Board (Part IV)

The 3 pin modular connector(s) A/D Bus Board was designed to accommodate Phidgets and Seeed Depot (China) compatible boards. There are many sensors and widgets, which can be easily connected to the Home Automation Gator PLC by the standard pinout format of (1)GND, (2)VCC, and (3)signal (analog or digital) on their three pin modular connectors.

Note: The PLC +5 VDC switching 1 amp. power supply supplies power from the I2C/+5 VDC bus board to all 3 pin modular connectors.

Links: http://www.phidgets.com/products.php?product_id=1120
http://www.seeedstudio.com/depot/electronic-brick-family-sensors-c-48_52.html (2 weeks shipping)

The following is just a sample that can be quickly connected to the 3 pin modular 5 VDC. input/output A/D PLC interface:
           Sensors:                                                         ($USD)
       #1102 - IR Reflective Sensor                       $7.00 Phidgets
       #1103 - IR Reflective Sensor                     $11.00 Phidgets
       #1128 - Sonar Sensor                               $35.00 Phidgets
       #2008 - IR Distance Sensor                       $25.00 Phidgets
       Electronic Brick - Diffuse Ref. IR Switch       $10.50 Seeed Depot
       #1106 - Force Sensor                                $11.00 Phidgets
       #1115 - Pressure Sensor                           $50.00 Phidgets
       #1120 - FlexiForce Adapter (for below)       $11.00 Phidgets
          #3100 FlexiForce  0-1# Sensor                $22.00 Phidgets
          #3101 FlexiForce  0-25# Sensor              $22.50 Phidgets
          #3102 FlexiForce  0-100# Sensor            $22.50 Phidgets          
       #1126 - Differential Gas Pressure Sensor   $40.00 Phidgets
       #1129 - Touch Sensor                                $11.00 Phidgets
       Electronic Brick - Touch Sensor Module(Dig)   $5.50 Seeed Depot                          
       #1104 - Vibration Sensor                            $11.00 Phidgets
       #1111 - Motion Sensor - PIR                       $45.00 Phidgets
       Electronic Brick - PIR Motion Sensor            $11.50 Seeed Depot
       #1108 - Magnetic Sensor                            $11.00 Phidgets
       #1124 - Precision Temp. Sensor                  $15.00 Phidgets
       Electronic Brick - Temperature Sensor           $3.50 Seeed Depot
       #1125 - Humidity/Temp. Sensor (2 inputs)   $50.00 Phidgets
       #1127 - Precision Light Sensor                    $11.00 Phidgets
       Electronic Brick - Light Sensor Cad. Sulf.       $3.50 Seeed Depot
       Electronic Brick - Carbon Monoxide Sensor    $9.00 Seeed Depot <--- Note 1
       Electronic Brick - Gas Sensor LPG/Nat.Gas.   $6.90 Seeed Depot <--- Note 1
       Electronic Brick - Gas Sensor LPG/Propane    $9.90 Seeed Depot <--- Note 1
       Electronic Brick - Smoke Sensor                   $6.90 Seeed Depot <--- Note 1
      <Input- Output>
       #1109 - Rotation Sensor                             $7.00 Phidgets
       #1112 - Slider 60 Sensor                          $11.00 Phidgets
       #1113 - Mini Joy Stick Sensor                    $15.00 Phidgets
       #1116 - Multi-Turn Rotation Sensor            $29.00 Phidgets
       Electronic Brick - Multi Rotary Sensor (Pot)   $8.50 Seeed Depot
       Electronic Brick - Multi Angle Sensor (Pot)     $3.50 Seeed Depot
       Electronic Brick - Magnetism Switch (Dig.)    $3.90 Seeed Depot
       Electronic Brick - Mercury Tilt Switch (Dig)    $1.50 Seeed Depot <--- Illegal in USA?
       Electronic Brick - Joystick (D/A 3 inputs)       $7.90 Seeed Depot
       Electronic Brick - 5 VDC Relay (Digital)         $7.90 Seeed Depot
       Electronic Brick - Buzzer (Digital)                 $5.50 Seeed Depot
       Electronic Brick - Microphone                      $9.50 Seeed Depot
       Electronic Brick - LED (Digital)                    $3.50 Seeed Depot
       Electronic Brick - Microphone                      $9.50 Seeed Depot
       Electronic Brick - A/D Key Module               $5.50 Seeed Depot
       Electronic Brick - Big Button Switch (Dig.)    $3.50 Seeed Depot
       Electronic Brick - Dual Big Button Switch(D) $3.80 Seeed Depot
       Electronic Brick - Tac Switch (Digital)           $3.50 Seeed Depot
       Electronic Brick - Rolling Ball Tilt SW(Dig)    $3.50 Seeed Depot
       #1122 - 30A Current Sensor AC/DC(2 inputs) $31.00 Phidgets
       #1135 - Precision Voltage Sensor                   $19.00 Phidgets
       #3500 - i-Snail-VC-10 Current Sensor 10A     $40.00 Phidgets
       #3501 - i-Snail-VC-25 Current Sensor 25A     $40.00 Phidgets
       #3500 - i-Snail-VC-50 Current Sensor 50A     $40.00 Phidgets
       #3501 - i-Snail-VC-100 Current Sensor 100A $40.00 Phidgets
       Electronic Brick - Electricity Meter                  $11.50 Seeed Depot

Note 1: Calibration gas samples / equipment  required for sensor calibration ---> $$$$$$
Sensor should not be used for the primary alert sensor for human (life) and protection!

Note 2. Some Phidget's sensors must be made of gold. By careful sensor inspection and reverse engineering, the cost of most of the sensors can be greatly reduced by installing the individual components on a perf board!

Note 3. We carefully choose sensors, which are connected to the PLC, which does not slow our polling scan time down significantly. Sensors which take complex math calculations, pulse and frequency reading and interrupts are never connected. There are always other sensors, to choose from, that will do the same function.  

Note 4. Other sensors from sparkfun.com, parallax.com and futurlec.com could be easily adapted for the 3 pin 5 VDC analog and digital interface connector.

Note 5. All Arduino analog inputs should work with the above sensors. If you subtract 2 analogs for I2C Bus then you only have four left. The Gator/Gator+ has 8 usable analog inputs and maps the I2C Bus to other I/O pins to be compatible with the Arduino.

Note 6. One user said "that our Home Automation PLC could be used for a great Arduino instructional, training and development system"  - great idea!

Note 7. Due to the Gator's I/O pin zener protection scheme, analog voltages above 4 VDC are slightly non-linear. Check their website for further details. Not a major problem, due to the usable input range of most sensors but you need to be aware.

8-) 8-) 8-)    

"Never trust an Internet bully who insults and makes fun of your level of intelligence."


Mar 17, 2010, 05:55 pm Last Edit: Mar 18, 2010, 01:43 am by ArduinoAndy Reason: 1
Approximate cost estimation of Home Automation Gator PLC in $USD
(We used parts we had laying around for other projects for the Gator PLC)

It is extremely hard to compare the Home Automation Gator PLC with commercial units.
Our PLC has many design enhancements not found on commercial PLCs like the BLinkM RGB annunciator, a very accurate RTC (ChronoDot), external Watchdog, user adjustable photo inputs, and selectable digital outputs (AC or AC/DC loads using solid state and/or mechanical relays), an I2C bus for further analog expansion.
To do a fair comparison then all the PLC specs., hardware, software would have to be exactly the same.
Since, using a PLC, requires using I/O in an application for the end user, then a very crude comparison would be the cost per I/O point.

The Automation Direct probably has the lowest cost PLC in the industry, so a very crude cost comparison was made with our Home Automation Gator PLC. It will be quite obvious that making your own Arduino PLC is inexpensive. Being able to use the flexible Arduino programming language functions provides faster program development. The ability able to repair your own PLC yourself provides a great advantage to other commercial PLCs which cannot be fixed on site.

Automation Direct Click Series PLCs (needs 24 VDC power)
Part# CO-02DR-D 4 DC IN/ 4 Relay out, 2 channel analog In 2 channel analog out
Note: Software is Free
Note: Needs programming cable(s) to function - $14 (R3232 cable)  & $29 (USB to RS232)

$182.00    Click PLC Total Cost

Total Click PLC $182 / 12 I/O points =  Cost per usable I/O point ~$15 <-------<<<<<<

The approximate cost of the Home Automation Gator PLC Sub Modules:
(Excludes no tax, shipping cost, mounting hardware, misc. wiring, labor/ construction)

Gator Sub-Modules Cost USD:

 Gator CPU + cable inc.  $40.00 <--- 24 usable I/O points >  Click PLC
 5 VDC Power Supply       $7.00 <--- Extra part not found on Click PLC
 LCD 4x20 Display          $24.00 <--- Extra part not found on Click PLC
 Watchdog Bus Module    $13.00 <--- Extra part not found on Click PLC (Also, reduces wiring)
 BlinkM Annunciator        $13.00 <--- Extra part not found on Click PLC
 RTC ChronoDot             $15.00 <--- More accurate part than Click PLC
 Digital I/O (isolated)      $50.00 <--- Flexible user defined (Digital Inputs / Outputs)
 I2C Bus Module             $12.00 <--- I2C (127 max.) slave expansion - Click has fixed analog I/O (Also,
                                                      reduces wiring)
 A/D Bus Module             $12.00 <--- Extra part not found on Click PLC (Also, reduces wiring)
                                    $186.00 Total plus relays (see below)

Total Gator PLC $186 + $16 (8 @ $2 each - mechanical relays)
$202.00 / 24 I/O = Cost per I/O point ~$8.41 <-------<<<<
Note:  Relays are extra! - Solid State relays are $4.00 each and Mechanical relays are $2.00 each - user definable per application.

Note: The Gator has 28 I/O points and 24 usable I/O points. Using the cost per I/O from the Click PLC and applying it to the Gator PLC comes out to be 24 x $15 = $360.

Note: 12 VDC input clean supply required plus dirty supplies for external devices.

8-) 8-) 8-)
"Never trust an Internet bully who insults and makes fun of your level of intelligence."


Picture below is the close up of the A/D bus module of the PLC.
The LM34DZ (temp. sensor ) the TEMT6000 (ambient light sensor) and the PLC Piezo Buzzer are to the left.

8-) 8-) 8-)
"Never trust an Internet bully who insults and makes fun of your level of intelligence."


The Home Automation Gator PLC Complete Panel - picture below.
PLC simulation, testing, debugging & software development is on-going ...
8-) 8-) 8-)
"Never trust an Internet bully who insults and makes fun of your level of intelligence."


I think you really have something there. The power of a PLC with the potential to do things much faster than PLC's typically pathetic scan time.


We are not using the Home Automation Gator PLC for robotics or machine control, which needs a very fast scan time, but we need it to do sprinkler valve sequencing, garage door automation, home security and environmental data monitoring.
8-) 8-) 8-)
"Never trust an Internet bully who insults and makes fun of your level of intelligence."


Mar 24, 2010, 09:48 pm Last Edit: Mar 25, 2010, 02:13 pm by ArduinoAndy Reason: 1
The Home Automation Gator PLC raw scan time is below 2 ms. per loop. There were several analogs sensors and also some digital sensors we needed to add to the PLC. We did not want to increase our scan time by processing the following analog and digital sensors:

#1. Sensirion SHT71, which provides 14 bit resolution digital ambient temperature (F), relative humidity (%) and dewpoint (F.)
   Design Note: Sensor needs to be polled every five seconds to prevent self heating and excessive current draw.
   Design Note: The Arduino Sensirion library converts this sensor measurements to floats and in degrees C.
                       Conversion is needed to degrees F.

#2. EZ0 Maxbotix - Analog distance range sonar.
     Design Note: Sonar signal needs to be averaged.

#3. PIR security sensor - Parallax, Radio Shack or Futurlec. The same module but the cost varies alot between
    different vendors.
   Design Note: PIR needs to have a sample and hold applied to the output digital signal to indicate proper
                      motion detection.
   Design Note: We added a motion detection LED on the Smart Sensor Module in which could be turned on/off via
   Design Note: This passive infrared sensor has a very long range (~30') and is very fast and heat or motion
   Design Note: Jumper on PIR Module was set for High trigger.

#4. LM34DZ - Analog ambient temperature sensor 10/mv per F. (Inexpensive +- 3 F. temperature sensor to verify
     the SHT71 temperature and used as a backup sensor)
   Design Note: LM34DZ sensor signal needs to be averaged.
   Design Note: Inexpensive temp. sensor - ~ $3

#5. TEMPT6000 - Fast ambient analog light sensor adapted to human eye responsivity - Sparkfun.
     Design Note: Ambient light sensor analog signal needs to be averaged.

To provide sensor averaging, scaling and other pre-processing to condition the sensors for the Home Automation PLC would take tens of milliseconds, which we did not want to waste. We came up with a "Smart Sensor" I2C Slave Module which pre-processes all analog/digital sensor signals and communicates with the Gator PLC via I2C.
Less than 1 millisecond of CPU time was needed to acquire the 11 bytes of sensor data from the Smart Sensor Module!

By checking the I2C communications, we found I2C errors around 2% of the total scan, which we could not tolerate. We added CRC16 error checking to the I2C communications to provide the most reliable data exchange from the Home Automation I2C bus. (see below algorithm)  

Note: We had a 6 foot I2C cable and the Smart Sensor Module was constructed on a proto board. It doesn't matter if the  I2C communication transmission length is one inch or 3 meters you will still need CRC16 error checking (or other types of error checking) to prevent false or corrupt I2C Slave to Master data bytes!!!! Having no error checking means you are playing Russian Routte with your data or worst yet controlling a PLC on bad data.!

Having error free I2C data from the Smart Sensor Module is good but not having the data arrive in a timely fashion is also another problem. We added a retry counter for missing I2C data and after 3 retries halts the PLC and triggers the watchdog. We also added a <millis()> timeout timer if the I2C data transfer takes too long.

Code: [Select]
<For Ref. only>
<Below is the CRC16 code we used - modified for the Arduino by ArduinoAndy>

My CRC algorithm uses a cyclic redundancy check "EEPromless" non table driven algorithm in the poly form of x16 + x15 + x2 + 1.
This CRC-16 algorithm is used in Modbus, SDLC, USB, disk drives and by IBM and many others. By using arrays the CRC checking
can be easily obtained.

CRC-16 Error Checking Accuracy:
Single Bit Errors: 100 percent
Double-Bit Errors: 100 percent
Odd-Numbered Errors: 100 percent
Burst Errors Shorter than 16 bits: 100 percent
Burst Errors of exactly 17 bits: 99.9969 percent
All other burst errors: 99.9984 percent

Arduino Code:

byte DataIn[5] = {
 2, 4, 8, 3, 2};

byte DataOut[5] = {
 2, 4, 8, 3, 2};

//The sending system will calculate a CRC and append it to the message. The receiving system will calculate a new
//CRC based on the entire message - including the appended CRC bytes. The resulting CRC should be 0x0000. If
//the CRC calculated by the receiving system is not equal to zero, then an error occurred in the transmission and all
//data should be ignored.

byte Test[7] = {
 2, 4, 8, 3, 2, 92, 3};

// Global Variables for CRC16 Checking
unsigned char CRC16_Hi_Byte = 0xFF; // Do not modify
unsigned char CRC16_Low_Byte = 0xFF; // Do not modify

/*The function cal_CRC16 takes two parameters:
unsigned char *CRC16_Data_Array   = A pointer to the data array containing binary data to be used for generating the CRC
unsigned short CRC16_Data_Array_Len = The number of bytes in the data array.
Optimized CRC-16 calculation uses no tables or EEPROM
Polynomial: x^16 + x^15 + x^2 + 1 (0xA001)
Initial value: 0xFFFF
CRC-16 is normally used in disk-drive controllers.
Modified for the Audrio/Freeduino */

unsigned int cal_CRC16(unsigned char *CRC16_Data_Array, unsigned short CRC16_Data_Array_Len)
 unsigned int x = 0xFFFF;
 unsigned int y;
 int i;
 x ^= *CRC16_Data_Array;
 for (i = 0; i < 8; ++i)
   if (x & 1)
     x = (x >> 1) ^ 0xA001; // <----The key
     x = (x >> 1);
 CRC16_Hi_Byte = highByte(x);
 CRC16_Low_Byte = lowByte(x);
 y = x;  
 while (CRC16_Data_Array_Len--)
   y ^= *CRC16_Data_Array;
   for (i = 0; i < 8; ++i)
     if (y & 1)
       y = (y >> 1) ^ 0xA001; // <---The Key
       y = (y >> 1);
   CRC16_Hi_Byte = highByte(y);
   CRC16_Low_Byte = lowByte(y);  
 CRC16_Hi_Byte = lowByte(y);   // write to global variable
 CRC16_Low_Byte = highByte(y); // write to global variable
 return y;
} // end of cal_CRC16 function

void setup()


void loop()
 //cal_CRC16(Test, 7);
 cal_CRC16(DataIn, 5);
 Serial.print("High Byte (hex) = ");
 Serial.print("High Byte (dec) = ");
 Serial.print("Low Byte (hex) = ");
 Serial.print("Low Byte (dec) = ");


8-) 8-) 8-)
"Never trust an Internet bully who insults and makes fun of your level of intelligence."


Mar 24, 2010, 09:52 pm Last Edit: Mar 24, 2010, 09:58 pm by ArduinoAndy Reason: 1
The Smart Sensor front side picture - below. <Left to right - top to bottom.>
Yellow motion detection LED, LM34DZ temp sensor & SHT71 temp., RH % humidity and dewpoint sensor side by side.
Temt6000 ambient light sensor, EZ0 Sonar and PIR motion dectector.
The 4 pin I2C bus cable on the right goes to the PLC.

8-) 8-) 8-)
"Never trust an Internet bully who insults and makes fun of your level of intelligence."


The Smart Sensor -- back side picture below.
The Smart Sensor pre-processor - the Bare Bones Board by Modern Device. This Arduino compatible board was a perfect fit to process the analog and digital sensors data and transmit via I2C to the master on the PLC I2C bus.

8-) 8-) 8-)
"Never trust an Internet bully who insults and makes fun of your level of intelligence."

Go Up