嵌入Python-Homework4

 Test14A

print("=============== 模块引入 =================")
# 模块:其他py文件
print("=============== import ==================")
# 引入外部文件中的所有内容,调用时需要加 文件名前缀
# import 文件
import Test14B                       # 引入Test14B文件

print(Test14B.Count)                 # 调用 14B 中的Count变量
Test14B.people("ROBOT",18,"男")      # 调用 14B 中的people类     
Test14B.Max(12,8)                         
print("###",Test14B.Count)

import Test14B as T     # 引入Test14B模块,并且使用别名T 
print(T.PI)             # 简便 等价于 Test14B.PI

print("=============== from import =============")
# 只引入文件在部分内容
# form 文件名 import 文件中的内容
from Test14B import Max
from Test14B import PI

print(Max(12,8))
print(PI)

print("=============== from import * =============")
# 引入文件所有内容
# form 文件名 import *
# 谨慎使用 本文件中有可能出现命名冲突
from Test14B import *

tyj_Count = 90
print(Count)

print("========== 面向对象三个特性:封装 继承 多态 ============")
# C -> java -> python 
# 协作开发:多人,多团体开发
from Test14B import car
p = car(10,12,14)       # 实例化一个car对象

p.show()
print(p.b)              # 通过对象访问公共属性,允许
#print(p.__a)           # 通过对象访问私有属性,不允许

#######################################################
# 学校
print("=========================================================")
from Test14B import student
s1 = student()
s1.name = "ming"
# s1.age = 18
s1.setage(18)
s1.show()
s2 = student()
s2.name = "li"
s2.setage(-7)    #属性可以被使用者无节制的使用
s2.show()

Test14B 

class people:
    def __init__(self,n,a,g):     # 属性
        self.name = n           
        self.age = a
        self.gender = g
    def show(self):             # 方法
        print(self.name,self.age,self.gender)


def Max(x,y):                   # 函数
    if x>y:
        return x
    else :
        return y

Count = 100
PI = 3.14

# 类的访问权限
# 私有属性特征:属性名前有两个下划线
# 公有属性特征: 属性名前没有下划线
# 保护属性特征:属性名前有一个下划线
class car:
    def __init__(self,x,y,z):
        self.__a = x    # 私有属性
        self.b = y      # 公共属性
        self._c = z     # 保护属性
    def show(self):
        # 无论是公共还是私有属性,类中可以调用
        print(self.__a,self.b)

#######################################################
# 企业
class student:
    def __init__(self): # 属性
        self.name = ""  
        # self.age = 1
        self.__age = 1  # age变成私有属性
    def show(self):     # 方法
        print(self.name,self.__age)
    # 为私有变量设置两个调用方法
    def getage(self):
        return self.__age
    def setage(self,x):
        if x<1:
            print("不合法")
        else:
            self.__age = x
        

Test16

print("=======math time==========")
import math     # 数学库
print(math.pi)
print(math.e)
print(math.sin(math.pi/6))

import time     # 时间库

print(time.time())  # 时间戳(秒)   自1970年1月1号0时到现在过去时间的秒值
t1 = time.time()    # 程序运行前的秒
for  i in range(5000):
    for j in range(10000):
        1+1
t2 = time.time()    # 程序运行后的秒
print("程序花费了:",t2-t1,"秒")
      
print(time.ctime()) # 返回当前时间的格式化描述

time.sleep(2)       # 让本线程休眠2秒
for i in range(5):
    print("hello")
    time.sleep(1)

print("===========多线程===========")
import time 
import threading    # 线程关键类

# main函数(python无需另外创建新的线程)中执行的就是主线程
threading.current_thread()
print(threading.current_thread().name)
print(threading.current_thread().ident)

# 任务a 2秒钟打印一个hello
# for i in range(10):
#     print("hello",time.time() % 100)
#     time.sleep(2)
# 任务b 2秒钟打印一个happy
# for i in range(10):
#     print("happy",time.time() % 100)
#     time.sleep(2)

