Build Real Time Clock using 8051and DS1307 RTC Module اصنع ساعة باستخدام


Notes On DS1307 RTC Module

Here we are using an RTC module with clock chip DS1307 based on I2C protocol (Two Wire Protocol). The module provides details such us second, minute, hour, day of week, day of month, month and year including correction for leap year. It can operate either in 12 Hour or in 24 Hour format. Current consumption of this module is nano ampere range. Even a 3V battery can power it for 10 years maintaining an accurate clock and without any external
power.


DS1307 has a memory area of 64 bytes of which the first 8 bytes are reserved as RTC register area and the remaining 56 bytes are allotted as general purpose RAM. The details about current, date and time is stored in its register area as Binary Coded Decimals(BCD). The module communicates with the microcontroller using a serial communication protocol called I2C. The I2C bus physically consists of 2 active wires. The wires, called SDA and SCL, are both bi-directional. SDA is the Serial Data line, and SCL is the Serial CLock line. Every device connected to the bus has its own unique device address, no matter whether it is an MCU or RTC module. Each of these chips can act as a receiver or transmitter, depending on the functionality.
DS1307 will act as slave in the communication network and controller can only access the slave by initiating a start condition along with a device address. Thereafter, we need to send the register number in order to access the value inside. The interface to the 8051 is simple I2C, with SDA and SCL pins connected to the any two pins of 8051. At the software side we are using a user defined library named “I2C” for I2C communication. This library allows you to communicate with I2C / TWI devices.
I hope you understood so far!  Lets get to the circuit diagram! So given below is the circuit 
diagram to connect RTC module to 8051
ملاحظات على DS1307 RTC Module
نحن هنا باستخدام RTC Module مع شريحة الساعة DS1307 على أساس البروتوكول I2C (بروتوكول سلكين). تزودنا بالتفاصيل الاتية مثل الثانية، دقيقة، ساعة،ايام الاسبوع، ايام الشهور والشهر والسنة بما في ذلك تصحيح السنة الكبيسة. وبامكان الساعة ان تعمل بنظام 12 ساعة أو 24 ساعة. استهلاك الطاقة في الدائرة في نطاق  النانو أمبير. اي ان بطارية 3V يمكن أن تشتغل لمدة 10 سنوات مع الحفاظ على ساعة دقيقة وبدون مصدر خارجي.
DS1307 يحتوي على مساحة ذاكرة 64 بايت . أول 8 بايت محجوزة كمنطقة تسجيل RTC و 56 بايت المتبقية مخصصة كذاكرة عشوائية للأغراض العامة. يتم تخزين التفاصيل الحالية كالتاريخ والوقت في مساحة من السجل ب النظام Binary Coded Decimals(BCD) . الوحدة تتصل مع متحكم باستخدام بروتوكول الاتصالات التسلسلي الذي يدعا I2C. ويتكون الناقل   I2C bus  من سلكين نشطين . الأسلاك تسمىSDA  وSCL ، وكليهما ثنائي الاتجاه. SDA هو خط البيانات التسلسلية، و SCL هو خط  التسلسلي لكلوك الساعة . كل جهاز متصل بالناقل لديه عنوان جهاز فريد من نوعه، بغض النظر عما إذا كان وحدة  MCU or RTC. كل من هذه الرقائق يمكن أن تكون بمثابة جهاز استقبال أو جهاز إرسال، اعتمادا على وظيفة.
سوف DS1307 بمثابة SLAVE اي الخادم في شبكة الاتصالات ويمكن الوصول فقط اليها عن طريق الشروع في عنوان الجهاز. بعد ذلك، نحن نحتاج إلى إرسال رقم السجل من أجل الوصول إلى القيمة في الداخل. واجهة إلى 8051 بسيطة I2C، مع SDA وSCL الاسنان او الارجل او الدبابيس كما تسمى االخاصة بالشريحة متصلة باثنين من دبابيس 8051. بخصو البرمجيات سوف نستخدم المكتبة المعروفة  باسم "I2C" للاتصالات I2C. هذه المكتبة تسمح لنا بالتواصل مع أجهزةI2C / TWI.

Circuit Diagram – RTC Interfacing with 8051



The Program/Code Explanation



Arduino IR Receiver Module



