How can I write data to int value in plc with Python

5.6k views Asked by At

my code:

import snap7.client as s7

ip = '192.168.0.7'
rack = 0
slot = 1
data_blok = 100
start_adress = 0
size = 260
try:
    plc = s7.Client()
    plc.connect(ip, rack, slot)
    con = plc.get_connected()
    print(f"Bağlantı Durumu: {con}")

    db = plc.db_read(data_blok, start_adress, size) //read

    name = db[0:256].decode('UTF-8').strip('\x00')
    print(f'Data AA: {name}')
    value = int.from_bytes(db[256:258], byteorder='big')
    print(f'Data BB: {value}')
    boll = bool(db[258])
    print(f'Data CC: {boll}')
except:
    print("hata")

output:

Bağlantı Durumu: True
Data AA: HELLO WORD //string
Data BB: 55 //int
Data CC:True //bool
Process finished with exit code 0 ...

///////////////////////////////////////////

How can I change the integer value here ??
plc.db_write(?????????)

2

There are 2 answers

0
Barış Aktaş On BEST ANSWER

I know that its late but this discussion helped me maybe() it will be helpful for someone else.

You should first use set_int() function from snap7.util to change the integer value in your bytearray as:

 your_int_value = 219
  
 snap7.util.set_int(db, 256, your_int_value)

This takes your bytearray "db", and writes the integer value "your_int_value" starting from the byte with index 256.

Secondly you should send the modified bytearray "db" back to plc as:

plc.db_write(data_blok, start_addres, db)

What this does is to write the bytearray "db" to the data block with number "data_blok" starting from the byte with index "start_addres"

Also here are my functions for writing a spesific data type to plc:

plc = snap7.client.Client()

#PLC'ye yazma fonksiyonları
def write_bool(db_num,start_byte,boolean_index,bool_value): #Bool yazma 
    data = bytearray(1)
    snap7.util.set_bool(data,0,boolean_index,bool_value)
    plc.db_write(db_num,start_byte,data)

def write_byte(db_num,start_byte,byte_value): #Byte yazma 
    data = bytearray(1)
    snap7.util.set_byte(data,0,byte_value)
    plc.db_write(db_num,start_byte,data)

def write_int(db_num,start_byte,int_value): #Integer yazma 
    data = bytearray(2)
    snap7.util.set_int(data,0,int_value)
    plc.db_write(db_num,start_byte,data)  

def write_real(db_num,start_byte,real_value): #Real yazma 
    data = bytearray(4)
    snap7.util.set_real(data,0,real_value)
    plc.db_write(db_num,start_byte,data)

Just give the Data Block number to "db_num", byte index for the starting byte for writing to "start_byte", and real, byte, int or boolean value for the corresponding function.

0
Tolga Cakir On

Firstly, you need to manipulate your buffer. (db named variable).

client.db_write(data_blok, start_adress, size, db)

https://github.com/gijzelaerr/python-snap7/blob/master/example/example.py