יום שישי, 27 באפריל 2012

Arduino Temperature Sensor


אז כמו שהבטחתי חיישנים, החיישן הבא איתו נתעסק הוא ה Temperature Sensor , אני אשתמש בחיישן TMP36 שמבוסס על חיישני Voltage Output Temperature והגדרת היצרן היא 10 Milivolts עבור מעלה אחת, בעצם אנחנו דוגמים Milivolts וממירים אותם למעלות כמו שנראה בהמשך.

דרישות

  • Arduino Uno
  • Arduino Prototype Shield
  • TMP36
  • Wires



TMP36


אז כמו שאמרתי, הדגימות של החיישן מבוססות על Milivolts כאשר 500ms הם טמפרטורת 0 ו 750ms הם 25 מעלות , נשתמש ב 2 נוסחאות הראשונה היא המרת ה Milivolts ל Fahrenheint  ואח"כ מ Fahrenheint  ל Celsius.

המרת Milivolts ל Fahrenheint:
  Fahrenheit = (((mili -.5)*100)*1.8)+32
המרת Fahrenheint ל Celsius:
  Celsius = ((Fahrenheit - 32) * 5 ) /9
וסתם בשביל הקטע המרה בין Celsius ל Fahrenheint:
  Fahrenheit  = (Celsius  * 9) /  5  + 32







מבנה סופי:





קוד: 

//set the tempertaure analog pin 
int tempin = 0;

void setup()
{
  //set serial to output
  Serial.begin(9600);

}

void loop()
{
  //get the milivolts
  float temp  = getVoltage(tempin);

  float Celsius = 0;
  float Fahrenheit = 0;

  //convert the milivolts to Fahrenheint
  Fahrenheit = (((temp -.5)*100)*1.8)+32;

  //convert Fahrenheint to Celsius;
  Celsius = ((Fahrenheit - 32) * 5 ) /9;

 //sending to print
 printme(Fahrenheit,Celsius);

  delay(5000);
}

//just printing to the serial
void printme(int Fahrenheit, int Celsius)
{
  Serial.print("Fahrenheit:");
  Serial.print(Fahrenheit);
  Serial.print(" Celsius :");
  Serial.print(Celsius);
  Serial.print("\n");
}

//reading the analogpin and getting 
//the milivoltages.
float getVoltage(int pin)
{
  return (analogRead(pin) * .004882814);
}



פלט:

סיכום:
בסדרת המאמרים האחרונה למדנו להכיר את Arduino ואת היכולות שלו, עבדנו עם 2 חיישנים , Leds וכפתורים, בשלב זה  אני אקח פסק זמן בכל הקשור ל Arduino כי יש לי עוד הרבה מה לספר לכם בנושאים אחרים ,כמובן שנחזור אליו בהמשך.

איזה חום?

יום חמישי, 26 באפריל 2012

Arduino Button Guide


אז כמו שאתם רואים רוב החודש מוקדש ל Arduino , יש כלכך הרבה מה להראות בו, למרות שהבטחתי להראות עוד חיישנים החלטתי לעבור על חלק קטן נוסף והוא עבודה עם Buttons (כפתורים) גם פה הנושא הוא פשוט ואינו מורכב מידי.



דרישות:

  • Arduino Uno
  • Arduino Prototype Shield
  • Button
  • Led
  • 330Ohm Resistor 
  • 10K Ohm Resistor
  • Bridges





The Button
הכפתורים ב Arduino עובדים על רעיון של רמות מתח, ה Pin שאליו מחובר הכפתור מאזין למתח וכאשר הוא לחוץ מזהה ה Arduino שהוא במתח נמוך ומגדיר אותו כ LOW כמו שתראו בקוד בהמשך... קיימת בעיה כאשר הכפתור לא לחוץ , ה Pin מקבל מתח כל הזמן ועלול לגרום לתופעות משונות על מנת להבטיח אמינות יש להשתמש ב Resistor 10K.




מבנה סופי




