pyserial & arduino

首先,执行easy_install pyserial。python程序,向串口写一个数字。

import serial

s = serial.Serial()
s.port = 3
s.baudrate = 9600
s.stopbits = 1
s.open()
#print s

print s.readline().strip()
s.write('10')
print s.readline().strip()

 

执行easy_install docopt,生活更美好。python程序版本0.2。

'''talk with arduino

usage:
    arduino.py <num>
    
options:
    -h --help
    -v --version
'''
from docopt import docopt

import serial

if __name__ == '__main__':
    arguments = docopt(__doc__, version='0.2')
    try:
        num = arguments['<num>']
        int(num)
    except ValueError as e:
        print 'argument must be a integer, from 1 to 254'
        exit(-1)
    
    s = serial.Serial()
    s.port = 3
    s.baudrate = 9600
    s.stopbits = 1
    s.open()
    #print s

    print s.readline().strip()
    s.write(num)
    print s.readline().strip()
    
    s.close()

arduino从串口读入呼吸灯亮度的退化值1~254。

int pin  = 9;
int stay = 5;

void setup () {                
    pinMode(pin, OUTPUT);     
  
    Serial.begin(9600);
    Serial.println(":-] hi");
  
    delay(300);
}

void loop () {
    int _stay = 0;
    while (Serial.available()) {
        char in = Serial.read();
        //Serial.println(in); continue;
        if (in >= 48 && in <= 57) {
            _stay = _stay * 10 + (in - 48);
        } else {
            _stay = 0;
            break;
        }
    }
    if (_stay != stay && _stay > 0 && _stay < 255) {
        stay = _stay;
        Serial.println(stay);       
    }

    for(int fade = 0 ; fade <= 255; fade += stay) { 
        analogWrite(pin, fade);         
        delay(30);                            
    } 
    for(int fade = 255 ; fade >= 0; fade -= stay) { 
        analogWrite(pin, fade);
        delay(30);                            
    } 
}

 

done! enjoy it

 

 

你可能感兴趣的:(arduino)