tony1812
Posts: 354
Joined: Sat Jul 15, 2017 12:40 pm
Location: Boston MA.

python on serial port

Thu Sep 27, 2018 12:39 pm

Hello. I wrote a very simple piece of code. all it does is when enter a 1 in serial monitor the the LED blinks for 1 second.

Code: Select all

void setup()
{
  Serial.begin(9600);
  pinMode(12, OUTPUT);
}
 
void loop() {
  if (Serial.available()) {
    
    if(Serial.read()=='1') {
      digitalWrite(12, HIGH);
      delay(1000);
      digitalWrite(12, LOW);
      delay(1000);
    }  
  }
}
This code works just fine with the serial monitor.
Now I want to use python3 on my Mac instead of the Serial Monitor

Code: Select all

import serial
#! /usr/local/bin/python3
 
import serial
from time import sleep

# for Mac
ser = serial.Serial("/dev/cu.usbmodem1D1330", baudrate=9600)

ser.write(('1').encode())
now the LED doesn't blink any more. I use the correct port /dev/cu.usbmodem1D1330 as in Ardrino. Can someone tell me what I have done wrong? Thanks

scotty101
Posts: 3680
Joined: Fri Jun 08, 2012 6:03 pm

Re: python on serial port

Thu Sep 27, 2018 4:40 pm

Try opening the port

Code: Select all

ser.open()
And try this too.

Code: Select all

ser.write(b'1')
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Return to “Python”