קוד:
//set the pins
int ledpin = 12;
int inpin = 3;

//set val for checking
int val =0;

 void setup()
 {
   //set the pin mode
   //led as output
   //button as input
   pinMode(ledpin,OUTPUT);
   pinMode(inpin,INPUT);
 }

 void loop()
 {
   val = digitalRead(inpin);

   //if val is high 
   //the button is not press
   //the led go off else go on
   if(val == HIGH)
   {
     digitalWrite(ledpin,LOW);
   }
   else
   {
     digitalWrite(ledpin,HIGH);
   }
 }

סרט הדגמה:



סיכום:
כפתורים הם חלק בלתי נפרד מחווית המשתמש, עכשיו אפשר להמשיך הלאה לשאר החיישנים.

push the button!

יום שישי, 20 באפריל 2012

Arduino Leds Guide



לפני שנמשיך לשאר החיישנים חייבים לשחק קצת עם לדים (Leds) , יש המון הסברים ודוגמאות בנושא ואחד הדברים הבסיסיים בעבודה עם Arduino, אני לא אזבל לכם במוח יותר מידי, סה"כ מדובר במשהו מאוד פשוט, במאמר זה נעבור על 2 סוגים שונים של Leds , הראשון הוא הסטנדרטי , הרגיל והמשעמם, השני הוא RGB ("אני רואה צבעים").

עבודה עם Led סטנדרטי

דרישות:


  • Arduino Uno
  • Wire
  • Resistors 330 Ohm
  • Bridges





ל Leds הסטנדרטים יש 2 רגליים (+\-) עבור המתח, את רגל החיובית ניתן לזהות בכך שהיא הרגל הארוכה, לה מתחבר נגד 330 Ohm שמתחבר ל Digital Pin , את הרגל הקצרה נחבר לכניסת GND ב Arduino.




ניתן להשתמש ב Bridges (גשרים) על מנת לחבר את כל הלדים לנקודת GND אחת.



מבנה סופי

קוד הדגמה:

//set arduino pins
int pinA =5;
int pinB =6;
int pinC =7;
int pinD =8;
int pinE =9;
int pinF =10;
int pinG =11;
int pinH =12;
int pinI =13;

void setup()
{
  //set pins as ouput
  pinMode(pinA,OUTPUT);
  pinMode(pinB,OUTPUT);
  pinMode(pinC,OUTPUT);
  pinMode(pinD,OUTPUT);
  pinMode(pinE,OUTPUT);
  pinMode(pinF,OUTPUT);
  pinMode(pinG,OUTPUT);
  pinMode(pinH,OUTPUT);
  pinMode(pinI,OUTPUT);
}

void loop()
{
  
  //change each led  to high => on and low => off 
  //using delay between switching

  digitalWrite(pinA,HIGH);
  delay(100);
  digitalWrite(pinA,LOW);
  delay(100);
  
   digitalWrite(pinB,HIGH);
  delay(100);
  digitalWrite(pinB,LOW);
  delay(100);
  
   digitalWrite(pinC,HIGH);
  delay(100);
  digitalWrite(pinC,LOW);
  delay(100);
  
  
   digitalWrite(pinD,HIGH);
  delay(100);
  digitalWrite(pinD,LOW);
  delay(100);
  
   digitalWrite(pinE,HIGH);
  delay(100);
  digitalWrite(pinE,LOW);
  delay(100);
  
    
   digitalWrite(pinF,HIGH);
  delay(100);
  digitalWrite(pinF,LOW);
  delay(100);
  
    
   digitalWrite(pinG,HIGH);
  delay(100);
  digitalWrite(pinG,LOW);
  delay(100);
  
    
   digitalWrite(pinH,HIGH);
  delay(100);
  digitalWrite(pinH,LOW);
  delay(100);
  
    
   digitalWrite(pinI,HIGH);
  delay(100);
  digitalWrite(pinI,LOW);
  delay(100);
  
    

}

עבודה עם Led RGB

