Category Archives: Contoh-contoh Aplikasi

Contoh Pemrograman Dasar Keypad 4×4 untuk Menu Input Data Angka 4 digit

Hardware
– PC/Laptop
– Board Microcontroller AVR dgn RS232 Port
– Keypad 4×4
– USB to rs232 Converter
– Cable pita isi 10  female to female
– power suply untuk board microcontroller

Software
– Codevision
– Hyperterminal

Penjelasan

Pada Contoh berikut  setiap penekanan  dari Keypad akan di tampilkan pada Led di PORTC dan data angka 4 digit akan dikirim ke PC melalui serial Port.

Gambar :

menukeyboard1

koneksi header  PortA dan  Keypad 4X4

headerkeypad4x4

Gambar Hyperterminal Pada PC

menuhyperterminal

Ringkasan code proggramnya spt ini :

while (1)
{
keypad();

if(kode !=0xff)             // jika keypad ditekan
{
if(digit==4)                //input digit menu pilihan (1~4)
if(menu==1) digit--
else if(menu==2) digit--
else if(menu==3) digit--
else if(menu==4) digit--
else                       // "pilihlah menu"
else if(digit==3) digit-- // masukan input ribuan
else if(digit==2) digit-- // masukan input satuan
else if(digit==1) digit-- // masukan input puluhan
else if(digit==0) digit=4 // masukan input satuan

kode =0xff ;   // kembalikan kode ke 0ff setiap 1 digit angka diketik (tombol dilepas)
}

} end of while

Code Program Selengkapnya:

/*****************************************************
CodeWizardAVR V1.24.8d
Chip type : ATmega16
Clock frequency : 11.059200 MHz

*****************************************************/
#include  < mega8535.h >
#include <stdio.h >
#include <stdlib.h>
#include <delay.h>
#define waktuTekanTombol 500



// Declare your global variables here
unsigned char menu,digit=4;
unsigned int ribuan,ratusan,puluhan,satuan,hasil;
char kode ;
void keypad(void);
void origin(void);
void LED_kelap_kelip(char jml_looping, unsigned int waktu_delay);
void LED_berjalan(unsigned int waktu_delay);

void main(void)
{

// Port A initialization untuk KEYPAD 4X4
// PA.0-PA3 sbg input,,  PA4-PA& sebagai Output
PORTA=0xFF;
DDRA=0xF0;

// Port B initialization
PORTB=0x00;
DDRB=0xF0;

// Port C initialization

//PORTC=0xFF;
//DDRC=0xF0;
PORTC=0x00;
DDRC=0xFF;

// Port D initialization
PORTD=0x00;
DDRD=0xB0;
// USART initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity, Baud rate: 9600
UCSRA=0x00;
UCSRB=0x18;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=0x47;

kode =0xff ;
LED_kelap_kelip(5,500);

while (1)
{

keypad();
if(kode !=0xff)
{

//================input data==========
if(digit==4) //menu pilihan
{
menu= kode;
//=======================================x
if(menu==1)
{

PORTC=menu;
putchar(48+kode);
delay_ms(waktuTekanTombol);
digit--;
putchar(13);
putchar(10);
}
else if(menu==2)
{

PORTC=menu;
putchar(48+kode) ;
delay_ms(waktuTekanTombol);
digit--;
putchar(13);
putchar(10);
}
else if(menu==3)
{

PORTC=menu;
putchar(48+kode);
delay_ms(waktuTekanTombol);
digit--;
putchar(13);
putchar(10);
}
else if(menu==4)
{

PORTC=menu;
putchar(48+kode);
delay_ms(waktuTekanTombol);
digit--;
putchar(13);
putchar(10);
}
else
{
LED_kelap_kelip(3,200);
}
//=======================================x

}
else if(digit==3) // masukan input ribuan
{
ribuan= kode;
PORTC = kode;
putchar(48+kode);
delay_ms(waktuTekanTombol);

digit--;
}
else if(digit==2)
{
ratusan = kode;
PORTC = kode ;
putchar(48+kode);
delay_ms(waktuTekanTombol);

digit--;
}
else if(digit==1)
{
puluhan = kode;
PORTC = kode;
putchar(48+kode);
delay_ms(waktuTekanTombol);

digit--;
}
else if(digit==0)
{
satuan = kode;
PORTC = kode ;
putchar(48+kode);
delay_ms(waktuTekanTombol);
putchar(10);
putchar(13);

putchar(48+menu);
putchar('@');
putchar(48+ribuan);//48+ribuan);
putchar(48+ratusan);//48+ribuan);
putchar(48+puluhan);//48+ribuan);
putchar(48+satuan);//48+ribuan);

LED_berjalan(1000);
origin();
delay_ms(waktuTekanTombol);

}

kode =0xff ; // kembalikan kode ke 0ff setiap 1 digit angka diketik (tombol tak ditekan)

} // penutup if(kode !=0xff)

} // end of while
} // end of main

 
 
//=================function definition==================
//=======================================================
void origin(void)
{ putchar(13);
putchar(10);
putchar('M');
putchar('e');
putchar('n');
putchar('u');
putchar('');
putchar('1');
putchar('-');
putchar('4');
putchar(':');
digit=4;
menu=0;
kode =0xff ;
ribuan=0;
ratusan=0;
puluhan=0;
satuan=0;
}

//============================================================
void keypad() //void untuk program keypad pada PORTA
{
PORTA.4=0;
delay_ms(3);
if (PINA.0==0) {kode=20;}
else if (PINA.1==0){kode=-13;}
else if (PINA.2==0){kode=0;}
else if (PINA.3==0){kode=-6;}

PORTA.4=1;
PORTA.5=0;
delay_ms(3);
if (PINA.0==0) {kode=19;}
else if (PINA.1==0){kode=9;}
else if (PINA.2==0){kode=8;}
else if (PINA.3==0){kode=7;}

PORTA.5=1; PORTA.6=0;
delay_ms(3);
if (PINA.0==0) {kode=18;}
else if (PINA.1==0){kode=6;}
else if (PINA.2==0){kode=5;}
else if (PINA.3==0){kode=4;}

PORTA.6=1; PORTA.7=0;
delay_ms(3);
if (PINA.0==0) {kode=17;}
else if (PINA.1==0){kode=3;}
else if (PINA.2==0){kode=2;}
else if (PINA.3==0){kode=1;}

PORTA.7=1;
delay_ms(3);
}

//============================================
void LED_kelap_kelip(char jml_looping, unsigned int waktu_delay)
{
char i;

PORTC=255;
for(i =0;i<jml_looping;i++)
{
PORTC =~PORTC;

delay_ms(waktu_delay);
}

PORTC=255;

}
//============================================

void LED_berjalan(unsigned int waktu_delay)
{
char i,data;
PORTC=255;
delay_ms(waktu_delay);
PORTC=254;
delay_ms(waktu_delay);
PORTC=253;

//255-254-253-251-247-239-223-191-127
for(i=0; i<7;i++)
{

PORTC=255-2^i;

delay_ms(waktu_delay);
}

PORTC=255;

}

Contoh Master Modbus dengan Bascom AVR