This post describes how to use the Keyes IR Receiver Module in a practical application.  The setup used in this experiment is shown in the picture to the right and it includes Arduino UNO card (hidden under an Ethernet shield), a display module JY-LKM1638, a Keyes IR Receiver module and a remote controller. The last two items are often sold together.
The connections are made as shown in the following tables. I found that the IR module works with either V5+ or V3.3+. The pin labels for the display module are printed in the backside of the card.
Arduino PinDescriptionTM1638IR Receiver
VCC+5VVCC
3V3+3.3V+ (middle)
GNDGNDGND
D6Digital Pin 6 (PWM)
D7Digital Pin 7STB0
D8Digital Pin 8DIO
D9Digital Pin 9 (PWM)CLK
D10Digital Pin 10 (PWM)
D11Digital Pin 11 (PWM)S
D12Digital Pin 12
Once wiring  is made, you should use the display module library and the IR module library for the rest of this post.
Run the example IRrecvDemo and use the serial monitor to observe the output. Every time you point the remote controller  to the IR receiver and press a button you will notice that its LED blinks and the output (in the form of 6 hex numbers) appears on the monitor. If your press is a bit long, a string of 8 ‘F’s appears after the the 6 digit code, as shown below. Note also that all valid codes has ‘FF’ in the high significant digits, so the unique part of the code is only four-digit long.
FFB04F
FFB04F
FFFFFFFF
FF6897
FF52AD
FF4AB5
FFFFFFFF
The sketch below uses this information to map the codes to the actual key labels on the remote controller. Once a new code is received, it is masked with ‘FFFF’ to get only four hex digits. IF the resultant code is ‘FFFF’ it is ignored, otherwise the valid code is mapped into a key and displayed on the display module. I created mapping for keys ‘0’ to ‘9’ only but there is no reason for not extending the mapping all keys. Once the key mapping is done, it can be used to execute any useful command.
#include <TM1638.h>
#include <IRremote.h>
// define IR module
decode_results results;
IRrecv irrecv(11);
// define a display module on data pin 8, clock pin 9 and strobe pin 7
TM1638 module(8, 9, 7);
// define code to charater mapping for
0x18E7, //2
// remote control keys '0' to '9'
long grid[] = {
0x6897, //0
char cmd[] = {
0x30CF, //1
0x7A85, //3
0x10EF, //4
0x38C7, //5
0x42BD, //7
0x5AA5, //6
0x4AB5, //8
irrecv.enableIRIn(); // Start the receiver
0x52AD //9
};
'-', ' ',' ',' ',' ',' ',' ',' ', '\0'};
void setup()
{
Serial.begin(9600);
void loop() {
module.setupDisplay(true, 5);
}
module.setDisplayToString(cmd);
if (irrecv.decode(&results)) {
long x = results.value;
if(x!=0xFFFF) {
x = x & 0xFFFF;
cmd[0] = mapping(x);
if(grid[i] == x) {
Serial.println(x, HEX);
executeCommand(cmd[0]);
irrecv.resume(); // Receive the next value
}
} }
char mapping(long x) {
return ('0'+i);
for(int i=0; i<10; i++) {
} } return '-'; }
}
void executeCommand(char cmd) {
// do something useful

Arduino Code for Obstacle Avoidance Robot Car




#include "IRremote.h"
#include <Servo.h>

//Pins for motor A 
const int MotorA1 = 6;
const int MotorA2 = 7; 
//Pins for motor B 
const int MotorB1 = 8;
const int MotorB2 = 9;
//Pins for ultrasonic sensor
const int trigger=10;
const int echo=11;

int leftscanval, centerscanval, rightscanval, ldiagonalscanval, rdiagonalscanval;
char choice;
  
//Pin for IR control
int receiver = 12; // pin 1 of IR receiver to Arduino digital pin 12
IRrecv irrecv(receiver);           // create instance of 'irrecv'
decode_results results; 
char contcommand;
int modecontrol=0;
int power=0;

const int distancelimit = 27; //Distance limit for obstacles in front           
const int sidedistancelimit = 12; //Minimum distance in cm to obstacles at both sides (the robot will allow a shorter distance sideways)

int distance;
int numcycles = 0;
char turndirection; //Gets 'l', 'r' or 'f' depending on which direction is obstacle free
const int turntime = 900; //Time the robot spends turning (miliseconds)
int thereis;
Servo head;

void setup(){
  head.attach(5);
  head.write(80);
  irrecv.enableIRIn(); // Start the IR receiver
  pinMode(MotorA1, OUTPUT); 
  pinMode(MotorA2, OUTPUT); 
  pinMode(MotorB1, OUTPUT); 
  pinMode(MotorB2, OUTPUT);
  pinMode(trigger,OUTPUT);
  pinMode(echo,INPUT);
  //Variable inicialization
  digitalWrite(MotorA1,LOW);
  digitalWrite(MotorA2,LOW);
  digitalWrite(MotorB1,LOW);
  digitalWrite(MotorB2,LOW);
  digitalWrite(trigger,LOW);
}

void go(){ 
   digitalWrite (MotorA1, HIGH);                              
   digitalWrite (MotorA2, LOW); 
   digitalWrite (MotorB1, HIGH); 
   digitalWrite (MotorB2, LOW);
}

void backwards(){
  digitalWrite (MotorA1 , LOW);                              
  digitalWrite (MotorA2, HIGH); 
  digitalWrite (MotorB1, LOW); 
  digitalWrite (MotorB2, HIGH);
}

int watch(){
  long howfar;
  digitalWrite(trigger,LOW);
  delayMicroseconds(5);                                                                              
  digitalWrite(trigger,HIGH);
  delayMicroseconds(15);
  digitalWrite(trigger,LOW);
  howfar=pulseIn(echo,HIGH);
  howfar=howfar*0.01657; //how far away is the object in cm
  return round(howfar);
}

void turnleft(int t){
  digitalWrite (MotorA1, LOW);                              
  digitalWrite (MotorA2, HIGH); 
  digitalWrite (MotorB1, HIGH); 
  digitalWrite (MotorB2, LOW);
  delay(t);
}

void turnright(int t){
  digitalWrite (MotorA1, HIGH);                              
  digitalWrite (MotorA2, LOW); 
  digitalWrite (MotorB1, LOW); 
  digitalWrite (MotorB2, HIGH);
  delay(t);
}  

void stopmove(){
  digitalWrite (MotorA1 ,LOW);                              
  digitalWrite (MotorA2, LOW); 
  digitalWrite (MotorB1, LOW); 
  digitalWrite (MotorB2, LOW);
}  

void watchsurrounding(){ //Meassures distances to the right, left, front, left diagonal, right diagonal and asign them in cm to the variables rightscanval, 
                         //leftscanval, centerscanval, ldiagonalscanval and rdiagonalscanval (there are 5 points for distance testing)
  centerscanval = watch();
  if(centerscanval<distancelimit){stopmove();}
  head.write(120);
  delay(100);
  ldiagonalscanval = watch();
  if(ldiagonalscanval<distancelimit){stopmove();}
  head.write(160); //Didn't use 180 degrees because my servo is not able to take this angle
  delay(300);
  leftscanval = watch();
  if(leftscanval<sidedistancelimit){stopmove();}
  head.write(120);
  delay(100);
  ldiagonalscanval = watch();
  if(ldiagonalscanval<distancelimit){stopmove();}
  head.write(80); //I used 80 degrees because its the central angle of my 160 degrees span (use 90 degrees if you are moving your servo through the whole 180 degrees)
  delay(100);
  centerscanval = watch();
  if(centerscanval<distancelimit){stopmove();}
  head.write(40);
  delay(100);
  rdiagonalscanval = watch();
  if(rdiagonalscanval<distancelimit){stopmove();}
  head.write(0);
  delay(100);
  rightscanval = watch();
  if(rightscanval<sidedistancelimit){stopmove();}

  head.write(80); //Finish looking around (look forward again)
  delay(300);
}

char decide(){
  watchsurrounding();
  if (leftscanval>rightscanval && leftscanval>centerscanval){
    choice = 'l';
  }
  else if (rightscanval>leftscanval && rightscanval>centerscanval){
    choice = 'r';
  }
  else{
    choice = 'f';
  }
  return choice;
}

void translateIR() { //Used when robot is switched to operate in remote control mode
  switch(results.value)
  {
  case 0xFF629D: //Case 'FORWARD'
    go();
    break;
  case 0xFF22DD: //Case 'LEFT'
    turnleft(turntime); 
    stopmove();  
    break;
  case 0xFF02FD: //Case 'OK'
    stopmove();   
    break;
  case 0xFFC23D: //Case 'RIGHT'
    turnright(turntime);
    stopmove(); 
    break;
  case 0xFFA857: //Case 'REVERSE'
    backwards();
    break;
  case 0xFF42BD:  //Case '*'
    modecontrol=0; stopmove(); // If an '*' is received, switch to automatic robot operating mode
    break;
  default: 
    ;
  }// End Case
  delay(500); // Do not get immediate repeat
} 

void loop(){
  
  if (irrecv.decode(&results)){ //Check if the remote control is sending a signal
    if(results.value==0xFF6897){ //If an '1' is received, turn on robot
      power=1; }
    if(results.value==0xFF4AB5){ //If a '0' is received, turn off robot
      stopmove();
      power=0; }
    if(results.value==0xFF42BD){ //If an '*' is received, switch operating mode from automatic robot to remote control (press also "*" to return to automatic robot mode)
      modecontrol=1; //  Activate remote control operating mode
      stopmove(); //The robot stops and starts responding to the user's directions
    }
    irrecv.resume(); // receive the next value
  }
  
  while(modecontrol==1){ //The system gets into this loop during the remote control mode until modecontrol=0 (with '*')
    if (irrecv.decode(&results)){ //If something is being received
      translateIR();//Do something depending on the signal received
      irrecv.resume(); // receive the next value
     }
  }
  if(power==1){
  go();  // if nothing is wrong go forward using go() function above.
  ++numcycles;
  if(numcycles>130){ //Watch if something is around every 130 loops while moving forward 
    watchsurrounding();
    if(leftscanval<sidedistancelimit || ldiagonalscanval<distancelimit){
      turnright(turntime);
    }
    if(rightscanval<sidedistancelimit || rdiagonalscanval<distancelimit){
      turnleft(turntime);
    }
    numcycles=0; //Restart count of cycles
  }
  distance = watch(); // use the watch() function to see if anything is ahead (when the robot is just moving forward and not looking around it will test the distance in front)
  if (distance<distancelimit){ // The robot will just stop if it is completely sure there's an obstacle ahead (must test 25 times) (needed to ignore ultrasonic sensor's false signals)
      ++thereis;}
  if (distance>distancelimit){
      thereis=0;} //Count is restarted
  if (thereis > 25){
    stopmove(); // Since something is ahead, stop moving.
    turndirection = decide(); //Decide which direction to turn.
    switch (turndirection){
      case 'l':
        turnleft(turntime);
        break;
      case 'r':
        turnright(turntime);
        break;
      case 'f':
        ; //Do not turn if there was actually nothing ahead
        break;
    }
    thereis=0;
  }
 }
}


for download IRremote.zip 


كتب عن الروبوت ونظم التحكم


1- كتاب عن الروبوت ونظم التحكم بالعربي
            الكتاب يشرح اساسيات الروبوت  للتحميل انقر هنا 

2- كتيب بالانجليزية يشرح تطوير وصنع الروبوت للتحميل انقر هنا 

3- DATA COLLECTION USING THE LEGO® MINDSTORMS PLATFORM

                     للتحميل انقر هنا 




Arduino Code for Robot




/*
Arduino Code
The following demo code is complied in Arduino (www.arduino.cc) and uses two
subroutines. You are free to copy/paste the code into the Arduino compiler.
Ensure the motor controller is connected properly before use.
The serial data line of the motor controller should be connected to pin 1 (Tx) on the
Arduino.
*/
int servopulse1 = 1250; //test servo tilt position (0deg =0 to 180deg =1500)
int servopulse2 = 1500; //test servo pan position (0deg =0 to 180deg =1500)
int servopin1 = 9; //yellow wire from servo 1 to digital pin 9
int servopin2 = 10; //yellow wire from servo 2 to digital pin 10
int motor_reset = 2; //motor reset pin connected to digital pin 2
void setup()
{
pinMode(motor_reset, OUTPUT); //sets pin as output
pinMode(servopin1, OUTPUT); //sets pin as output
pinMode(servopin2, OUTPUT); //sets pin as output
//digitalWrite(motor_reset, LOW); //do not activate motor driver
Serial.begin(9600); //communication at 9600 baud
// reset motor controller
digitalWrite(motor_reset, LOW);
delay(50);
digitalWrite(motor_reset, HIGH);
delay(50); // reset delay
}
void loop()
{
servoposition(); // subroutine servoposition
motorcontrol(); // subroutine motor control
}
//subroutine servoposition
void servoposition()
{
digitalWrite(servopin1, HIGH); // Start the pulse to servo 1
delayMicroseconds(servopulse1); // Length of the pulse sets the servo position
digitalWrite(servopin1, LOW); // Stop the pulse
digitalWrite(servopin2, HIGH); // Start the pulse to servo 2
delayMicroseconds(servopulse2); // Length of the pulse sets the motor position
digitalWrite(servopin2, LOW); // Stop the pulse
}
//subroutine motor control
void motorcontrol()
{
//left motor
unsigned char buff1[6];
buff1[0]=0x80; //start byte specific to Pololu motor controller
buff1[1]=0x00; //Device type byte specific to Pololu controller
buff1[2]=0x01; //Motor number and direction byte; motor one =00,01
buff1[3]=0x7F; //Motor speed "0 to 128" (ex 100 is 64 in hex)
for(int i=0;i<4;i++) {Serial.print(buff1[i],BYTE);}
//right motor
unsigned char buff2[6];
buff2[0]=0x80; //start byte - do not change
buff2[1]=0x00; //Device type byte
buff2[2]=0x03; //Motor number and direction byte; motor two=02,03
buff2[3]=0x7F; //Motor speed "0 to 128" (ex 100 is 64 in hex)
for(int i=0;i<4;i++) {Serial.print(buff2[i],BYTE);}
{





Programming Your Robot


What Language to Choose?


There are many programming languages which can be used to program microcontrollers, the most common of which are:

  • Assembly; its just one step away from machine code and as such it is very tedious to use. Assembly should only be used when you need absolute instruction-level control of your code.
  • Basic; one of the first widely used programming languages, it is still used by some microcontrollers(Basic Micro,Basicx ,Parallax)  for educational robots.
  • C/C++; one of the most popular languages, C provides high-level functionality while keeping a good low-level control.
  • Java; it is more modern than C and provides lots of safety features to the detriment of low-level control. Some manufacturers like Parallax make microcontrollers specifically for use with Java.
  • .NET/C#; Microsoft’s proprietary language used to develop applications in Visual Studio. Examples include Netduino, FEZ Rhino and others).
  • Processing (Arduino); a variant of C++ that includes some simplifications in order to make the programming for easier.
  • Python, one of the most popular scripting languages. It is very simple to learn and can be used to put programs together very fast and efficiently.
In lesson 4, you chose a microcontroller based on the features you needed (number of I/O, user community, special features, etc). Often times, a microcontroller is intended to be programmed in a specific language. For example:
  • Arduino microcontrollers use Arduino software and are re-programmed in Processing.
  • Basic Stamp microcontrollers use PBasic
  • Basic Atom microcontrollers use Basic Micro
  • Javelin Stamp from Parallax is programmed in Java
If you have chosen a hobbyist microcontroller from a known or popular manufacturer, there is likely a large book available so you can learn to program in their chosen programming language. If you instead chose a microcontroller from a smaller, lesser known manufacturer (e.g. since it had many features which you thought would be useful for your project), it’s important to see what language the controller is intended to be programmed in (C in many cases) and what development tools are there available (usually from the chip manufacturer).

Getting Started

Hello World PSP
The first program you will likely write is  “Hello World” (referred to as such for historic reasons). This is one of the simplest programs that can be made in a computer and is intended to print a line of text (e.g. “Hello World”) on the computer monitor or LCD screen. In the case of a microcontroller, another very basic program you can do that has an effect on the outside world (rather than just on-board computations) is toggling an IO pin. Connecting an LED to and I/O pin then setting the I/O pin to ON and OFF will make the LED blink. Although the simple act of turning on an LED may seem basic, the function can allow for some complex programs (you can use it to light up multi-segment LEDs, to display text and numbers, operate relays, servos and more).

Step 1: Ensure you have all components needed to program the microcontroller
Not all microcontrollers come with everything you need to program them, and most microcontrollers need to be connected to a computer via USB plug. If your microcontroller does not have a USB or DB9 connector, then you will need a separate USB to serial adapter, and wire it correctly. Fortunately many hobbyist microcontrollers are programmable either via an RS-232 port or by USB, and include the USB connector on-board which is used not only for two-way communication, but also to power the microcontroller board.
Step 2: Connect the microcontroller to the computer and verify which COM port it is connected to. Not all microcontrollers will be picked up by the computer and you should read the “getting started” guide in the manual to know exactly what to do to have your computer recognize it and be able to communicate with it. You often need to download “drivers” (specific to each operating system) to allow your computer to understand how to communicate with the microcontroller and/or the USB to serial converter chip.
Step 3: Check product’s user guide for sample code and communication method / protocol
Don’t reinvent the wheel if you don’t have to. Most manufacturers provide some code (or pseudo code) explaining how to get their product working. The sample code may not be in the programming language of your choice, but don’t despair; do a search on the Internet to see if other people have created the necessary code.
  • Check product manuals / user guides
  • Check the manufacturer’s forum
  • Check the internet for the product + code
  • Read the manual to understand how to write the code

Useful Tips

  1. Create manageable chunks of functional code: By creating segments of code specific to each product, you gradually build up a library. Develop a file system on your computer to easily look up the necessary code.
  2. Document everything within the code using comments: Documenting everything is necessary in almost all jobs, especially robotics. As you become more and more advanced, you may add comments to general sections of code, though as you start, you should add a comment to (almost) every line.
  3. Save different versions of the code – do not always overwrite the same file: if you find one day that your 200+ lines of code do not compile, you won’t be stuck going through it line by line; instead you can revert to a previously saved (and functional) version and add / modify it as needed. Code does not take up much space o a hard drive, so you should not feel pressured to only save a few copies.
  4. Raise the robot off the table or floor when debugging (so its wheels/legs/tracks don’t accidentally launch it off the edge), and have the power switch close by in case the robot tries to destroy itself. An example of this is if you try to send a servo motor to a 400us signal when it only accepts a 500 (corresponding to 0 degrees) to 2500us (corresponding to 180 degrees) signal. The servo would try to move to a location which it cannot physically go to (-9 degrees) and ultimately burn out.
  5. If code does something that does not seem to be working correctly after a few seconds, turn off the power – it’s highly unlikely the problem will “fix itself” and in the meantime, you may be destroying part of the mechanics.
  6. Subroutines may be a bit difficult to understand at first, but they greatly simplify your code. If a segment of code is repeated many times within the code, it is a good candidate to be replaced with a subroutine.

Practical Example

Arduino Uno
We have chosen an Arduino microcontroller to be the “brain” of our robot. To get started, we can take a look at the Arduino 5 Minute Tutorials. These tutorials will help you use and understand the basic functionality of the Arduino programming language. Once you have finished these tutorials, take a look at the example below.

For the robot we have made, we will create code to have it move around (left, right, forward, reverse), move the two servos (pan/tilt) and communicate with the distance sensor. We chose Arduino because of the large user community, abundance of sample code and ease of integration with other products.
Sharp GP2D120 IR Range Finder


Distance sensor
Fortunately in the Arduino code, there is an example for getting values from an analog sensor. For this, we go to File -> Examples -> Analog -> AnalogInOutSerial (so we can see the values)
Pan/Tilt
Again, we are fortunate to have sample code to operate servos from an Arduino. File -> Examples ->  Servo -> Sweep
Servocity Pan and Tilt
Note that text after two slashes // are comments and not part of the compiled code

#include <Servo.h>            // This loads the servo script, allowing you to use specific functions below
Servo myservo;                      // create servo object to control a servo
int pos = 0;                             // variable to store the servo position

void setup()                           // required in all Arduino code
{
myservo.attach(9);             // attaches the servo on pin 9 to the servo object
}

void loop()                               // required in all Arduino code
{
for(pos = 0; pos < 180; pos += 1)  // variable ‘pos’ goes from 0 degrees to 180 degrees in steps of 1 degree
{
myservo.write(pos);              // tell servo to go to position in variable ‘pos’
delay(15);                                 // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1)     // variable ‘pos’ goes from 180 degrees to 0 degrees
{
myservo.write(pos);              // tell servo to go to position in variable ‘pos’
delay(15);                               // waits 15ms at each degree
}
}
Motor Controller
Pololu Serial Motor Controller
Here is where it gets a bit harder, since no sample code is available specifically for the Arduino. The controller is connected to the Tx (serial) pin of the Arduino and waits for a specific “start byte” before taking any action. The manual does indicate the communication protocol required; a string with specific structure:

  • 0x80 (start byte)
  • 0x00 (specific to this motor controller; if it receives anything else it will not take action)
  • motor # and direction (motor one or two and direction explained in the manual)
  • motor speed (hexadecimal from 0 to 127)
In order to do this, we create a character with each of these as bytes within the character:
unsigned char buff[6];
buff[0]=0x80; //start byte specific to Pololu motor controller
buff[1]=0; //Device type byte specific to this Pololu controller
buff[2]=1; //Motor number and direction byte; motor one =00,01
buff[3]=127; //Motor speed “0 to 128” (ex 100 is 64 in hex)

Serial.write(buff);
Therefore when this is sent via the serial pin, it will be sent in the correct order.
Putting all the code together makes the robot move forward and sweep the servo while reading distance values.




كتب عن المتحكمات بالعربي



من افضل الكتب التي قراءتها في المتحكمات قد تساعدكم في تعلم المتحكمات بسهولة وببساطة وبدون تعقيدات وهذا سوف يساعدني في عمل مشاريع عبر مدونتي بسهولة .

1- الكتاب الاول  كتاب محاكاة الاردوينو  



كتاب محاكاة الاردوينو يتطرق الكتاب للتعريف بالاردوينو وكيفية استخدام موقع Circuits.io لمحاكاة دائرة الاردوينو وعمل حساب فيه ... ومحاكاة الاردوينو على برنامج بروتس Proteus مع تنفيذ محاكاة لمشاريع باستخدام لوح الاردوينو وهو من تاليف المهندس عبدالله علي عبدالله  حجم الكتاب  3MB  للتحميل انقرهنا 

2- الكتاب الثاني كتاب AVR ببساطة



يتحدث الكتاب عن النظم المدمة وهو من تاليف المهندس عبد الله علي حيث يشرح الكتاب المتحكمات الدقيقة من عائلة AVR وكيفية برمجتها بلغة السي المعيارية ANSI، وشرح ايضاً مبسط للتركيب الداخلي للمتحكم الدقيق وقراءة البيانات Datasheet الخاصة بها، حجم الكتاب23MB  للتحميل انقر هنا 


3- الكتاب الثالث راسبيري باي ببساطة 




كتاب راسبيري باي ببساطة للمهندس عبدالله علي، سوف تتعرف من خلاله على الراسبيري باي وشرح كيفية تشغيله والخوض في نظام لينكس راسبيان. وايضاً شرح ليكفية التحكم في الراسبيري باي من جهاز اخر... ويشمل الفصل السادس في الكتاب شرح لكيفية برمجة منافذ التحكم الالكتروني بالبايثون جحم الكتاب 16MB  للتحميل انقر هنا 



4- الكتاب الرابع  كتاب اردوينو ببساطة



كتاب اردوينو ببساطة سوف تدخل من خلاله عالم الاردوينو المتحكمات الدقيقة بشكل مبسط وسهل وكيفية تشغيل واستخدام لوح الاردوينو وجزئ من الكتاب يناقش تطبيقات مشاريع الكترونية باستخدام الاردوينو والحساسات والمحركات  حجم الكتاب 12MB للتحميل انقر هنا
تابعونا للمزيد من الكتب بالنقر على زر المتابعة او الاشتراك في النشرةالبريدية اسفل الصفحة

Arduino Codes -part 2( Structure -functions)



Functions

A function is a block of code that has a name and a block of statements that are executed when the function is called. The function s setup () and void loop() have already been discussed and other built- in functions will be discussed later

الدوال او الوظائف هي كتلة او حزمة او مجموعة من الاكواد التي لديها اسم محدد وحزمة من العبارات البرمجية والتي يتم تنفيذها عند استدعاء الدالة .

type function Name (parameters)
{
          Statements;
}

Custom functions can be written to perform repetitive tasks and reduce clutter in a program .Functions are declared by first declaring the function type . This is the type of value to be returned by the function such as 'int' for an integer type function . if no value is to be returned the function type would be void . After type ,declare the name given to the function and in parenthesis any parameters being passed to the function. 
الدوال حسب الطلب يمكن كتابتها لاداء مهام تكرارية او محددة ولكي تقلل من الفوضي في البرنامج بالاضافة الى تنسيق خوارزمية البرنامج يعني يصبح البرنامج مفهوم ومرتب ويسهل على الالة تنفيذ البرنامج بسهولة وبدون اخطاء . على كل الدوال يجب ان يصرح عن نوعها مثلا هل هي من النوع الصحيح مثلا int  حيث تعيد القيم الصحيحة فقط ما عدا ذلك تكون غير مقبولة

The following integer type function delay Val () is used to set a delay value in program by reading the value of a potentiometer . it first declares a local variable V, sets V to the value of the potentiometer which gives a number between 0-1023 , then divides that value by 4 for a final value between 0-255, and finally returns that value back to the main program .

int delayval ()
{
  int v;                            //create temporary variable 'v'
  v= analogRead(pot); // read potentiometer value
  v/=4;                           // converts 0-1023 to 0-255
  return v;                     // return final value
}
في المثال السابق هناك دالة من النوع الصحيح وسميت ب delay Val ()  في هذه الدالة يتم قراءة potentiometer لكن قبل ذلك يجب التصريع عن متغير محلي لنسميه v هي تمثل قيمة التماثلية التي يتم رصدلها بواسطة البورد او المتحكم حيث تكون القيم بين 0-1023 بعد ذلك يتم قسمة القيمة على 4 والتي يعيد القيم بين 0-255 ثم بعد ذلك يعيد القيمة v وبالتالي يقرى البرنامج القيم التماثلية الصحيحة فقط ولا يقبل القيم الغير صحيحة.


NOTE                                                                                                                    ملاحظة
سيتم سرد بعض الرمز التي تستخدم عند كتابة البرنامج



{ } curly braces

Curly braces (also referred to as just "braces" or "curly brackets ") define the beginning and end of function blocks and statement blocks such as the void loop() function and the for  and if statements .
الحاصرتين هذه مهمه جدا في تحدد بداية ونهاية الدالة فمثلا في void loop() تكون الحزم او الاكواد مكتوبة بين هاتين الحاصرتين وكذك يتم استخدامها مع الدوال الاخرى وايضا مع دالة for , if  كما سنلاحظ في الاكواد القادمة وكمثال
Type function ()
{
Statements;
}
حيث Type function () قد تكون أي دالة مثلا int time() or for or if … ets
Statements نقصد ان تكتب مكانة العبارات البرمجية أي الاكواد


; semicolon

A semicolon must be used to end a statement and separate elements of the program . A semicolon is also used to separate elements in a for loop .

الفاصلة المنقطة يجب ان تنتهي العبارة البرمجية او الكود بها حتي تخبر الكمبيلر او المترجم بنهاية الكود البرمجي .

int x= 13; // declares variable 'x' as the integer 13

Note : forgetting to end a line in a semicolon will result in a compiler error .
ملاحظة عدم كتابة الفاصه المنقطة بعد الكود سوف ينتج خطاء في الترجمة ويعطي المترجم رسالة خطاء .




/**/ block comments

Block comments , or multi line comments, are areas of text ignored by the program and are used for large text descriptions of code of comments that help others understand parts of the program . They begin with /* and end with*/ and can span multiple lines .

/* this  is an enclosed block comment don't  forget the closing comment they have to be balanced ! */

يستخدم الخط نجمة خط نجمة /*..*/ لكتابة التعليقات عن البرنامج بحيث ان العبارات الواقعة بداخل هذه العلامة لا يتم قراءته  ويتم تجاهله . وهي مفيدة للتوضيح عن البرامج او الادوات المستخدمة الى اخرة .

Note : while it is possible to enclose single line comments within a block comment , enclosing a second block comment is not allowed .



// line comments

Single line comments begin with //and  end with the next line of code . like block comments , they are ignored by the program and take no memory space .
// this is a single line comment .

Single line comments are often used after a valid statement to provide more information about what the statement accomplishes or to provide a future reminder .

يستخدم هذين الخطين ايضا لعمل التعليقات حيث يتجاهل البرنامج العبارات التي تأتي بعدة و يبدا البرنامج بقراءة السطر الجديد .




اعلان

admashmedia

مقالات

chitika

اعلانات

أخبار