calling serial.read from other function - python

I'm trying to connect python with Arduino code using serial but I cannot call serial.read() within the led_on_off() function.
This is the Arduino code:
int led=13;
int val=0;
char functionname='K';
#include <string.h>
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
digitalWrite (led, LOW);
Serial.println("Connection established...");
}
void loop()
{
functionname = Serial.read();
if (functionname= 'L')
{
led_on_off();
}
}//void loop
void led_on_off()
{
val=Serial.read()
if (val= 1)
digitalWrite(led,HIGH)
else if (val == 0)
digitalWrite(led,LOW)
}
And this is the python code:
import serial
Arduino_Serial = serial.Serial('com18',9600) # Create Serial port object called arduinoSerialData
print(Arduino_Serial.readline()) # read the serial data and print it as line
print("Enter L to ON LED and M dc motor")
input_data = input()
Arduino_Serial.write(input_data.encode())
print(Arduino_Serial.readline())
input_value=input("enter 1 or 0")
Arduino_Serial.write(input_value.encode())
my expectation is to get input (1 or 0) from python code and process it within the led_on_off function in Arduino code using the serial.read() function and turn on or off the led at pin 13.

As already stated by #KIIV your Arduino code has some syntax errors. Besides that, you are sending a string from your Python script (input function) so you need to read it as a string on Arduino. Something like this would do the job:
Python script:
import serial
# Create Serial port object called arduinoSerialData
Arduino_Serial = serial.Serial('com18', 9600)
# read the serial data and print it as line
print(Arduino_Serial.readline())
input_data = input("Enter L to ON LED and M dc motor: ")
Arduino_Serial.write(input_data.encode())
print("Received Command:", Arduino_Serial.readline())
while True:
input_value = input("enter 1 or 0")
Arduino_Serial.write(input_value.encode())
Arduino code:
int led = 13;
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
}
void loop()
{
//void loop
if (Serial.available())
{
String functionname = Serial.readString();
if (functionname == "L")
{
Serial.println("Command received from Arduino!");
while (1)
{
led_on_off();
}
}
}
}
void led_on_off()
{
if (Serial.available())
{
String val = Serial.readString();
if (val == "1")
digitalWrite(led, HIGH);
else if (val == "0")
digitalWrite(led, LOW);
}
}

Related

How to send a decimal number from python to arduino