berikut ini contoh master  modbus RTU  dengan menggunakan bascom avr
compiler bascom avr  menyediakan fungsi library untuk master modbus yaitu “modbus.lbx” dan fungsi  untuk mengirim query modbus :

MAKEMODBUS(alamat slave, fucntion code, alamat register, varbts )

function code yg tersedia

  • 03 : read register

contoh

Slave Address                11
Function code                 03
alamat awal reg MSB    00
alamat awal reg  LSB      6B
jumlah reg MSB               00
jumlah reg LSB              03
CRC

  • 06 : write single register
  • 16 : write multiple register

$regfile = “m162def.dat”
$crystal = 8000000
$baud = 19200
$hwstack = 42
$swstack = 40
$framesize = 40

$lib “modbus.lbx”
Config Print1 = Portb.1 , Mode = Set

Rs485dir Alias Portb.1
Config Rs485dir = Output
Rs485dir = 0

Portc.0 = 1

‘The circuit from the help is used. See Using MAX485
‘ PB.1 data direction rs485

Config Com1 = Dummy , Synchrone = 0 , Parity = None , Stopbits = 1 , Databits = 8 , Clockpol = 0
Config Com2 = 9600 , Synchrone = 0 , Parity = Even , Stopbits = 1 , Databits = 8 , Clockpol = 0

Open “COM2:” For Binary As #1

Dim B As Byte
Dim W As Word
Dim L As Long

W = &H4567
L = &H12345678