# 创建一个子线程
def child():
    for i in range(4):
        print("children!",threading.current_thread())
        time.sleep(0.5)


a1 = threading.Thread(target = child)   # 定义线程对象,线程启动后,执行child内容
a1.start()  # 启动线程

child()     # 主线程跑child函数

def Jobo():
    for i in range(10):
        print("hello",time.time() % 100,threading.current_thread().name)
        time.sleep(2)
def Jpbo():
    for i in range(10):
        print("happy",time.time() % 100,threading.current_thread().name)
        time.sleep(1)

s1 = threading.Thread( target=Jobo )
s2 = threading.Thread( target=Jobo )
print("s1子线程启动")
s1.start()
print("s2子线程启动")
s1.start()

print("end 主线程死亡")

Test17

print("=======math time==========")
import math     # 数学库
print(math.pi)
print(math.e)
print(math.sin(math.pi/6))

import time     # 时间库

print(time.time())  # 时间戳(秒)   自1970年1月1号0时到现在过去时间的秒值
t1 = time.time()    # 程序运行前的秒
for  i in range(5000):
    for j in range(10000):
        1+1
t2 = time.time()    # 程序运行后的秒
print("程序花费了:",t2-t1,"秒")
      
print(time.ctime()) # 返回当前时间的格式化描述

time.sleep(2)       # 让本线程休眠2秒
for i in range(5):
    print("hello")
    time.sleep(1)

print("===========多线程===========")
import time 
import threading    # 线程关键类

# main函数(python无需另外创建新的线程)中执行的就是主线程
threading.current_thread()
print(threading.current_thread().name)
print(threading.current_thread().ident)

# 任务a 2秒钟打印一个hello
# for i in range(10):
#     print("hello",time.time() % 100)
#     time.sleep(2)
# 任务b 2秒钟打印一个happy
# for i in range(10):
#     print("happy",time.time() % 100)
#     time.sleep(2)

# 创建一个子线程
def child():
    for i in range(4):
        print("children!",threading.current_thread())
        time.sleep(0.5)


a1 = threading.Thread(target = child)   # 定义线程对象,线程启动后,执行child内容
a1.start()  # 启动线程

child()     # 主线程跑child函数

def Jobo():
    for i in range(10):
        print("hello",time.time() % 100,threading.current_thread().name)
        time.sleep(2)
def Jpbo():
    for i in range(10):
        print("happy",time.time() % 100,threading.current_thread().name)
        time.sleep(1)

s1 = threading.Thread( target=Jobo )
s2 = threading.Thread( target=Jobo )
print("s1子线程启动")
s1.start()
print("s2子线程启动")
s1.start()

print("end 主线程死亡")

 Test18

print("==========字节数组 bytes==========")
# 初衷,字节流操作

# 字节数组常亮
"abcd中文"      # 字符串类型,每个字符 2 个字符       
b"abcd"         # bytes 类型(c语言中的字符串),每个字符 1 个字符,不能写中文
# 字节数组使用
a = bytes()     # 空的字节数组
c = bytes("abcdf中文",encoding="utf-8")     # 把str转为字节数组 
print(c)
f = bytes([0x40,0x50,0x60])                 # 把int列表转化为字节数组
print(f)
# 字节数组调用 看成列表数组操作f【i】
print( "%x"%(f[0]) )
print( "%x"%(f[1]) )
print( "%x"%(f[2]) )
print( len(f) )         # 查看字节数组的元素个数
# 字节数组遍历
for i in f:
    print(i)

print("==========串口开发===========")
# 安装 pyserial 联网 指令: pip install pyserial
import serial                   # 串口操作库
import serial.tools.list_ports  # 串口设备环境库
# 了解设备中的串口数量克名称
ports = serial.tools.list_ports.comports()  # 返回设备中所有串口的描述
com_list = []
for i in ports:
    com_list.append(i[0])         # 把所有串口名都放到com_list列表中
    print(i[0])
