本帖最后由 hick 于 2013-8-19 17:23 编辑
纯 arduino 新手,高手勿笑,月初买的 arduino 板, 前天开始折腾, 好有意思, 分享的这个挺基础,可是之前搜索就是没搜到类似的,摸索出来以后特别分享下:
arduino 端还不知道怎么用 python 直接编译上传,貌似看到有方案? 先还是用 arduino IDE 写 C 来处理串口请求:
-------------------- - char line[500] = ""; // 传入的串行数据
- int ret = 0;
- void setup() {
- Serial.begin(9600); // 打开串口,设置数据传输速率9600
- }
-
- void loop() {
-
- // 纯口可用时操作
- if (Serial.available() > 0) {
- // 读取传入的数据: 读到 \n 为止,或者最多 500 个字符
- ret = Serial.readBytesUntil('\n', line, 500);
-
- //打印你得到的:
- Serial.print("I received: ");
- Serial.println(line);
- }
- // 每1秒做一个输出
- delay(1000);
- Serial.println("I am waiting! ");
- }
复制代码
--------------------
在安装好 pyserial 以后 python 读取串口数据:
--------------------
[pre lang="python" line="1"]#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import time
import serial
ser = serial.Serial(2) # 注意选择串口号, 从 0 开始计数, 我的是 COM3 ,所以参数是 2
line = ser.readline()
while line:
print(time.strftime("%Y-%m-%d %X\t") + line.strip())
line = ser.readline()
# 每 10 秒向窗口写当前计算机时间
sep = int(time.strftime("%S")) % 10
if sep == 0:
ser.write("hello, I am hick, the time is : " + time.strftime("%Y-%m-%d %X\n")) # write a string
ser.close() [/code]
--------------------
嘿嘿, 整理到了我博客, http://blog.hickwu.com/posts/275 |