0
votes

I'm trying to send message to arduino via usb cable with python.

#!python3

import serial
import time
import api
import sys

api = api.API()

arduino = serial.Serial('COM3', 115200, timeout=.1)
time.sleep(2)

while api['IsOnTrack'] == True:
        if api['Gear'] == 3:
            arduino.write('pinout 13')
            print "Sending pinon 13"
            msg = arduino.read(arduino.inWaiting())
            print ("Message from arduino: ")
            print (msg)
            time.sleep(2)

Arduino:

// Serial test script

int setPoint = 55;
String command;

void setup()
{

  Serial.begin(115200);  // initialize serial communications at 9600 bps
  pinMode(13,OUTPUT);
}

void loop()
{
  while(!Serial.available()) {
  }
   // serial read section
  while (Serial.available())
  {
    if (Serial.available() >0)
    {
      char c = Serial.read();  //gets one byte from serial buffer


  if(c == '\n')
  {
    parseCommand(command);
    command = "";
  }
  else
  {
    command += c;          //makes the string command
  } 
    }
  }
  if (command.length() >0)
  {
    Serial.print("Arduino received: ");  
    Serial.println(command); //see what was received
      }
}
void parseCommand(String com)
{
  String part1;
  String part2;

  part1 = com.substring(0, com.indexOf(" "));
  part2 = com.substring(com.indexOf(" ") +1);

  if(part1.equalsIgnoreCase("pinon"))
  {
    int pin = part2.toInt();

    digitalWrite(pin, HIGH);
  }
  else if(part1.equalsIgnoreCase("pinoff"))
  {
    int pin = part2.toInt();

    digitalWrite(pin, LOW);
  }
  else
  {
    Serial.println("Wrong Command");
  }
}

Python shell looks like this: http://i.imgur.com/IhtuKod.jpg

Can I for example make the arduino read the message once and the clear the serial? Or can you spot a clear mistake I have made?

While using just the Arduino IDE serial monitor. The led lights up when I write "pinon 13", this doesn't work while using python. Or when I send "pinout 13" message from serial monitor, it will tell me that it is a "Wrong Command", this also won't happen while using python.

Do you guys have any ideas how I should make the python send the message just once and not contiunously?

1

1 Answers

0
votes

In your Python code, you will have to write/send a \n after the command for the Arduino to recognize.

serial.write('pinon 13\n'); should work; note though, that \n may yield different results on different systems (eg. Windows vs. Linux), so you may want to explicitly use the same ASCII code on the Arduino and on the PC.

In Python this should be chr(10) and on the Arduino you may use if(c == 10) if you want.