当前位置:网站首页>Scratch graphical programming operation hardware
Scratch graphical programming operation hardware
2022-07-21 22:17:00 【alading20160112】
One , brief introduction
scratch It is a graphical programming software developed by MIT , This software provides the ability to use javascript And scratch Interface of interaction , It also provides a socket Ports and a series of commands interact with Applications , Here we explain how to pass python And scratch Interaction
Two , explain
The reason for choosing python It is mainly based on the following reasons :
1,python Is a non compiled language , So unless the provider of the library will not want open source code written in C/C++, perhaps java And other compiled language code , And then through python call , In general, we can see the source code
2,scratch For the use of python Interact with it , Have a ready-made python Library can be called , So we don't need to know in detail scratch The cumbersome command structure defined externally , It doesn't make sense
3、 ... and , principle
1, When scratch When starting, the machine will be turned on by default 42001 The port is used as the server side socket Receive application requests ( This port Just the default , You can modify )
2, We go through local socket Connect to scratch, Then you can send a series of commands and scratch Interaction , So we can go through scratch Graphical programming operates anything we want to operate , Like hardware
Four , Environment configuration
explain : I do ubuntu below , Can be in similar linux It's all right on the distribution
1, install scratch: Be careful to install 1.4 Version of , What I installed on my machine with the following command is 1.4, If someone installs something other than 1.4 edition , I can't promise for the time being
sudo apt-get install scratch
2, install scratch Of python library
sudo apt-get install python-pip scratchpy
3, After installation, there is a scratch.py Of python Script , You can see scratch.py Code for , This is provided through python operation scratch All interfaces and commands
5、 ... and ,scratch.py Provided interface
The following post scratch.py Part of the code we use here : You can see if you are interested scratch.py Source code
import array
import errno
import itertools
import socket
import struct
class ScratchError(Exception): pass
class ScratchConnectionError(ScratchError): pass
class Scratch(object):
prefix_len = 4
broadcast_prefix_len = prefix_len + len('broadcast ')
sensorupdate_prefix_len = prefix_len + len('sensor-update ')
msg_types = set(['broadcast', 'sensor-update'])
def __init__(self, host='localhost', port=42001):
self.host = host
self.port = port
self.socket = None
self.connected = False
self.connect()
def connect(self):
""" Connects to Scratch. """
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.socket.connect((self.host, self.port))
except socket.error as (err, msg):
self.connected = False
raise ScratchError("[Errno %d] %s" % (err, msg))
self.connected = True
def broadcast(self, msg):
if getattr(msg, '__iter__', False): # iterable
for m in msg:
self._send('broadcast "%s"' % self._escape(str(m)))
print "hjptestfor:",self._escape(str(m))
else: # probably a string or number
self._send('broadcast "%s"' % self._escape(str(msg)))
print "hjptestfor:",self._escape(str(msg))
def receive(self):
return self._parse(self._recv())
1, We can see the used port The port is 42001, yes host yes “localhost”( Description remote connection is not supported ), Of course, we can use our application as a springboard , Then operate remotely scratch, It's all a postscript
2, We can also translate the above code into other languages, such as C Language, etc. , Of course, since there is already this library, there is no need , Interested as a kind of trial practice
6、 ... and , Our example
The code is as follows :
#filename:helloscratch.py
import scratch
try:
s = scratch.Scratch()
if s.connected:
print "Connected to Scratch successfully"
else:
print "Connected to Scratch error"
except scratch.ScratchError:
print "Scratch is not opened or remote sensor connections aren't enabled"
try:
print "broadcast begin"
s.broadcast('hello scratch')
except NameError:
print "Scratch: Unable to Broadcast"
while True:
try:
msg = s.receive()
print "Scratch: receive:",msg
except KeyboardInterrupt:
print "GrovePi Scratch: Disconnected from Scratch"
break
The main function of this code is to scratch Print out the sent string , To operate the hardware , We can customize a set of commands , such as i2c,address etc. , When we receive these strings, we can operate the hardware in our client ( Of course, this example is just printing )
For example, to operate i2c, Just execute sudo apt-get install python-smbus That's all right. ,
7、 ... and , Running effect
perform : First, start it manually scratch, Otherwise, our client will fail to connect because the server is not online
stay shell Input directly :scratch Enter and start scratch
And then in shell Run our client under , It's connected to scratch:
suso python helloscratch.py
That's it with us shell Interaction
For example, we add the following module
When we click on the flag scratch Graphic code runs , Received on our client 112 This string , The effect is as follows :
If you need to operate the hardware , You can put it in join It defines its own commands : After receiving these command strings , Then operate the hardware , This has the effect of operating the hardware
边栏推荐
- Typescript learning notes
- Raspberry pie 4B file transfer
- 什么是物联网控制系统?它具有哪些特点?
- Raspberry pie 4B new machine system configuration and computer connection operation
- Cortex-a53 developed from bare metal_ Development Notes (64 bit)
- 线上 JVM 内存问题定位
- 什么是直饮机?它的工作原理和优点是什么?
- Siemens invites you to attend the ALM webinar on July 27
- Armv8 cortex-a programming wizard manual learning_ four
- Write a program that completely intercepts user operations
猜你喜欢
通用流程编排引擎介绍
浅聊Matter协议 (原CHIP协议)
Armv8 cortex-a programming wizard manual learning_ one
Qt5 GUI
Postman核心功能解析-參數化和測試報告
接口测试实战流程和步骤小结
检测设备开发的作用及应用的行业有哪些?
How should API interfaces be designed? How to ensure safety? How to sign? How to prevent weight loss?
Réponse: Qu'est - ce que l'unit é de concept nmn et qu'est - ce que nmn exactement
Visual Studio 特性进阶
随机推荐
Quartz.NET c# 教程 - 课程五:SimpleTrigger
Some superficial research and development stages involve software summarization
Make the tinder window unable to respond to some user messages
About the problems of sylixos kernel - can kernel driver
TS 类 和 ES6 类对比
ALM系统如何通过容器管理物件(以Polarion为例)
Scientific evidence: does NMN have an effect on cholecystitis, and how about the clinical effect of NMN
Matter协议特性解析(一) 支持非Matter协议,私有协议,Matter Bridge技术分析
JMeter中如何实现接口之间的关联?
How to realize the association between interfaces in JMeter?
德国大众集团独家软件测试供应商-Parasoft
Sonova sonova reduced the time of compliance documents by 80% using polarion
仿照MEMZ做一个特效程序
Réponse: Qu'est - ce que l'unit é de concept nmn et qu'est - ce que nmn exactement
scratch图形化编程操作硬件
UI自动化测试之ddt实战
网关是什么?什么是物联网网关?
liteos连接器脚本(二)
Raspberry pie 4B three sound sensor Ao module connection and high-precision time output
linear algebra