i am trying to send a decimal number from python to arduino, the problems is data is sent in an other type (i don't know which one maybe binary), so i did not get the desired response!
here is my arduino code
void setup() {
// put your setup code here, to run once:
pinMode(10, OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available() > 0) {
char k = Serial.read();
if (k > 500) {
analogWrite(10, 255);
delay(1000);
}
if (150 < k < 500) {
analogWrite(10, 128);
}
else if (k < 150) {
analogWrite(10, 0);
delay(1000);
}
Serial.print(k);
}
}
& here is python code
import serial
import struct
arduinoData = serial.Serial('com3',9600)
data = 0
while(1==1):
serialcmd = input("serial command: ")
arduinoData.write (struct.pack('>B',serialcmd))
data = arduinoData.readline()
print(data)

how to receive only 1 single value form python to arduino

I'm new to this!!
python code
i = results[1]
i *= 100
if i >= 75:
print('Recognised as owner!')
arduino.write(str.encode('1'))
else:
print('not matches')
serial monitor
111111111111111111111111111111111111111111111111111111111111111111...
Arduino code
#include <Servo.h>
Servo servo;
char value1;
void setup()
{
servo.attach(8);
servo.write(0);
Serial.begin(9600);
}
void loop()
{
if(Serial.available() > 0)
value1 = Serial.read();
Serial.print(value1);
if (value1 == '1') {
digitalWrite(13, HIGH);
servo.write(90);
delay(100);
}
for (int i = 10; i > 0; i--){
Serial.println("go inside!!, hurry up !!");
delay(1000);
}
servo.write(0);
Serial.println("door is closed");
delay(1000);
}
question:
this program can handle the door system based on face recognition
the Arduino takes the value of "1" over and over. so later servo always looping every 10 s. because the program cant handles 1 single value.
my goal is to make sure that the Arduino only get 1 single input. so later the servo is running well
ty

Using Arduino as output for Python progam

I'm trying to control Arduino outputs via USB with python.
Basically if a value x in python is 5, then digital output 5 should be high.
What I had imagined was something like this on the
Python side:
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 9600)
x=5
while True:
ser.write('x')
Arduino:
void setup(){
Serial.begin(9600);
pinMode(5, OUTPUT);
pinMode(4, OUTPUT);
}
void loop()
{
int out;
out = Serial.read();
if (out == 5){
digitalWrite(5, HIGH);
}
Am I way off?
One improvement in python:
x='5'
while True:
ser.write(x)
Now, you get '5' in out, not 'x'.
And arduino code:
void setup() {
Serial.begin(9600);
for(char i=0;i<10;i++)
pinMode(i, OUTPUT);
}
void loop() {
;
}
void serialEvent() {
if (Serial.available()) {
char inChar = (char)Serial.read();
inChar-='0';
for(char i=0;i<10;i++)
digitalWrite(i, LOW);
digitalWrite(inChar,HIGH);
}
}

Arduino serial size

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?
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.

ArduinoPI Python - SERIAL CONNECTION LOST DATA

Intent: Control arduino uno from serial port
Tools:
https://github.com/JanStevens/ArduinoPi-Python
I got the server working on both my mac and my Model b+ Raspberry.
The browser behaves as shown in the picture below in both situations.
To me it looks like the server sent the message to Arduino successfully. But the data somehow gets lost on the way. The Arduino board resets every time I access the url in my browser. I googled and found that a 10uF capacitor between ground and reset pins would prevent the reset from happening. It did, but pin 3 won't go "HIGH". I got a LED+RESISTOR plugged on pin 3 and ground accordingly. I can see the Rx led blinking every time I access the url. So it makes me think that the Arduino is misunderstanding the command from my Flask sever.
OG Arduino code:
String cmd;
bool cmdRec = false;
void setup()
{
//Start the connection with the Raspberry Pi
Serial1.begin(115200);
// Start the connection with the Laptop, for debugging only!
//Serial.begin(115200);
}
void loop()
{
handleCmd();
}
void serialEvent1() {
while(Serial1.available() > 0) {
char inByte = (char)Serial1.read();
if(inByte == ':') {
cmdRec = true;
return;
} else if(inByte == '#') {
cmd = "";
cmdRec = false;
return;
} else {
cmd += inByte;
return;
}
}
}
void handleCmd() {
if(!cmdRec) return;
// If you have problems try changing this value,
// my MEGA2560 has a lot of space
int data[80];
int numArgs = 0;
int beginIdx = 0;
int idx = cmd.indexOf(",");
String arg;
char charBuffer[20];
while (idx != -1) {
arg = cmd.substring(beginIdx, idx);
arg.toCharArray(charBuffer, 16);
data[numArgs++] = atoi(charBuffer);
beginIdx = idx + 1;
idx = cmd.indexOf(",", beginIdx);
}
// And also fetch the last command
arg = cmd.substring(beginIdx);
arg.toCharArray(charBuffer, 16);
data[numArgs++] = atoi(charBuffer);
// Now execute the command
execCmd(data);
cmdRec = false;
}
// For advanced function like switch all the leds in RGB
void execCmd(int* data) {
switch(data[0]) {
case 101:
{
for(int i = 2; i < (data[1]*2)+1; i+=2) {
pinMode(data[i], OUTPUT);
analogWrite(data[i], data[i+1]);
}
}
break;
case 102:
{
pinMode(data[1], INPUT);
int sensor = analogRead(data[1]);
Serial1.println(sensor);
}
break;
case 103:
{
String result = "";
int sensor = 0;
for(int j = 2; j < data[1]+2; j++) {
pinMode(data[j], INPUT);
sensor = analogRead(data[j]);
result += String(sensor)+",";
}
Serial1.println(result);
}
break;
default:
{
pinMode(data[0], OUTPUT);
analogWrite(data[0], data[1]);
}
break;
}
}
It does not compile this way. So I uncommented the second Serial.begin line and deleted all the "Serial1." appearances on the code. I can't see no action on the arduino IDE serial when I test it on my mac.
As the code was written with an Arduino Mega that got 2 or 3 serial ports, void serialevent1() is triggered when there is communication going on the the MEGA's SERIAL1 port. Since I am working on the UNO, that only have 1 serial port, all i had to do was delete the "1" before the parenthesis and all worked as supposed.
void serialEvent() { }

Categories