Skip to content

Commit

Permalink
Arduino Control
Browse files Browse the repository at this point in the history
Include write_struct.py to control machine arduinos
Can send and receive data.
  • Loading branch information
Shellowb committed Jun 29, 2021
1 parent af134f0 commit 04a15f5
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
11 changes: 9 additions & 2 deletions biomixer_interface/back_end/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from .models import *
import PIL
from .forms import MaterialFormSet, Labels

from biomixer_interface.arduino.write_struct import MachineCmd

class HomePage(View):
"""
Expand Down Expand Up @@ -120,7 +120,14 @@ def post(self, request):
value_list.append(answer['value'])
material_index.append(i+1)
i += 1

# BEGIN ARDUINO
# SEND Values
machine = MachineCmd(port='/dev/ttyACM0') # Hay que poner el port que vayan a usar aquí
machine.set_values(d1=value_list[0], d2=value_list[1],
d3=value_list[2], d4=value_list[3])
machine.serialize()
print(machine.read())
# END ARDUINO
return render(request, 'mixing.html', context={'materials_and_index': zip(material_list, material_index),
'materials': material_list,
'values': value_list})
Expand Down
37 changes: 37 additions & 0 deletions biomixer_interface/biomixer_interface/arduino/write_struct.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# -*- coding: utf-8 -*

import serial
import struct
from io import BytesIO


class MachineCmd(object):
"""
define the structure of the data, little-endian
h is for 2 byte integer, see the full list here https://docs.python.org/3/library/struct.html#format-characters
add as many data types as you want to send to arduino
"""

_struct = struct.Struct('<hhhh')

def __init__(self, port='/dev/ttyUSB0'):
self.arduino = serial.Serial(port, 9600)
self.buffer = BytesIO()
self.d1 = 0
self.d2 = 0
self.d3 = 0
self.d4 = 0

def serialize(self):
self.buffer.write(self._struct.pack(self.d1, self.d2, self.d3, self.d4))

@staticmethod
def to_hex(data):
return ":".join("{:02x}".format(c) for c in data)

def set_values(self, d1=0, d2=0, d3=0, d4=0):
pass

def read(self):
return bytearray(self.buffer.getvalue())

0 comments on commit 04a15f5

Please sign in to comment.