# 创建串口实例
ser = serial.Serial()             # 串口实例,未连接
ser.port = "com3"                 # 串口名
ser.baudrate = 115200             # 波特率
ser.parity = serial.PARITY_NONE   # 校验
# 打开串口
if ser.is_open:                   # 串口实例已经打开过
    pass
else:
    ser.open()
# 数据发送
st = "Welcom to guangzhou"
stb = bytes(st,encoding="utf-8")  # 把数组转为字节数组
ser.write(stb)
bt = [0xaa,0x90,0x25,0x18]
btb = bytes(bt)
ser.write(btb)
# 数据接收
while True:
    re = ser.read_all()            # re就是bytes,串口接收内容
    if len(re) == 0:
        pass
    else:
        print(re)
        for i in re:
            print( "%x"%(i) )
        break
# 关闭串口
ser.close()

  Test19run

# 应用
from Test19ser import MyCom
import threading
import time
mc1 = None

# 子线程回调函数T,串口输出控制台输入的内容
def Input_T():
    global mc1  # 说明mc1是全局变量,子线程需要她来操作串口
    print("发送线程启动")
    while True:
        new = input("请输入发送的内容:") 
        print(new)
        mc1.send_mycom(new)
    # print("end",threading.current_thread().name)

def Listen_T():
    global mc1
    print("监听线程启动")
    while True:
        bt = mc1.recevie_mycom()
        if len(bt) == 0 :   # 收不到数据
            pass
        else:
            print("收到数据:",str(bt))
    print("end",threading.current_thread().name)

print("当前线程:",threading.current_thread().name)
mc1 = MyCom()
mc1.set_serial(pt="com3")
mc1.show_serial()
print(mc1.get_serial_com())
mc1.open_mycom()    # 串口连接

t1 = threading.Thread(target = Input_T)
t1.start()
t2 = threading.Thread(target = Input_T)
# t2.start()  # 启动 接收数据 线程

print("end",threading.current_thread().name)
# mc1.close_mycom()

Test19ser

# 串口类
import serial
import serial.tools.list_ports
import threading
class MyCom(threading.Thread):
    def __init__(self): # 设置属性
        threading.Thread.__init__(self) # 父类的初始化
        self.ms = serial.Serial()       # 创建串口对象
        self.com_list = []              # 保存可用的串口号

    def set_serial(self,pt="com1",br=9600,pa=serial.PARITY_NONE):  #设置串口属性
        self.ms.port = pt               # 串口名
        self.ms.baudrate = br           # 波特率
        self.ms.parity = pa

    def show_serial(self):              # 打印信息
        print("串口对象信息: ",self.ms.port,self.ms.baudrate,self.ms.parity)
        
    def get_serial_com(self):           # 返回可用的串口号
        ports = serial.tools.list_ports.comports()
        for i in ports:
            self.com_list.append(i[0])
        return self.com_list
    
    def open_mycom(self):               #连接串口
        if self.ms.is_open:             #如果对象已经连接串口,先断开
            self.ms.close()
            print("关闭了旧的连接")
        else:
            pass
        
        try:
            self.ms.open()              # 连接串口
            print("连接成功")
        except Exception as e:
            print("连接错误")
    
    def close_mycom(self):              # 关闭连接
        self.ms.close()

    def send_mycom(self,st):            # 发送数据,st是字符串
        if self.ms.is_open:
            tmp = str(st)
            stb = bytes(tmp,encoding="utf-8")
            self.ms.write(stb)   
            print("发送成功")
        else:
            print("发送错误:还未连接")
    
    def recevie_mycom(self):            # 只读一次,返回读的内容
        if self.ms.is_open:
            re = self.ms.read_all()
            return re
        else:
            print("接收失败:还未连接")
            return None

# 接收数据 线程:产生一个线程,打印接收到数据
    def run(self):
        while True:
            #   不断监听,并打印
            if self.ms.is_open:
                g = self.recevie_mycom()
                if len(g) != 0:
                    print(g)
                else:
                    pass
            else:
                print("串口未打开")
                break
                # 循环结束

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值