דרישות:

  • Arduino Uno
  • Wire
  • 3 Resistors 330 Ohm
  • RGB Led


פה העסק קצת שונה עבור כל ערוץ צבע (שבעצם רגל) מתחבר ל Resistor , הרגל הארוכה מסמנת כרגל השלילית שמתחברת ל GND.


מבנה סופי



יאללה דיסקו!


קוד דוגמה:



//set pins in the arduino
const int RED_LED_PIN = 1;
const int GREEN_LED_PIN = 2;
const int BLUE_LED_PIN =3;

//init value for each channel
int red = 0;
int green = 0;
int blue = 0;

//delay
const int display_timeout = 100;

void setup(){}

void loop()
{
  
  //change the green channel
  // mixing with the red channel
      for(green = 0; green <= 255; green+=5)
    {
       red = 255 - green;
       analogWrite(GREEN_LED_PIN,green);
       analogWrite(RED_LED_PIN,red);
       delay(display_timeout);
    }
    
  //change the blue channel
  // mixing with the green channel
      for(blue = 0; blue <= 255; blue+=5 )
    {
       green = 255 - blue;
       analogWrite(BLUE_LED_PIN,blue);
       analogWrite(GREEN_LED_PIN,green);
       delay(display_timeout);
    }
     
    
  //change the  red channel
  // mixing with the blue channel
      for(red = 0; red <= 255; red+=5)
    {
       blue = 255 - red;
       analogWrite(RED_LED_PIN,red);
       analogWrite(BLUE_LED_PIN,blue);
       delay(display_timeout);
    }
    
}



סיכום:
ראינו כאן משהו מאוד פשוט אבל הכרחי בכל הקשור לחווית המשתמש במוצר שלכם.


סרט הדגמה:




יום שישי, 13 באפריל 2012

Arduino UltraSonic Sensor


אחרי הסקירה הקצרה שלי על Arduino הגיע הזמן שנגע בנושא הכי מעניין מסביב Arduino והוא החיישנים,
יש המון חיישנים שניתן לחבר ל Arduino ולממש בעזרתם המון מוצרים , החלטתי לעשות את המאמר הראשון על  Ultrasonic דרך פשוטה למדוד מרחקים ולשליטה במרחב התנועה של המוצר שלנו.

דרישות:
  • Arduino Uno
  • Arduino Prototype Shiled
  • Wires
  • Ultasonic Sensor Based SDM-IO Module


Ultrasonic
אני לא מומחה גדול בעיבוד אותות אבל אנסה בכול מקרה, מדובר על גלי קול בתדר גבוה שבני אדם לא מסוגלים לשמוע, הרכיב המרכזי במערכות Sonar, החיישן שולח גל קול ומחכה לגל החוזר במקרה ולא חוזר גל הדרך פנויה או שאינה בטווח החיישן, וכאשר יש גל חוזר ניתן לחשב את המרחק שלקח לגל קול לחזור לחיישן, אחד השימושים עבור Ultrasonic הוא "עיניים" , בדיוק כמו שזה נשמע נניח שנרצה לבנות שואב אבק ביתי שהסתובב לנו בבית באופן רנדומלי ,נוכל לבצע זאת בעזרת Ultrasonic שיבדוק אם הדרך עבור השואב שלנו פנויה ובמקרה שלא שהסתובב עד שהחיישן יחזיר שהדרך חופשית.





קיימים סוגים שונים של חיישנים חלקם מגיעים עם 3 ו 4 פינים, החיישן שלי מבוסס על SDM-IO Moudle עם 4 פינים,Vcc,Trig,Echo,Gnd.


נקודות החיבור עם ה Arduino




Arduino Protoype Shield
אחד התוספות החשובות בעבודה עם Arduino מאפשר לנו לפתח אב טיפוס ע"ג ה Arduino לפני יצירת ה Sheild שלכם, ניתן למצוא אותו ברשת במחיר ממוצע של 10 דולר.




מבנה סופי:




