将代码从arduino转换为python

时间:2016-03-29 23:25:03

标签: python arduino byte

有人可以帮我把这个arduino代码翻译成python代码吗?

#define BUFFLEN 3

byte buffer[] = { 0x05, 0x0D, 0x02, 0xFF, 0x10, 0xAA }

for (byte i=0; i < BUFFLEN; i++) {
    val = analogRead(A0);
    val = constrain(val,0,1023);
    buffer[i*2] = (byte)(i<<2) | highByte(val);
    buffer[i*2+1] = lowByte(val);
}

由于

1 个答案:

答案 0 :(得分:0)

您可以使用pyserial库通过串口捕获数据,然后使用python处理数据,在这种情况下,以下代码可以执行:

import serial
import struct

ser = serial.Serial('COM6',9600) #put the port number and the communication rate


BUFFLEN = 3 #constant

buffer = [ 0x05, 0x0D, 0x02, 0xFF, 0x10, 0xAA ]   #array

i=0  #initialize control variable

def clamp(n, minn, maxn):
    return max(min(maxn, n), minn)

while (i < BUFFLEN):
    val = ser.read()
    val = clamp(val,0,1023)
    buffer[i*2] = (i<<2) or struct.pack('<h', val)
    buffer[i*2+1] = struct.pack('>h', val)
    i+=1    #increment

但请记住从arduino IDE中捕获并打印数据到序列号