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);
}
}
Related
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)
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
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);
}
}
I'm sending data from a python script to my Arduino board. I can succesfully communicate with the board. Based on the data send by the python, the stepper motor connected should either move forward or backward. If python is sending '0' the motor should rotate forward and if python is sending '1' then the motor should rotate backward. When i type '0' in the serial monitor the stepper moves forward and on '1' stepper moves backward. But when python is sending data at first, stepper is not moving forward or backward. Only when the state change happens(if state changes from '1' to '0' or '0' to '1'), the stepper either moves forward or backward. I tried to see if data is send from python, the arduino is receiving data from python. Suggestion will be heavily appreciated.
Ardunio code
static const int SELENOID_PIN = 2;
static const int OPEN = '0';
static const int CLOSE = '1';
static const int STEPS = 30;
static const int delaylegnth = 10;
void setup() {
//establish motor direction toggle pins
pinMode(12, OUTPUT); //CH A -- HIGH = forwards and LOW = backwards???
pinMode(13, OUTPUT); //CH B -- HIGH = forwards and LOW = backwards???
//establish motor brake pins
pinMode(9, OUTPUT); //brake (disable) CH A
pinMode(8, OUTPUT); //brake (disable) CH B
Serial.begin(9600);
while(!Serial){}//wait until the serial port is connected
Serial.write('1');
pinMode(SELENOID_PIN ,OUTPUT);
}
void polarisingA()
{
digitalWrite(9, LOW); //ENABLE CH A
digitalWrite(8, HIGH); //DISABLE CH B
digitalWrite(12, HIGH); //Sets direction of CH A
analogWrite(3, 255); //Moves CH A
delay(delaylegnth);
}
void polarisingB()
{
digitalWrite(9, HIGH); //DISABLE CH A
digitalWrite(8, LOW); //ENABLE CH B
digitalWrite(13, HIGH); //Sets direction of CH B
analogWrite(11, 255); //Moves CH B
delay(delaylegnth);
}
void polarisingC()
{
digitalWrite(9, LOW); //ENABLE CH A
digitalWrite(8, HIGH); //DISABLE CH B
digitalWrite(12, LOW); //Sets direction of CH A
analogWrite(3, 255); //Moves CH A
delay(delaylegnth);
}
void polarisingD()
{
digitalWrite(9, HIGH); //DISABLE CH A
digitalWrite(8, LOW); //ENABLE CH B
digitalWrite(13, LOW); //Sets direction of CH B
analogWrite(11, 255); //Moves CH B
delay(delaylegnth);
}
void stepRight()
{
polarisingA();
polarisingB();
polarisingC();
polarisingD();
}
void stepLeft();
{
polarisingD();
polarisingC();
polarisingB();
polarisingA();
}
void spin(bool dir,int tickes)
{
//Serial.print(dir);
for(int i =0 ; i < tickes; i++)
{
if(dir == true)//right
{
stepRight();
}
else
{
stepLeft();
}
}
}
void loop() {
if(Serial.available() > 0)
{//there is incoming data form the serial and serial is setted up
handleData();
}
delay(5);
}
void handleData()
{
unsigned char a = Serial.read();
Serial.write("new data");
int action = -1;
if(a == OPEN)
{
action = 1;
}
else if(a == CLOSE)
{
//Serial.print("close");
action = 0;
}
if (action != -1)
{
bool dir = action == 1 ? HIGH : LOW ;
spin(dir,STEPS);
digitalWrite(SELENOID_PIN ,action ? HIGH : LOW );
Serial.write(a);//ack
}
}
Python code(Part only sending data to arduino):
def openthedoor(set_accepted_list,set_list_ant_id,set_forbidden_list,set_accepted_list_frozen):
if(((len(set_accepted_list)) >0) & (set_forbidden_list == set()) & ((set_accepted_list_frozen == None) or ((set_accepted_list_frozen & set_accepted_list)== set_accepted_list))):
print"yes,open the gate"
use_step(1)
else:
print"no,close the gate"
use_step(0)
def establishing_connection():
#serial.Serial("COM1",9600)
print ser.read();
last_action = -1
def use_door(activate):
global last_action
#global serial
if(last_action != activate):
send_data(activate)
last_action = activate
def send_data(data):
global ser
try:
if(ser == None):
ser = serial.Serial("COM1",9600,timeout = 0)
print "reconnect"
if(data==0):
ser.write('0')
print "python is telling the arduino to move stepper forward"
else:
ser.write('1')
print "python is telling the ardunio to move stepper backward"
time.sleep(0)
except IOError:
time.sleep(0)
ser.close()
#continue
ser = None
print "after read"
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() { }