Print “RS-485 MODBUS master”
Do
If Pinc.0 = 0 Then
Waitms 500
Print “send request to slave/server”
‘ Send one of the following three messages
‘ Print #1 , Makemodbus(2 , 3 , 8 , 2);
‘ Print #1 , Makemodbus(2 , 6 , 8 , W);
Print #1 , Makemodbus(2 , 16 , 8 , L);
End If
If Ischarwaiting(#1) <> 0 Then
B = Waitkey(#1)
Print Hex(b) ; “,”;
End If
Loop

End

sumber

http://avrhelp.mcselec.com/index.html?modbus_slaveserver.htm

Contoh pemrograman AVR dgn sensor SHT11

Gambar Sckematik

konekasi sht11 dgn AVR

 

Program AVR

/*********************************************

Project : The Sensirion SHT11 Humidity & Temperature Demo
Chip type : AT90S8535

Clock frequency : 4.000000 MHz
Memory model : Small
External SRAM size : 0
Data Stack size : 192

SHT1X Humidity and Temperature Sensor
AVR
Pin 1 GND
Pin 2 Data (PB0)
Pin 3 Serial Clock (PB1)
Pin 4 VDD (2.4V to 5.5V)

AVR PB2 – Heater On/Off Switch

Pin PB2 high – Heater On
Pin PB2 low – Heater Off

*********************************************/

#include <90s8535.h>
#include <stdio.h>
#include <delay.h>
#include <math.h>
// Alphanumeric LCD Module functions
#asm
.equ __lcd_port=0x1B
#endasm
#include <lcd.h>

// Declare your global variables here

typedef union
{ unsigned int i; float f;} value;

enum {TEMP,HUMI};

sfrb PINB = 0x16;
sfrb PORTB = 0x18;
sfrb DDRB = 0x17;

#define SHT_DATA_OUT DDRB.0
#define SHT_DATA_IN PINB.0
#define SHT_SCK PORTB.1
#define HEAT_SW PINB.2 // Heater On or Off
#define noACK 0
#define ACK 1
//adr command r/w
#define STATUS_REG_W 0x06 //000 0011 0
#define STATUS_REG_R 0x07 //000 0011 1
#define MEASURE_TEMP 0x03 //000 0001 1
#define MEASURE_HUMI 0x05 //000 0010 1
#define RESET 0x1e //000 1111 0

const float C1=-4.0; // for 12 Bit
const float C2=+0.0405; // for 12 Bit
const float C3=-0.0000028; // for 12 Bit
const float T1=+0.01; // for 14 Bit @ 5V
const float T2=+0.00008; // for 14 Bit @ 5V

typedef struct{
unsigned char second; //enter the current time, date, month, and year
unsigned char minute;
unsigned char hour;
unsigned char date;
unsigned char month;
unsigned int year;
}time;
time t;

char lcd_buffer[33];

// Function Prototypes
interrupt [TIM2_OVF] void timer2_ovf_isr(void);
char not_leap(void);

//SHT Functions
char SHT_WriteByte(unsigned char value);
char SHT_ReadByte(unsigned char ack);
void s_transstart(void);
void s_connectionreset(void);
char s_softreset(void);
char s_measure(unsigned char *p_value, unsigned char *p_checksum, unsigned char mode);
void calc_sth11(float *p_humidity ,float *p_temperature);
float calc_dewpoint(float h,float t);

char s_write_statusreg(unsigned char *p_value);
char s_read_statusreg(unsigned char *p_value, unsigned char *p_checksum);

void main(void)
{
// Declare your local variables here

value humi_val, temp_val;
unsigned char error, checksum, status;
float dew_point;

t.hour = 23;
t.minute = 30;
t.second = 00;
t.date = 22;
t.month = 8;
t.year = 2003;

// Input/Output Ports initialization
// Port A initialization
// Func0=In Func1=In Func2=In Func3=In Func4=In Func5=In Func6=In Func7=In
// State0=T State1=T State2=T State3=T State4=T State5=T State6=T State7=T
PORTA=0x00;
DDRA=0x00;

// Port B initialization
// Func0=In Func1=In Func2=In Func3=In Func4=In Func5=In Func6=In Func7=In
// State0=T State1=T State2=T State3=T State4=T State5=T State6=T State7=T
PORTB=0x00;
DDRB=0x00;

// Port C initialization
// Func0=In Func1=In Func2=In Func3=In Func4=In Func5=In Func6=In Func7=In
// State0=T State1=T State2=T State3=T State4=T State5=T State6=T State7=T
PORTC=0x00;
DDRC=0x00;

// Port D initialization
// Func0=In Func1=In Func2=In Func3=In Func4=In Func5=Out Func6=In Func7=In
// State0=T State1=T State2=T State3=T State4=T State5=0 State6=T State7=T
PORTD=0x00;
DDRD=0x20;

// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: Timer 0 Stopped
TCCR0=0x00;
TCNT0=0x00;

// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: Timer 1 Stopped
// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
TCCR1A=0x00;
TCCR1B=0x00;
TCNT1H=0x00;
TCNT1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;

// Timer/Counter 2 initialization
// Clock source: TOSC1 pin
// Clock value: PCK2/128
// Mode: Normal top=FFh
// OC2 output: Disconnected
ASSR=0x08;
TCCR2=0x05;
TCNT2=0x00;
OCR2=0x00;

// External Interrupt(s) initialization
// INT0: Off
// INT1: Off
GIMSK=0x00;
MCUCR=0x00;

// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0x40;

// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
// Analog Comparator Output: Off
ACSR=0x80;

// LCD module initialization
lcd_init(20);
lcd_putsf(“- SHT11 Monitor -“);
//sprintf(lcd_buffer,”No. of Visitors = %d”,visitor);
//lcd_gotoxy(0,2);
//lcd_puts(lcd_buffer);

// Setup Sensibus Pins

PORTB.1 = 0; // ClockLow
DDRB.1 = 1; // SCK is an output

PORTB.0 = 0; // Always Zero
// Toggle DDRB.0 for Data

s_connectionreset();

/*
while (1)
{
s_transstart(); //transmission start

error+=SHT_WriteByte(MEASURE_TEMP); //send command to sensor

for (i=0;i<65535;i++)
if(SHT_DATA_IN==0) break; //wait until sensor has finished the measurement

if(SHT_DATA_IN) error+=1; //or timeout (~2 sec.) is reached

MSB =SHT_ReadByte(ACK); //read the first byte (MSB)
LSB =SHT_ReadByte(ACK); //read the second byte (LSB)
checksum =SHT_ReadByte(noACK); //read checksum

sprintf(lcd_buffer,”T= %u %u %u”,MSB,LSB,checksum);
lcd_gotoxy(0,1);
lcd_puts(lcd_buffer);

delay_ms(500);
}
*/

while (1)
{
error=0;
// Check heater pin
if(HEAT_SW)
status = 0b00000100; // Heater On
else status = 0b00000000; // Heater Off
s_write_statusreg(&status);

error+=s_measure((unsigned char*) &humi_val.i,&checksum,HUMI);
error+=s_measure((unsigned char*) &temp_val.i,&checksum,TEMP);
if(error!=0) s_connectionreset();
else{
humi_val.f=(float)humi_val.i; //converts integer to float
temp_val.f=(float)temp_val.i; //converts integer to float
calc_sth11(&humi_val.f,&temp_val.f); //calculate humidity, temperature
dew_point=calc_dewpoint(humi_val.f,temp_val.f); //calculate dew point
sprintf(lcd_buffer,”T:%5.1fC H:%5.1f%%”,temp_val.f,humi_val.f);
lcd_gotoxy(0,1);
lcd_puts(lcd_buffer);
if (HEAT_SW)
sprintf(lcd_buffer,”DP:%5.1fC Heat On “,dew_point);
else sprintf(lcd_buffer,”DP:%5.1fC Heat Off “,dew_point);
lcd_gotoxy(0,2);
lcd_puts(lcd_buffer);
}
// Global enable interrupts
#asm(“sei”)
delay_ms(1000);
#asm(“cli”)
}

}

// Timer 2 overflow interrupt service routine
interrupt [TIM2_OVF] void timer2_ovf_isr(void)
{
// Place your code here
if (++t.second==60) //keep track of time, date, month, and year
{
t.second=0;
if (++t.minute==60)
{
t.minute=0;
if (++t.hour==24)
{
t.hour=0;
if (++t.date==32)
{
t.month++;
t.date=1;
}
else if (t.date==31)
{
if ((t.month==4) || (t.month==6) || (t.month==9) || (t.month==11))
{
t.month++;
t.date=1;
}
}
else if (t.date==30)
{
if(t.month==2)
{
t.month++;
t.date=1;
}
}
else if (t.date==29)
{
if((t.month==2) && (not_leap()))
{
t.month++;
t.date=1;
}
}
if (t.month==13)
{
t.month=1;
t.year++;
}
}
}
}
sprintf(lcd_buffer,”%02d:%02d:%02d %02d/%02d/%04d”,t.hour, t.minute, t.second, t.date, t.month, t.year);
lcd_gotoxy(0,3);
lcd_puts(lcd_buffer);
}

char not_leap(void) //check for leap year
{
if (!(t.year%100))
return (char)(t.year%400);
else
return (char)(t.year%4);
}
//———————————————————————————-
// writes a byte on the Sensibus and checks the acknowledge
//———————————————————————————-
char SHT_WriteByte(unsigned char value)
{
unsigned char i,error=0;
for (i=0x80;i>0;i/=2) //shift bit for masking
{
if (i & value) SHT_DATA_OUT=0; //masking value with i , write to SENSI-BUS
else SHT_DATA_OUT=1;
SHT_SCK=1; //clk for SENSI-BUS
delay_us(5); //pulswith approx. 5 us
SHT_SCK=0;
}
SHT_DATA_OUT=0; //release DATA-line
SHT_SCK=1; //clk #9 for ack
error=SHT_DATA_IN; //check ack (DATA will be pulled down by SHT11)
SHT_SCK=0;
return error; //error=1 in case of no acknowledge
}

//———————————————————————————-
// reads a byte form the Sensibus and gives an acknowledge in case of “ack=1″
//———————————————————————————-
char SHT_ReadByte(unsigned char ack)
{
unsigned char i,val=0;
SHT_DATA_OUT=0; //release DATA-line
for (i=0x80;i>0;i/=2) //shift bit for masking
{
SHT_SCK=1; //clk for SENSI-BUS
if (SHT_DATA_IN) val=(val | i); //read bit
SHT_SCK=0;
}
SHT_DATA_OUT=ack; //in case of “ack==1″ pull down DATA-Line
SHT_SCK=1; //clk #9 for ack
delay_us(5); //pulswith approx. 5 us
SHT_SCK=0;
SHT_DATA_OUT=0; //release DATA-line
return val;
}

//———————————————————————————-
// generates a transmission start
// _____ ________
// DATA: |_______|
// ___ ___
// SCK : ___| |___| |______
//———————————————————————————-
void s_transstart(void)
{
SHT_DATA_OUT=0;
SHT_SCK=0; //Initial state
delay_us(1);
SHT_SCK=1;
delay_us(1);
SHT_DATA_OUT=1;
delay_us(1);
SHT_SCK=0;
delay_us(5);
SHT_SCK=1;
delay_us(1);
SHT_DATA_OUT=0;
delay_us(1);
SHT_SCK=0;
}

//———————————————————————————-
// communication reset: DATA-line=1 and at least 9 SCK cycles followed by transstart
// _____________________________________________________ ________
// DATA: |_______|
// _ _ _ _ _ _ _ _ _ ___ ___
// SCK : __| |__| |__| |__| |__| |__| |__| |__| |__| |______| |___| |______
//———————————————————————————-

void s_connectionreset(void)
{
unsigned char i;
SHT_DATA_OUT=0; SHT_SCK=0; //Initial state
for(i=0;i<9;i++) //9 SCK cycles
{
SHT_SCK=1;
delay_us(1);
SHT_SCK=0;
}
s_transstart(); //transmission start
}

//———————————————————————————-
// resets the sensor by a softreset
//———————————————————————————-

char s_softreset(void)
{
unsigned char error=0;
s_connectionreset(); //reset communication
error+=SHT_WriteByte(RESET); //send RESET-command to sensor
return error; //error=1 in case of no response form the sensor
}

//———————————————————————————-
// makes a measurement (humidity/temperature) with checksum
//———————————————————————————-
char s_measure(unsigned char *p_value, unsigned char *p_checksum, unsigned char mode)
{
unsigned error=0;
unsigned int i;

s_transstart(); //transmission start
switch(mode){ //send command to sensor
case TEMP : error+=SHT_WriteByte(MEASURE_TEMP); break;
case HUMI : error+=SHT_WriteByte(MEASURE_HUMI); break;
default : break;
}
for (i=0;i<65535;i++) if(SHT_DATA_IN==0) break; //wait until sensor has finished the measurement
if(SHT_DATA_IN) error+=1; // or timeout (~2 sec.) is reached
*(p_value+1) =SHT_ReadByte(ACK); //read the first byte (MSB)
*(p_value) =SHT_ReadByte(ACK); //read the second byte (LSB)
*p_checksum =SHT_ReadByte(noACK); //read checksum
return error;
}

//—————————————————————————————-
// calculates temperature [°C] and humidity [%RH]
// input : humi [Ticks] (12 bit)
// temp [Ticks] (14 bit)
// output: humi [%RH]
// temp [°C]
//—————————————————————————————-

void calc_sth11(float *p_humidity ,float *p_temperature)
{

//float rh=*p_humidity; // rh: Humidity [Ticks] 12 Bit
//float t=*p_temperature; // t: Temperature [Ticks] 14 Bit
float rh_lin; // rh_lin: Humidity linear
float rh_true; // rh_true: Temperature compensated humidity
float t_C; // t_C : Temperature [°C]

t_C=*p_temperature*0.01 – 40; //calc. temperature from ticks to [°C]
rh_lin=C3*(*p_humidity)*(*p_humidity) + C2*(*p_humidity) + C1; //calc. humidity from ticks to [%RH]
rh_true=(t_C-25)*(T1+T2*(*p_humidity))+rh_lin; //calc. temperature compensated humidity [%RH]
if(rh_true>100)rh_true=100; //cut if the value is outside of
if(rh_true<0.1)rh_true=0.1; //the physical possible range

*p_temperature=t_C; //return temperature [°C]
*p_humidity=rh_true; //return humidity[%RH]
}

//——————————————————————–
// calculates dew point
// input: humidity [%RH], temperature [°C]
// output: dew point [°C]
//——————————————————————–

float calc_dewpoint(float h,float t)
{
float logEx,dew_point;
logEx=0.66077+7.5*t/(237.3+t)+(log10(h)-2);
dew_point = (logEx – 0.66077)*237.3/(0.66077+7.5-logEx);
return dew_point;
}

//———————————————————————————-
// reads the status register with checksum (8-bit)
//———————————————————————————-
char s_read_statusreg(unsigned char *p_value, unsigned char *p_checksum)
{
unsigned char error=0;
s_transstart(); //transmission start
error=SHT_WriteByte(STATUS_REG_R); //send command to sensor
*p_value=SHT_ReadByte(ACK); //read status register (8-bit)
*p_checksum=SHT_ReadByte(noACK); //read checksum (8-bit)
return error; //error=1 in case of no response form the sensor
}

//———————————————————————————-
// writes the status register with checksum (8-bit)
//———————————————————————————-
char s_write_statusreg(unsigned char *p_value)
{
unsigned char error=0;
s_transstart(); //transmission start
error+=SHT_WriteByte(STATUS_REG_W);//send command to sensor
error+=SHT_WriteByte(*p_value); //send value of status register
return error; //error>=1 in case of no response form the sensor
}

Pemrograman Display 7 Segment dengan SPI MAX7221 dan MAX7219

Pemrograman Display 7 Segmen dengan MAX7221 /MAX7219  via komunikasi  SPI.

Cara paling mudah memprogram display  7 segment adalah  dgn bantuan IC MAX7221 atau MAX7219.  Kita tdk perlu lagi membuat program scanning (program bergantian mengaktifkan digit ) karena semua itu dilakukan oleh ic max7221. Kita hanya mengirim sedikit perintah2 dan data ke ic tsb  via SPI dgn  format yg sudah ditentukan untuk menampilkan data  di 7 segmen. Selain itu kita bisa berhemat kaki IO  microcontroller, karena  max7221 hanya perlu 3 pin dari  microcontroller.

MAx7221 Untuk Display 7 segment dgn SPI

contoh rangkaian 7 segment dgn max7221

Kaki -kaki  SPI pada microcontroller AVR atmega

Pin isp pada Atmega AVR

Pemrograman Max7221

Untuk menampilkan data kita perlu mengirimkan format dibawah ini ke ic max7221 :

Format Data yg dikirim ke Max7221

Keterangan rincian kombinasi bit pada byte  Address gambar diatas sbb

kombinasi byte Adress untuk memilih Digit  yg aktif dan perintah

datasheetmax1

scantable

—-

testtable

Set up/inisialisasi program AVR   untuk memprogram max7221/7219

1.  mejadikan AVR sebagai master SPI, contoh pada codewizard di codevision

cvwizard_spi

2. Enable decoding mode (command 0x09)

3.  Set Limit Scan

4.  Akktifkan display (perintah 0xC)

5. Set angka tiap digit.

Adapun Langkah-langkah mengirim data(angka)  SPI ke max7221  :

1. Buat pin CS menjadi Low

2. Kirim data dengan format data diatas  ( 2 byte)

3. Buat pin CS kembali High

Contoh Code Program dengan   bahasa C AVR Studio:

#include<avr/io.h>
#define MOSI 5   //(PortB.5)  data out
#define SCK 7    //(PortB.7)
#define SS 4     //(PortB.4)

void kirimbyte(unsigned char perintah, unsigned char data)
PORTB =PORTB & ~(1<<SS)  //pin  SS dibuat LOW

//kirim byte pertama (perintah)
SPDR = perintah;
while(!(SPSR & (1<<SPIF));//tunggu transfer 1 byte sampai  selesai

//kirim byte kedua(data)
SPDR = data;
while(!(SPSR & (1<<SPIF)); //tunggu transfer 1 byte sampai  selesai

PORTB =PORTB | (1<<SS);        //pin SS dibuat  High
}

int main(void)
{
//setting SPI
DDRB = (1<<MOSI) | (1<<SCK) | (1<<SS); //set bit Mosi & sck sbg output
SPCR = (1<<SPE) | (1<<MSTR) | (1<<SPR0) //AVR sebagai master SPI

kirimbyte(0x09,0xFF);// mengaktifkan  8 digit 7segmen
//jika cuma 2 digit : kirimbyte(0x9,0x3);

kirimbyte(0x0B,0x08);   //scan (looping) 8 digit
kirimbyte(0x0C,0x07);   //aktifkan Chip

//menampilkan angka

Kirimbyte(0x01,0x8);  //menampilkan angka 8 di digit 1
Kirimbyte(0x02,0x9);  //menampilkan angka 9 di digit 2
Kirimbyte(0x04,0x7);  //menampilkan angka 7 di digit 3
Kirimbyte(0x08,0x5);  //menampilkan angka 5 di digit 4
// dan seterusnya....

while(1);

return 0;

}

Adapun cara pengiriman data melaui SPI dgn Codevision :  SPI(char data)

lebih lengkapnya Anda bisa baca disini dan   disini.

Rangkaian Cascade 

Jika kita ingin membuat dua buah baris  atau lebih display maka kita bisa membuatnya dengan menyambung ic Max7221  atau max7219 secara cascade sbb:

cascademax7221_7219

perhatikan pin chip select(load) kedua ic  disambung . karena memang  kedua ic ini bekerja  secara bersama.

cascaderegister

Referensi:

- Datasheet max7221

-microcontroller AVR C & asembly, muhammmad ali mazidi

Mengirim Sms Melalui Modem (HP) GSM dengan C#

Tujuan dari Artikel ini : - Anda Bisa mengirimkan data yg dikumpulkan dari micon (data produksi,data sensor dll) melaui modem gsm  kepada user dengan media  SMS

kirim data via sms

Untuk Mengirim sms  melalui modem GSM dengan bahasa pemrograman C# saat  sudah cukup  mudah, karena telah banyak yang menyediakan Class library untuk menghubungkan modem GSM . Kita bisa menggunakan fungsi/methode  dari class tsb dgn mudah . dibawah ini saya berikan satu contoh  Class library   .NET  yaitu GSMComm.

Modem GSM yang anda bisa gunakan Baik yang bertype GSM modem USB atau  modem GSM yang terdapat di Handphone anda.  saya sudah coba pada keduanya dan berhasil dengan baik. caranya pun cukup mudah.

MODEM GSM USB

GSM modem  USB yang saya gunakan  bermerk Mobinil Manufacturer: huawei ,Model: E153 saya beli harganya 200rb-an. dan percobaan kedua saya gunakan Hanphone  bermerk NOKIA type clasic 3110   via bluetooth.

tahapan membuat Aplikasi

1. Download GSMcomm for NET  (termasuk contoh aplikasinya) , file hasil download : GSMCommnet86.msi  . Install file tsb sampai selesai. Lokasi  class library maupun project contoh ada di  C:\Program Files\ GSMComm NET 2.

bukalah file  project contoh C# tsb .

untuk melihat no PORT modem anda , klik kanan my computer -> properties->device manager:

melihat NO PORT Modem GSM pada device Manager

No Port diatas diperlukan ketika anda akan menghubungkan PC dengan Modem GSM baik pada project contoh ataupun aplikasi yang anda akan buat.

2.  Untuk  aplikasi baru Hubungkan class library GSMcomm di reference pada aplikasi .NET anda  dgn add references.  Lokasinya ada di C:\Program Files\GSMComm for .NET 2.0 

Menghubungkan Aplikasi dgn class library GSMComm

Kode Program mengirim SMS  dengan C#

using GsmComm.PduConverter;

using GsmComm.PduConverter.SmartMessaging;

using GsmComm.GsmCommunication;

using GsmComm.Interfaces;

using GsmComm.Server;

privatevoid button1_Click(object sender, EventArgs e)

{

Cursor  .Current = Cursors.WaitCursor;

// Send an SMS message

SmsSubmitPdu pdu;

string smsc = chkSMSC.Checked ? txtSMSC.Text : string.Empty;

// The straightforward version

pdu = newSmsSubmitPdu(txtMessage.Text, txtNumber.Text, smsc);

comm.SendMessage(pdu);

Cursor.Current = Cursors.Default;

}

Mengirim sms  dengan AT command  

Alternatif selain  menggunakan Library GSMcomm for NET  yg telah dibahas atas anda dpt  membuat sendiri pengontrolan modem dgn At command  melalui program C# anda  ,  potongan kode program berikut  untuk  mengirim sms  dgn  C#

Serialport.Write( “AT” + “\r”);

Serialport.Write( “AT+CMGF=1″ + “\r”);

Serialport.Write( “AT+CMGS=”+6285695341050″ + “\r” + “isi pesan ” +

char.ConvertFromUtf32(26) + “\r” );

dasar dasar AT Command bisa dibaca disini:

http://pccontrol.wordpress.com/2012/02/13/pengetahuan-dasar-mengirim-menerima-sms-melalui-mikrokontroler-dgn-at-command-modem-gsm/

Contoh Code Master Modbus RTU dengan C# (FC03)

Master Modbus RTU untuk  memberi perintah  Slave Modbus RTU  khususnya untuk function Code 03 , yaitu untuk membaca data register slave RTU microcontroller pada artikel sebelumya.

Tampilan Menu Utama

Modbus Master  untuk function code 03 dan 04

Kode program dengan C#:

//sebelumnya anda drag and drop komponen serial comm ke form dan ganti namanya menjadi  serialPort1.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace SimpleSerial
{
    public partial class Form1 : Form
    {

      
        string RxString_Respon_dari_slave;
private void buttonStart_Click(object sender, EventArgs e)
        {
            serialPort1.PortName = "COM1";
            serialPort1.BaudRate = 9600;

            serialPort1.Open();
            if (serialPort1.IsOpen)
            {
                buttonStart.Enabled = false;
                buttonStop.Enabled = true;
                textBox1.ReadOnly = false;
            }
        }
 private void buttonStop_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                buttonStart.Enabled = true;
                buttonStop.Enabled = false;
                textBox1.ReadOnly = true;
            }

        }
private void button2_Click(object sender, EventArgs e)
        {

            
            byte[] CRC = new byte[2];
            byte[] message = new byte[8];
            ushort start = Convert.ToUInt16(textAlamatAwal.Text);
            ushort reg_qty = Convert.ToUInt16(textJumlahRegister.Text);
            // jika port belum di open , keluar
            if (!serialPort1.IsOpen) return;
            //Clear in/out buffers:
            serialPort1.DiscardOutBuffer();
            serialPort1.DiscardInBuffer();

            message[0] = Convert.ToByte(txtalamat.Text);
            message[1] = Convert.ToByte(textFunctionCode.Text); 

            message[2] = (byte)(start >> 8);
            message[3] = (byte)start;

            message[4] = (byte)(reg_qty >> 8);
            message[5] = (byte)reg_qty;

            HitungCRC(message, ref CRC);
            message[message.Length-2] = CRC[0];
            message[message.Length-1] = CRC[1];
        //tampilkan hasil CRC ke textbox
            textCRC.Text = CRC[1].ToString() + " " + CRC[0].ToString();
            textCRCHigh.Text = CRC[1].ToString();
            textCRCLow.Text = CRC[0].ToString();
            //kirim data di buffer message ke serial port
            serialPort1.Write(message, 0, message.Length);

        }
//tampilkan data respon dari slave
 private void DisplayText(object sender, EventArgs e)
        {
textBox1.AppendText(RxString_Respon_dari_slave);

        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            RxString_Respon_dari_slave = serialPort1.ReadExisting();

            this.Invoke(new EventHandler(DisplayText));
        }

 private void HitungCRC(byte[] message, ref byte[] CRC)
        {
           

            ushort CRCFull = 0xFFFF;
            byte CRCHigh = 0xFF, CRCLow = 0xFF;
            char CRCLSB;

            for (int i = 0; i < (message.Length) - 2; i++)
            {
                CRCFull = (ushort)(CRCFull ^ message[i]);

                for (int j = 0; j < 8; j++)
                {
                    CRCLSB = (char)(CRCFull & 0x0001);
                    CRCFull = (ushort)((CRCFull >> 1) & 0x7FFF);

                    if (CRCLSB == 1)
                        CRCFull = (ushort)(CRCFull ^ 0xA001);
                }
            }
            CRC[1] = CRCHigh = (byte)((CRCFull >> 8) & 0xFF);
            CRC[0] = CRCLow = (byte)(CRCFull & 0xFF);
        }

Contoh Penggunaan Dasar Sensor Gas TGS2602 dgn Microcontroller AVR Atmega8535

Sensor Figaro TGS 2602 :

The Figaro 2600 series is a new type thick film metal oxide  semiconductor, screen printed gas sensor which offers
miniaturization and lower power consumption. The TGS 2602 has high sensitivity not only to air contaminants which are emitted
by cigarette smoke, but also to low concentrations of odorous gases such as ammonia and H2S generated from waste materials
in office and home environments.

Sensor Gas

Spesifikasi

Spesifikasi

Spesifikasi TGS6202

Circuit

Rangkaian dan rumus

Gas Polutan akan merubah2 nilai Rs , untuk mendapatkan nilai Rs kita dapat dari tegangan Vout atau tegangan pada RL (VRL).

RL =10kohm ,VC 5 volt , Vout tegangan output yang di masukan ke ADC.

Contoh Rangkaian:

Contoh rangkaian sensor ke Microcontroller Atmega8535

 

Untuk contoh program ADC  microcontoller atmega8535   Anda bisa lihat contoh  disini :

http://pccontrol.wordpress.com/2011/06/05/contoh-adc-atmega8535-dgn-resolusi-10-bit/

referensi ;

Contoh Code Slave Modbus dengan Microcontroller AVR Atmega8535 dgn bahasa C codevision

Pada Artikel ini saya mencoba  membuat Slave  untuk protokol Modbus dengan microcontroller Atmega8535 dengan bahasa C CodeVision.  Saya berharap bagi anda yang sudah mengerti atau  pernah membuat , bisa memberikan masukannya demi kemajuan kita semua.

Untuk mengerti  tentang modbus RTU atau ASCII anda sebaiknya sudah mengerti pemrograman RS232 /  RS485 . anda bisa baca pada artikel lainya pada blog ini.

Kita akan membuat  Slave dengan function Code 03 dan 04 yaitu   fungsi untuk membaca data (register)  pada slave ,  sebagai masternya  adalah program di PC dengan C# .

Untuk versi awal ini saya tidak menggunakan timeout spt yg dipersyaratkan oleh Modbus , untuk menghindari kerumitan.

Konsep dasar  modbus RTU.

master-slave-modbus

master-slave-modbus function code 03 atau 04

Program Master Pada PC

Slave Modbus hanya bersifat menungu perintah dari master , maka  sebelumnya kita harus membuat program sbagai Master  pada PC untk mengirim query /perintah. Perintah master disebut query dan jawaban slave disebut respon.

Program pd PC akan kita buat dgn C#, program ini  akan berfungsi:

1. Mengirim Perintah (query)  ke Slave.

2. Menerima Respon dari Slave.

Berikut ini contoh kode program mengirim perintah/query dengan C# :

pembahasan contoh  master RTU lengkapnya bisa baca di artikel ini

private SerialPort serialcomm1 = new SerialPort();

private void open_com_Click()
{
                serialcomm1.PortName = "COM1";
                serialcomm1.BaudRate = 9600;
                serialcomm1.DataBits = 8;
                serialcomm1.Parity = Parity.None;
                serialcomm1.StopBits = StopBits.One;

                serialcomm1.ReadTimeout = 1000;
                serialcomm1.WriteTimeout = 1000;
                serialcomm1.Open();
}
private void KirimPerintah(ref byte[] framedata)
        {

            byte[] CRC = new byte[2];
            ushort alamat _awal = Convert.ToUInt16(txtAlamat_Awal_Register.Text)
            ushort jumlah_register = Convert.ToUInt16(txtJumlah_Register.Text);
                //Clear  buffers:
                serialcomm1.DiscardOutBuffer();
                serialcomm1.DiscardInBuffer();
                //Perintah Function Code 03 selalu  8 byte:
                byte[] framedata = new byte[8];

            framedata[0] =Convert.ToByte(txtAlamatSlave.Text);
            framedata[1] = 0x03 ; //FuctionCode
            framedata[2] = (byte)(alamat_awal >> 8);    // MSB starting address
            framedata[3] = (byte)alamat_awal;           // LSB
            framedata[4] = (byte)(jumlah_register >> 8);  //MSB
            framedata[5] = (byte)jumlah_register;         //LSB
            GetCRC(framedata, ref CRC);
            framedata[framedata.Length - 2] = CRC[0];
            framedata[framedata.Length - 1] = CRC[1];

             //kirim perintah/query  ke slave
                    serialcomm1.Write(framedata, 0, framedata.Length);

            }

//fungsi menghitung Error Check ( CRC16 )
 private void GetCRC(byte[] framedata, ref byte[] CRC)
        {

            ushort CRCFull = 0xFFFF;
            byte CRCHigh = 0xFF, CRCLow = 0xFF;
            char CRCLSB;

            for (int i = 0; i < (message.Length) - 2; i++)
            {
                CRCFull = (ushort)(CRCFull ^ message[i]);

                for (int j = 0; j < 8; j++)
                {
                    CRCLSB = (char)(CRCFull & 0x0001);
                    CRCFull = (ushort)((CRCFull >> 1) & 0x7FFF);

                    if (CRCLSB == 1)
                        CRCFull = (ushort)(CRCFull ^ 0xA001);
                }
            }
            CRC[1] = CRCHigh = (byte)((CRCFull >> 8) & 0xFF);
            CRC[0] = CRCLow = (byte)(CRCFull & 0xFF);
        }

Anda bisa juga membuat program mengirim data tetap buat testing saja
contoh data :

  • 01 05 00 01 00 02 CB  1D    //data ini a kan memberi memberi fuction eror
  • 01 03 00 01 00 02   CB 95  // data yg ok FC=03

data data tsb akan ditampilkan di LCD2x16 dlm bentuk desimal.

private void button2_Click(object sender, EventArgs e)       
 {

            byte[] message = new byte[9]; 

            message[0] = 0x01; //address;
            message[1] = 0x03;//FC03;

            message[2] = 0x00;//START ADRESS MSB ;
            message[3] = 0x01;  //START ADRESS LSB;

            message[4] = 0x00;  //QTY REGISTER MSB;
            message[5] = 0x02;  //QTY REGISTER LSB;

            message[6] = 0x95; //   CRC LOW             
            message[7] = 0xCB; //   CRC High

           serialcomm1.Write(message, 0, message.Length);
                    }

Berikut ini contoh program untuk Microcontroller Atmega8535 dgn C codevision:  (maaf  belum selesai)

/*

fungsi usart_rx_isr()   -> untuk menerima data dan simpan di rx_buffer

fungsi kirim_data_isr()   -> untuk mengirim data array di tx_buffer

fungsi main()    -> fungsi  utama terus menerus mengecek data rx_buffer yg datang.

fungsi  checkframedata()   -> fungsi  yg  memeriksa  alamat , fungsi 03 dan crc

fungsi baca_register()   -> fungsi untuk membaca  alamat  register yg dituju

fungi get_crc();    -> fungsi untuk menghitung nilai CRC dari frame datang atau yg akan dikirim.

/*****************************************************

Date    : 6/30/2011
Author  : PCCONTROL.WORDPRESS.COM
Company :
Comments: Slave Modbus RTU 

Chip type           : ATmega8535
Program type        : Application
Clock frequency     : 4.000000 MHz
Memory model        : Small
External SRAM size  : 0
Data Stack size     : 256
*****************************************************/

#include <mega8535.h>
#include <math.h>
#include <delay.h>
// Alphanumeric LCD Module functions
#asm
   .equ __lcd_port=0x15 ;PORTC
#endasm
#include <lcd.h>
#include <string.h>
#include <stdio.h>

#define RXB8 1
#define TXB8 0
#define UPE 2
#define OVR 3
#define FE 4
#define UDRE 5
#define RXC 7

#define FRAMING_ERROR (1<<FE)
#define PARITY_ERROR (1<<UPE)
#define DATA_OVERRUN (1<<OVR)
#define DATA_REGISTER_EMPTY (1<<UDRE)
#define RX_COMPLETE (1<<RXC)

unsigned char	sendBuf[32],localAddr = 0x1;
// USART Receiver buffer
#define RX_BUFFER_SIZE 30
unsigned char rx_buffer[RX_BUFFER_SIZE],rx_counter;

//char tampung3[16]; 

unsigned char CRC[2],CRCLow,CRCHigh;
unsigned char tampung1[10];
unsigned char tampung2[10];
unsigned char tampung3[10];
unsigned char data0[10];
unsigned char data1[10];
unsigned char data2[10];
unsigned char data3[10];
unsigned char data4[10];
unsigned char data5[10];
unsigned char data6[10];
unsigned char data7[10];
//unsigned char data8[10];

unsigned char r_ready; 

void GetCRC(char message[], char panjangdata);
unsigned char rx_wr_index,tx_wr_index;

void checkframedata();
void readRegisters();
int getRegisterVal(int addr,int *tempData);
int testRegister; 

// USART Receiver interrupt service routine
interrupt [USART_RXC] void usart_rx_isr(void)
{
char status,data;
status=UCSRA;
data=UDR;
if ((status & (FRAMING_ERROR | PARITY_ERROR | DATA_OVERRUN))==0)
   {
      if(rx_wr_index <= 7)  // 0 sampai 7
      {  

      rx_buffer[rx_wr_index]=data;
      rx_wr_index++;
      }
      else
      {
       lcd_clear();
       sprintf(tampung3,"%i",rx_wr_index);
       lcd_gotoxy(15,1);
       lcd_puts(tampung3); 

       GetCRC(rx_buffer,rx_wr_index-2);

       rx_wr_index=0;
       r_ready=1;
       UCSRB.7=0;
      }

   };
}

void main(void)
{

// USART initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART Receiver: On
// USART Transmitter: On
// USART Mode: Asynchronous
// USART Baud rate: 9600
UCSRA=0x00;
UCSRB=0x98;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=0x19;

// LCD module initialization
lcd_init(16);
lcd_gotoxy(0,0);
lcd_putsf("MODBUS SLAVE FC3");
// Global enable interrupts
#asm("sei")

 r_ready=0;
 rx_wr_index=0;
 UCSRB.7=1;  

while (1)
      {
      // Place your code here

        //ambil parameter
        if(r_ready==1)  //==============
           {  

             checkframedata(); 

           } 

      }; //end of while(1)
}     //end of main

        void GetCRC(char message[], char panjangdata)
       // unsigned  int GetCRC(char message[], char panjangdata)
        {
            //Function expects a modbus message of any length as well as a 2 byte CRC array in which to
            //return the CRC values:
           unsigned char i,j;
            unsigned int  CRCFull = 0xFFFF;
         //  unsigned char CRCHigh = 0xFF, CRCLow = 0xFF;
           unsigned  char CRCLSB;

            for (i = 0; i < (panjangdata) ; i++)
            {
                CRCFull = (CRCFull ^ message[i]);

                for ( j = 0; j < 8; j++)
                {
                    CRCLSB = (CRCFull & 0x0001);   //ambil LSB
                    CRCFull = ((CRCFull >> 1) & 0x7FFF);  // geser 

                    if (CRCLSB == 1)
                        CRCFull = CRCFull ^ 0xA001;
                }
            }
            CRC[1] = CRCHigh = ((CRCFull >> 8) & 0xFF);
            CRC[0] = CRCLow = (CRCFull & 0xFF); 

           return ;//0 ; //CRCFull;
        }

  void checkframedata()
  {  

      //untuk mendebug tampilkan Data di baris pertama dan CRC di baris ke dua  LCD 2x16
        sprintf(data0,"%i",rx_buffer[0]); //01
        lcd_gotoxy(0,0);
        lcd_puts(data0); 

        sprintf(data1,"%i",rx_buffer[1]); //03
        lcd_gotoxy(3,0);
        lcd_puts(data1);

        sprintf(data2,"%i",rx_buffer[2]); //00
        lcd_gotoxy(6,0);
        lcd_puts(data2);

        sprintf(data3,"%i",rx_buffer[3]); //01
        lcd_gotoxy(9,0);
        lcd_puts(data3);

        sprintf(data4,"%i",rx_buffer[4]); //00
        lcd_gotoxy(12,0);
        lcd_puts(data4);

        sprintf(data5,"%i",rx_buffer[5]); //02
        lcd_gotoxy(14,0);
        lcd_puts(data5);
        // tampilkan nilai CRC kiriman dari PC

        sprintf(data6,"%i",rx_buffer[6]); //123
        lcd_gotoxy(0,1);
        lcd_puts(data6);

        sprintf(data6,"%i",rx_buffer[7]); //123
        lcd_gotoxy(3,1);
        lcd_puts(data6);

        //Tampilkan Nilai CRC hasil hitungan Microcontroller
        sprintf(tampung1,"%i",CRC[1]);
        lcd_gotoxy(7,1);
        lcd_puts(tampung1);  

        sprintf(tampung2,"%i",CRC[0]);
        lcd_gotoxy(10,1);
        lcd_puts(tampung2);  

	if(rx_buffer[0]==0x01)  // alamat slave ini = 01
	 {
	  if(CRC[1] == rx_buffer[7] && CRC[0]==rx_buffer[6])
	{
	  	if(rx_buffer[1] == 0x03)
	  	{
	  	 lcd_gotoxy(14,1);
	         lcd_putsf("ok");
	        readRegisters();
		}
		 else if(rx_buffer[1] != 3)
		 {
		 lcd_gotoxy(0,1);
		 lcd_putsf("Fuction Error ");
		 }
	  }
         else
          {
          lcd_gotoxy(0,1);
	  lcd_putsf("CRC error    ");
          }

         }											

   r_ready=0;
   rx_wr_index=0;
   UCSRB.7=1;
  }       

void readRegisters(void)
{
	unsigned char addr;
	unsigned char tempAddr;

	unsigned int crcData;
	unsigned char readCount;
	unsigned char byteCount;

	unsigned int i;
	unsigned int tempData = 0;	

	//addr = (receBuf[2]<<8) + receBuf[3];
	//tempAddr = addr & 0xfff;
	addr = rx_buffer[3];
	tempAddr = addr;

	//readCount = (receBuf[4]<<8) + receBuf[5];	//?????
	readCount = rx_buffer[5];

	byteCount = readCount * 2;

	for(i=0;i<byteCount;i++)
	{     tempAddr++;
		getRegisterVal(tempAddr,&tempData);
		sendBuf[2*i+3] = tempData >> 8;
		sendBuf[2*i+4] = tempData & 0xff;
	}

	sendBuf[0] = localAddr;
	sendBuf[1] = 3;
	sendBuf[2] = byteCount;
	byteCount = byteCount + 3;
	GetCRC(sendBuf,byteCount);;
	sendBuf[byteCount] = crcData >> 8;
	byteCount++;
	sendBuf[byteCount] = crcData & 0xff;

	tx_wr_index = byteCount + 1;
	//beginSend();
}//void readRegisters(void)

int getRegisterVal(int addr,int *tempData)
{
	 int result = 0;

	switch(addr & 0xff)
	{
		case 0:
		        	*tempData = testRegister;
				break;
		case 1:
				break;

		default:
				break;
	}

	return result;
}

tobe continue….

referensi:

http://chinahack.com

http://www.modbus.pl/Microchip.html

Pengaturan Daya Listrik Bolak Balik ( AC ) oleh Microcontroller menggunakan TRIAC

Pengaturan daya listrik  bolak balik / AC  dapat dilakukan dengan menggunakan  TRIAC .

.

Arus Gate hanya diperlukan untuk menghubungkan MT1 dan MT2, setelah itu MT1 akan tetap terhubung ke MT2 meskipun sudah tidak ada arus gate lagi. Pemberian arus gate sesaat untuk menghubungkan MT1 dan MT2 dikatakan sebagai penyulutan / men-triger TRIAC.  Pada saat  arus beban menjadi lebih kecil dari arus triger TRIAC , TRIAC akan menjadi OFF yaitu   ketika sinyal AC pada posisi 0.

Pengaturan daya dilakukan dengan cara merubah besaran phase listrik AC. dengan cara mengatur waktu penyulutan TRIAC oleh microcontroller.

waktu triger Triac diatur oleh microcontroller

Zero crossing Detektor untuk  menentukan titik  nol sinyal Ac untuk memulai delay ,  ia akan  menginterupsi  microcontroller  saat sinyal AC pada posisi 0.  misal yg kita pakai INT0 (interup ekternal 0).

Jadi tahapanya sebagai berikut:

1.  Pada saat sinyal Ac  menuju titik o  , maka zero crosing detektor memberi sinyal interupsi ke pin INT0 microcontroller.

2.  Microcontroller mejalankan  program interupt servis rutin INT0.

Program servis rutin  INT0 berisi  delay dan output untuk men triger gate TRIAC. Besarnya nilai delay menentukan daya yg disalurkan oleh TRIAC. Contoh dibawah ini  besarnya delay 5 ms. artinya setelah 5 ms micon akan mentriger TRIAC .

Beberapa gambaran hasil pengaturan daya listrik bolak balik / AC :

 

Beberapa hasil output pengaturan daya dgn TRIAC

 

ini salah satu contoh aplikasi  :

http://www.avrprojects.info/avr-projects/digital-dimmer-using-atmega8/

referensi:

MICROCONTROLLER AND TRIACS 

Dimming AC Incandescent Lamps Using A PIC10F200

Program DFA Sederhana dengan bahasa C

/* 
Contoh Program DFA sederhana , untuk parsing  
 buat file testdfa misal isinya spt ini:
   a  b
>0 1  0
 1 2  0
*2 0  3

*/

#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

char  transfer(char state, char huruf, char state_x[],char state_y[]);

main()
{
FILE *fp;
char baris[20], kar1[5], kar2[5], kar3[5],stringmasukan[10],state_a[5],state_b[5],state_cur[5];
char matrik[20][3];
int  i, s, f ,j;

fp=fopen("testdfa","r");
if (fp==NULL) {
    printf("file tdk bisa dibuka\n");
    exit(1);
}
/*
if(argc!=3) {
    printf("You forgot to enter a filename.\n");
    exit(1);
  }

  if((fp=fopen(argv[1], "r"))==NULL) {
    printf("Cannot open source file.\n");
    exit(1);
  }

*/

//printf(" %s\t %s\t %s\n ", argv[1], argv[2],argv[3])

printf("\n");

printf("==========================\n");

printf("data tabel transfer DFA : \n");

printf("==========================\n");

i= 0;
while (fgets(baris,sizeof baris,fp)!=NULL) {    // baca tiap baris  sampai fp ga ada char/null

//printf("data baris= %d = %s",i,baris);

sscanf(baris,"%s %s %s",kar1,kar2,kar3);   // salin string tiap baris ( dipisah spasi)ke variable
printf("%s",baris);

      if (strstr(kar1,">")!=NULL)  s=i;
      if (strstr(kar1,"*")!=NULL)  f=i;

state_cur[i]=kar1[0];
state_a[i]=kar2[0];
state_b[i]=kar3[0];
/*
printf("state_cur[i] = %c\t",state_cur[i]);
printf("state_a[i] = %c\t",state_a[i]);
printf("state_b[i] = %c\n",state_b[i]);
*/
i++;
}

//printf("index s f = %d  %d\n", s,f);
//printf("Start State Is = %c | Final State Is = %c\n",state_cur[s], state_cur[f]);
printf("start state = %c \n",state_cur[s]);
printf("Final state = %c\n", state_cur[f]);

char start_state = state_cur[s];
printf("\n");

printf("==========================================\n");
printf("masukan string:(max 10 huruf kecil a,b ) : ");
fgets(stringmasukan,sizeof stringmasukan,stdin);
//printf("data yg anda masukan = %s jml huruf= %d\n ",stringmasukan,strlen(stringmasukan)-1);
printf("==========================================\n");

int k = strlen(stringmasukan)-1;
int m=0;
char last_state = start_state;

for(m=0;m<k;m++)
{
 char cur_huruf = stringmasukan[m];
last_state = transfer(last_state,cur_huruf,state_a,state_b);
printf("input : %c\t",cur_huruf);
printf("menuju state => : %c\n",last_state);
}
printf("==========================================\n");

printf("state akhir : %c\n\n\n",last_state);

if(last_state== state_cur[f]) {
printf("###################\n");
printf("# string diterima #\n");
printf("###################\n\n\n"); }
else{
printf("###################\n");
printf("# string di TOLAK #\n");
printf("###################\n\n\n"); }

return(0);
}

char transfer(char state, char huruf ,char state_x[],char state_y[])
{
char current_state;
//extern state_a,state_b;
int indek;

 switch (state)
{
        case '0' : indek=0 ; break;
        case '1' : indek=1 ; break;
        case '2' : indek=2 ; break;
        case '3' : indek=3 ; break;
}

if(huruf== 'a')
{ current_state = state_x[indek]; }

if(huruf== 'b')
{
current_state = state_y[indek];
}

return (current_state);

}
Follow

Get every new post delivered to your Inbox.

Join 62 other followers