קוד:
 //time out  waiting for signal
 #define SDM_IO_TIMEOUT 1000

 //TrigPin in Arduino
 int TrigPin = 12;

 //EchoPin in Arduino
 int EchoPin = 13;

 unsigned long ultrasoundDuration;
 int timeout;
 unsigned long tStartPing = 0;
 int sensorValue = 0;
       
           void setup() {  
                                       //init the serial
                                       Serial.begin(9600);
                                      
                                       //pins setup 
                                       pinMode(TrigPin, OUTPUT);
                                       pinMode(EchoPin, INPUT);
                                    }


             void loop()  {  
              
                                   sensorValue = read_sdm_io_range();  
                                       if(sensorValue != 999)
                                       {
                                         //printing distanse value
                                         Serial.print(sensorValue); 
                                         Serial.println(" cm"); 
                                         //delay before new sample
                                         delay(300);     
                                       }
                               
                                   }
                                  
                                  
          //SDM-IO Ultrasonic Range Sensor distance function 
          float read_sdm_io_range() {  
                                                                   
                                       unsigned char pin = 0;
                                       unsigned int time_flag = 0;
                                                                  
                                        //send HIGH signal
                                        digitalWrite(TrigPin, HIGH);
                                                                   
                                        //wait 2 microsecond
                                        delayMicroseconds(2);
                                                                   
                                        //send LOW signal
                                       digitalWrite(TrigPin, LOW);
                                                                    
                                        //wait 10 microsecond
                                        delayMicroseconds(10);
                                                                   
                                        //send HIGH signal
                                        digitalWrite(TrigPin, HIGH);
                                                                   
                                       //getting system clock
                                       tStartPing = micros();
                                       timeout = 0;
                                       pin = digitalRead(EchoPin);
                                                   
                                       while(pin)  
                                       {   
                                          //waiting for response from EchoPin
                                           //break out when timeout

                                           pin = digitalRead(EchoPin);
                                            time_flag++;
                                                                        
                                            //break when time_flag equal to
                                            //timeout limit

                                             if(time_flag > SDM_IO_TIMEOUT)   
                                            {         timeout = 1;         break;       } 
                                         }
                                                                
                                         //calculate the response time  
                                         ultrasoundDuration = micros() - tStartPing;   
                                                                  
                                         //if timeout equal 1
                                            if (timeout)    
                                                 return 999; 
                                            else    
                                                 return ultrasoundDuration * 0.017;
                                                // result in cm
 }
פלט:


סיכום:
החיישנים הם החלק הבולט והמעניין ביותר בעבודה עם Arduino ומאפשר לנו ללכת צעד קדימה בעיצוב ובתכנון של מוצרי Embedded בהמשך אני אסקור עוד חיישנים רבים עבור מגוון רחב של שימושים.

זה חי...

יום ראשון, 1 באפריל 2012

JavaScript Optimizer

מי שלא זוכר הבטחתי לייצר סדרת כלים חינמים, הראשון שיצא הוא Laping שמאפשר למנהלי רשתות לבדוק זמינות של פורטים ברחבי הרשת, עבר המון זמן והנה הגיעה השעה לכלי חדש, JavaScript Optimizer הוא כלי המבוסס על .Net וביטויים רגולרים (regular expression) שעוברים על הקוד של ה JavaScript ומשנים אותו, הם משנים אותו בצורה אופטימלית כלומר צמצום רווחי שורה, והורדת הערות מקומיות.

מי ולמה צריך את זה?

בעיקר מפתחי אתרים , הרעיון הוא לצמצם את גודל הקובץ שהלקוח צריך להוריד למחשב שלו בעזרת צמצום רווחים ושורות שגם הם תופסים משקל בקובץ, דבר נוסף שמרווחים בתהליך הוא הפיכת הקוד ללא קריא ומקשה מאוד על הצפייה בקוד, מי שרוצה לנתח את הקוד יצטרך לעבור מילה מילה ולעצב את הקובץ בעצמו על מנת שהיה קריא.

