Arduino UNO micro controller and Python (ongoing)

 
Alright so i was looking for something to do with my Arduino UNO micro controller and while there are many ideas, projects and tutorials on the Web, i concluded it would be best to implement something using Python. So for starters we will do the "Blink"  example.

Downloading and installing:

Depending on your OS things differ. However every bit of info can be found in Arduino Homepage.
For Mint  users like myself a simple sudo pip install arduino command will do.
And  that's that. No further USB drivers tweaking or anything. However when you connect your board and try to compile and upload one of the example programs, you might  encounter  this  single error.

Serial port 'COM1' not found. Did you select the right one from the Tools > Serial Port menu?

A trivial solution to this throwback is to create a group in the starting prompt and restarting the program this time as an admin sudo  arduino. This time once the default serial port (COM1) will fail the program will automatically try to connect you using another one. That's it!

Step 1.

We can now proceed with installing the pySerial library which uses a serial interface in order to communicate with Arduino.

make a python file .py with the following simple code:

## import the serial library
import serial

## Boolean variable that will represent 
## whether or not the arduino is connected
connected = False

## open the serial port that your ardiono 
## is connected to.
ser = serial.Serial("/dev/ttyACM0", 9600)

## loop until the arduino tells us it is ready
while not connected:
    serin = ser.read()
    connected = True

## Tell the arduino to blink!
ser.write("1")

## Wait until the arduino tells us it 
## is finished blinking
while ser.read() == '1':
    ser.read()

## close the port and end the program
#ser.close()



Step 2.

Then either create a new sketch .ino file or simply open a new sketch  within Arduino IDE using this code:


// Open a serial connection and flash LED when input is received

void setup(){
  // Open serial connection.
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  Serial.write('1'); 
}

void loop(){ 
  if(Serial.available() > 0){      // if data present, blink
    digitalWrite(13, HIGH);
    delay(1000);            
    digitalWrite(13, LOW);
    delay(1000); 
    //Serial.write('0');
  }
} 

 
Step 3.

Compile and upload the code to arduino. Wait for a moment, run the python script sudo python pythonfile.py and thats it, watch the LED blinking for ya! ;)


No comments:

Post a Comment


Free online chess

View Kapellas Nick's profile on LinkedIn
Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License