I everybody,
Today, I learnt about controlling my Arduino with raspberry via Adafruit AIO. I will post the code below. I success to receive data of a potentiometer and set ON/OFF two LEDs, it works well (but it's not very responsive, I'm limited by the rate limit of Adafruit, that's why I added a millis() timer in my code).
But it's not sufficient for my project. I have a peristaltic pump and I need to control the pump with a slider object (from 0 to 255 PWM for example).
I will create a pump feed that sends data from AIO to my raspberry but I don't know how I can send, at the same time, the string which commands the Arduino and the slide value, and how I can retrieve the data to send the command to the pump.
If you have ideas, I'm in !!
Thanks,
... Alex
int led1= 6;
int led2= 5;
int poto = A2;
unsigned long currentTime = 0;
unsigned long previousTime = 0;
void setup() {
Serial.begin(115200); // start serial communication at 9600 baud
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(poto, INPUT);
}
void loop() {
currentTime = millis();
if ((currentTime-previousTime)>1500){ //AIO rate limit 6O threads per seconds
previousTime = currentTime;
const int poto_value=analogRead(poto);
Serial.println(poto_value);
if (Serial.available()) { // check for incoming serial data
String command = Serial.readString(); // read command from serial port
if (command == "led_1_on") { // turn on LED
digitalWrite(led1, HIGH);
} else if (command == "led_1_off") { // turn off LED
digitalWrite(led1, LOW);
} else if (command == "led_2_on") { // turn off LED
digitalWrite(led2, HIGH);
} else if (command == "led_2_off") { // turn off LED
digitalWrite(led2, LOW);
}
}
}
}
And here is my rasp code :
#!/usr/bin/env python3
"""Control an Arduino over the USB port"""
import serial
from Adafruit_IO import Client
from time import sleep
USB_PORT="/dev/ttyACM0" #Port USB raspberry
baudrate=115200
try:
s = serial.Serial(USB_PORT,baudrate, timeout=30) #timeout ?
except:
print("Error - Could not open USB Serial Port Please check your port name and permissions")
print("Exiting program")
exit()
ADAFRUIT_IO_USERNAME = "alexglowee"
ADAFRUIT_IO_KEY = "aio_UmjB60kISJn2XsQ9wcRuDyg2FaZ1"
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
pompe = aio.feeds('proto.pompe')
output = open('data.csv', 'w')
etat_led_1 = "OFF"
etat_led_2 = "OFF"
while 1:
s.dtr=0
s.dtr=1
sleep(0.2)
s.reset_input_buffer()
while 1:
#data = s.readline().decode()
#output.write(data)
#output.flush()
aio.send_data(pompe.key, data)
led_1 = aio.receive("proto.led-1")
led_2 = aio.receive("proto.led-2")
led_value_1 = led_1.value
led_value_2 = led_2.value
if led_value_1 != etat_led_1:
if etat_led_1 == "OFF":
s.write(b'led_1_on')
elif etat_led_1 == "ON":
s.write(b'led_1_off')
etat_led_1 = led_value_1
if led_value_2 != etat_led_2:
if etat_led_2 == "OFF":
s.write(b'led_2_on')
elif etat_led_2 == "ON":
s.write(b'led_2_off')
etat_led_2 = led_value_2