דוגמה ללא אופטמיזציה:


function helloWorld(id) {
    var root = document.getElementById('tmp');
    for (var i = 0; i < root.childElementCount; i++) {        
         var elm = root.childNodes[i];      
         elm.className = "test";      
         changeWorld(elm.id);  
         }
}

function changeWorld(id) {
      var f = document.getElementById(id);
      f.attributes("Style", "width:24px; height:32");
      changeSpace(f.id);
}

function changeSpace(id)
{  
      var f = document.getElementById(id);
      f.attributes("onclick", "helloWorld()");
}


דוגמה עם אופטמיזציה:

function helloWorld(id) { var root = document.getElementById('tmp'); for (var i = 0; i < root.childElementCount; i++) { var elm = root.childNodes[i]; elm.className = "test"; changeWorld(elm.id); } } function changeWorld(id) { var f = document.getElementById(id); f.attributes("Style", "width:24px; height:32"); changeSpace(f.id); } function changeSpace(id) { var f = document.getElementById(id); f.attributes("onclick", "helloWorld()"); }

אחרי שראינו את ההבדל נעבור על תוכנית, התוכנית מבוססת על ה Framework 2.0 אבל ניתן לממש אותה בכול שפה שתומכת בביטויים רגולרים, התוכנית עצמה מאוד פשוטה וכוללת בתוכה 2 פונקציות בלבד, טעינה ושמירת קובץ JS, ומורכבת מ 2 ביטויים רגולרים, הביטוי הראשון אינו מתעסק אם האופטימזציה אלא עם ההערות שהמשתמש רשם לקובץ והסיבה היא כאשר נבצע אופטמיזציה ונצמצם את השורות ההערות יפגעו לנו באופטימזיצה בכך שיהפכו את הפקודות בקובץ לההערה, הביטוי השני מצמצם לנו את הרווחים בקובץ.

// remove all to local comments in the file
 file = Regex.Replace(file, "(?<!:)//[^\r\n]*", "", RegexOptions.IgnoreCase);

//replace all extra spaces to one space.
 file = Regex.Replace(file, @"\s+", " ",RegexOptions.Multiline);



חשוב מאוד! במקרה שיש מחרוזות עם רווחים כפולים הם הצטמצמו לרווח בודד, בדקתי את הקוד על מספר קבצים והוא עבד תקין, במקרה של תקלה נא לפרסם בפוסט זה.






התוכנית:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;

namespace javaScriptMinimize
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string file;

        private void btn_input_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txb_input.Text = openFileDialog1.FileName;
                FileStream myfile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                StreamReader myreader = new StreamReader(myfile);
                file = myreader.ReadToEnd();
                file = Regex.Replace(file, "(?<!:)//[^\r\n]*", "", RegexOptions.IgnoreCase);
                file = Regex.Replace(file, @"\s+", " ",RegexOptions.Multiline);
                txb_mini.Text = file;
                myreader.Close();
                myfile.Close();
                myreader.Dispose();
                myfile.Dispose();
            }
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            try
            {
                string filename = "mini_" + Path.GetFileName(txb_input.Text);
                string path = Path.GetDirectoryName(txb_input.Text);
                if (File.Exists(path + "\\" + filename))
                    File.Delete(path + "\\" + filename);

                FileStream myfile = new FileStream(path + "\\" + filename, FileMode.Append, FileAccess.Write);
                StreamWriter mywriter = new StreamWriter(myfile);
                mywriter.Write(file);
                mywriter.Close();
                myfile.Close();
                mywriter.Dispose();
                myfile.Dispose();
            }
            catch (Exception ex)
            { }
        }
    }
}

סיכום:
אז מה ראינו פה? גם הדברים הקטנים ביותר מאפשרים לנו להעלות את האופטמיזציה לאתרים שלנו, ניתן לממש את הרעיון בכל השפות וזאת דרך מעולה להפוך את הקוד שלנו ללא קריא.

פששש....