├── .gitignore ├── 01_TrasmissioneSerialeArduino ├── 01_TrasmissioneSerialeArduino_Relazione.pdf ├── Trasmissione seriale su Arduino.pdf ├── fase1 │ ├── analisiSegnaleOscilloscopio │ │ └── analisiSegnaleOscilloscopio.ino │ └── segnale.png └── fase2 │ ├── codiceInvio │ └── codiceInvio.ino │ └── codiceRicezione │ └── codiceRicezione.ino ├── 02_Python-2-Seriale ├── 02_Python_2_Seriale_Relazione.pdf ├── Python - 2 - Seriale.pdf ├── parte1 │ ├── sensorePython.py │ └── sketchSensore │ │ └── sketchSensore.ino └── parte2 │ ├── fase 2.2 │ └── sketchAttuatore │ │ └── sketchAttuatore.ino │ ├── fase 2.3 │ └── sketchAttuatore │ │ └── sketchAttuatore.ino │ └── fase 2.4 │ ├── attuatorePython.py │ └── sketchAttuatore_fase_2.4 │ └── sketchAttuatore_fase_2.4.ino ├── 03_Python-3-Pacchetto_livello_3_7_del modello_ISO-OSI_su_seriale ├── 03_Python_3_Pacchetto_livello_3_7_modello_ISOOSI_su_seriale_Relazione.pdf ├── Python - 3 - Pacchetto Livello 3 e 7 ISO-OSI su seriale.pdf └── parte3 │ ├── fase 3.1 │ └── sketch_sensore │ │ └── sketch_sensore.ino │ ├── fase 3.2 │ └── ricezione_dati_sensore.py │ ├── fase 3.3 │ └── invio_comandi_al_motore.py │ └── fase 3.4 │ └── sketch_motore │ └── sketch_motore.ino ├── 04_Python-4-GUI ├── 04_Python_4_GUI_Relazione.pdf ├── Python - 4 - GUI 1.pdf ├── parte2 │ ├── soluzione1 │ │ └── guiAttuatore1.py │ ├── soluzione2 │ │ └── guiAttuatore2.py │ └── soluzione3 │ │ └── guiAttuatore3.py └── parte3 │ ├── soluzione1 │ └── guiSensore1.py │ ├── soluzione2 │ └── guiSensore2.py │ └── soluzione3 │ └── guiSensore3.py ├── 05_Python-5-JSON ├── 05_Python_5_JSON_Relazione.pdf ├── Python - 5 - JSON.pdf ├── parte1 │ └── esercizioDiz1.py ├── parte2 │ ├── esDiz1.json │ └── esercizioDiz2.py └── parte3 │ ├── datiSensore.json │ ├── esercizioSensJ.py │ └── sketch_sensore_json │ └── sketch_sensore_json.ino ├── 07_Python-7-Flask ├── 07_Python_7_Flask_Relazione.pdf ├── Python - 7 - Flask 3.pdf ├── parte1 │ └── index.html ├── parte2 │ ├── index.html │ └── pyTohtml.py ├── parte3 │ ├── datiSensore.json │ └── flask1.py ├── parte4 │ └── fileComandi.txt └── parte6 │ ├── plotly │ ├── datiSensore.json │ ├── plotly1.py │ └── templates │ │ └── index.html │ └── template │ ├── datiSensore.json │ ├── template1.py │ └── templates │ └── index.html ├── 08_Python-8-Form ├── 08_Python_8_Form_Relazione.pdf ├── Python - 8 - Form.pdf ├── parte1 │ ├── ricevi.py │ └── templates │ │ └── index.html └── parte2 │ ├── datiSensore.json │ ├── ricevi2.py │ └── templates │ └── index.html ├── 09_Raspberry ├── Raspberry -Installazione senza monitor e senza tastiera - Lite 3.pdf └── imp.txt ├── 10_Pacchetto-RF24-Arduino ├── 10_Pacchetto_RF24_Arduino_Relazione.pdf ├── Pacchetto Livello 3 e 7 - RF24 - Arduino.pdf ├── parte0 │ └── sketch_prova │ │ └── sketch_prova.ino ├── parte1 │ └── sketch_sensore │ │ └── sketch_sensore.ino └── parte2 │ └── sketch_motore │ └── sketch_motore.ino ├── 11_Pacchetto-RF24-Raspberry ├── 11_Pacchetto-RF24-Raspberry_Relazione.pdf ├── Pacchetto Livello 3 e 7 - RF24 - Raspberry.pdf ├── parte2 │ ├── rf24SensoreJSON.py │ ├── rf24SensoreTemplate.py │ └── templates │ │ └── index.html ├── parte3 │ ├── rf24Attuatore.py │ └── templates │ │ └── index.html └── parte4 │ ├── rf24SensAtt.py │ ├── rf24SensoreJSON.py │ └── templates │ └── index.html ├── 12_Cloud-MQTT ├── 12_Cloud_MQTT_Relazione.pdf ├── Cloud - MQTT 1.pdf ├── imp.txt ├── parte3 │ ├── provaPublish.py │ └── provaRead.py ├── parte7 │ ├── attuatore │ │ └── subscribeAttuatore.py │ └── sensore │ │ └── publishSensore.py └── parte8 │ ├── attuatore.py │ └── sensore.py ├── 13_Cloud-MQTT-ESP8266 ├── 13_Cloud_MQTT_ESP8266_Relazione.pdf ├── Cloud - MQTT - ESP8266.pdf └── parte2 │ ├── esp8266_motore │ └── esp8266_motore.ino │ └── esp8266_sensore │ └── esp8266_sensore.ino ├── 14_Cloud-Alexa ├── Cloud - Alexa.pdf ├── imp.txt └── parte6 │ ├── interactionModels │ └── custom │ │ └── it-IT.json │ ├── lambda │ ├── lambda_function.py │ ├── requirements.txt │ └── utils.py │ └── skill.json ├── 15_Cloud_BLE ├── 15_Cloud_BLE_Relazione.pdf ├── Cloud - BLE.pdf ├── indirizzi_ble_esp32.txt ├── parte1 │ └── server_BLE │ │ └── server_BLE.ino ├── parte4 │ └── client_ble.py └── parte5 │ └── server_BLE_sensore_motore │ └── server_BLE_sensore_motore.ino ├── LICENSE ├── README.it.md ├── README.md ├── lib.md └── pdfs ├── Cloud - Alexa.pdf ├── Cloud - BLE.pdf ├── Cloud - IFTTT.pdf ├── Cloud - Infrared.pdf ├── Cloud - Lego EV3 Robot.pdf ├── Cloud - MQTT - ESP8266.pdf ├── Cloud - RF433MHz.pdf ├── Cloud - Telegram.pdf ├── Cloud - Tuya.pdf ├── Cloud - Zigbee Conbee 2.pdf ├── Cloud - Zigbee2MQTT 1.pdf └── Cloud - rete mesh su NRF24.pdf /.gitignore: -------------------------------------------------------------------------------- 1 | #VS 2 | .vs/ 3 | 4 | #VScode 5 | .vscode/ 6 | 7 | #idea 8 | .idea/ 9 | 10 | # Byte-compiled / optimized / DLL files 11 | __pycache__/ 12 | *.py[cod] 13 | *$py.class 14 | 15 | # C extensions 16 | *.so 17 | 18 | # Distribution / packaging 19 | .Python 20 | build/ 21 | develop-eggs/ 22 | dist/ 23 | downloads/ 24 | eggs/ 25 | .eggs/ 26 | lib/ 27 | lib64/ 28 | parts/ 29 | sdist/ 30 | var/ 31 | wheels/ 32 | pip-wheel-metadata/ 33 | share/python-wheels/ 34 | *.egg-info/ 35 | .installed.cfg 36 | *.egg 37 | MANIFEST 38 | 39 | # PyInstaller 40 | # Usually these files are written by a python script from a template 41 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 42 | *.manifest 43 | *.spec 44 | 45 | # Installer logs 46 | pip-log.txt 47 | pip-delete-this-directory.txt 48 | 49 | # Unit test / coverage reports 50 | htmlcov/ 51 | .tox/ 52 | .nox/ 53 | .coverage 54 | .coverage.* 55 | .cache 56 | nosetests.xml 57 | coverage.xml 58 | *.cover 59 | *.py,cover 60 | .hypothesis/ 61 | .pytest_cache/ 62 | 63 | # Translations 64 | *.mo 65 | *.pot 66 | 67 | # Django stuff: 68 | *.log 69 | local_settings.py 70 | db.sqlite3 71 | db.sqlite3-journal 72 | 73 | # Flask stuff: 74 | instance/ 75 | .webassets-cache 76 | 77 | # Scrapy stuff: 78 | .scrapy 79 | 80 | # Sphinx documentation 81 | docs/_build/ 82 | 83 | # PyBuilder 84 | target/ 85 | 86 | # Jupyter Notebook 87 | .ipynb_checkpoints 88 | 89 | # IPython 90 | profile_default/ 91 | ipython_config.py 92 | 93 | # pyenv 94 | .python-version 95 | 96 | # pipenv 97 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 98 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 99 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 100 | # install all needed dependencies. 101 | #Pipfile.lock 102 | 103 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 104 | __pypackages__/ 105 | 106 | # Celery stuff 107 | celerybeat-schedule 108 | celerybeat.pid 109 | 110 | # SageMath parsed files 111 | *.sage.py 112 | 113 | # Environments 114 | .env 115 | .venv 116 | env/ 117 | venv/ 118 | ENV/ 119 | env.bak/ 120 | venv.bak/ 121 | 122 | # Spyder project settings 123 | .spyderproject 124 | .spyproject 125 | 126 | # Rope project settings 127 | .ropeproject 128 | 129 | # mkdocs documentation 130 | /site 131 | 132 | # mypy 133 | .mypy_cache/ 134 | .dmypy.json 135 | dmypy.json 136 | 137 | # Pyre type checker 138 | .pyre/ 139 | -------------------------------------------------------------------------------- /01_TrasmissioneSerialeArduino/01_TrasmissioneSerialeArduino_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/01_TrasmissioneSerialeArduino/01_TrasmissioneSerialeArduino_Relazione.pdf -------------------------------------------------------------------------------- /01_TrasmissioneSerialeArduino/Trasmissione seriale su Arduino.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/01_TrasmissioneSerialeArduino/Trasmissione seriale su Arduino.pdf -------------------------------------------------------------------------------- /01_TrasmissioneSerialeArduino/fase1/analisiSegnaleOscilloscopio/analisiSegnaleOscilloscopio.ino: -------------------------------------------------------------------------------- 1 | void setup() { 2 | Serial.begin(300); 3 | } 4 | 5 | void loop() { 6 | while(true){ 7 | Serial.print('a'); 8 | delay(500); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /01_TrasmissioneSerialeArduino/fase1/segnale.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/01_TrasmissioneSerialeArduino/fase1/segnale.png -------------------------------------------------------------------------------- /01_TrasmissioneSerialeArduino/fase2/codiceInvio/codiceInvio.ino: -------------------------------------------------------------------------------- 1 | void setup() { 2 | Serial.begin(1200); 3 | } 4 | 5 | void loop() { 6 | if(Serial.available() > 0) { 7 | char invio = Serial.read(); 8 | Serial.print(invio); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /01_TrasmissioneSerialeArduino/fase2/codiceRicezione/codiceRicezione.ino: -------------------------------------------------------------------------------- 1 | void setup() 2 | { 3 | Serial.begin(1200); 4 | pinMode(13, INPUT); 5 | } 6 | 7 | void loop() 8 | { 9 | if (digitalRead(13) == LOW) 10 | { 11 | delayMicroseconds(1250); 12 | char c = 0; 13 | for (int i = 0; i < 8; i++) 14 | { 15 | int var = digitalRead(13); 16 | bitWrite(c, i, var); 17 | delayMicroseconds(833); 18 | } 19 | Serial.print(c); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /02_Python-2-Seriale/02_Python_2_Seriale_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/02_Python-2-Seriale/02_Python_2_Seriale_Relazione.pdf -------------------------------------------------------------------------------- /02_Python-2-Seriale/Python - 2 - Seriale.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/02_Python-2-Seriale/Python - 2 - Seriale.pdf -------------------------------------------------------------------------------- /02_Python-2-Seriale/parte1/sensorePython.py: -------------------------------------------------------------------------------- 1 | import serial 2 | import time 3 | 4 | arduino = serial.Serial('COM3', 9600) 5 | time.sleep(1) 6 | 7 | print('inizio ricezione dei dati') 8 | while True: 9 | b = bytearray(arduino.readline()) 10 | s = int(b.decode()) 11 | print(s) 12 | time.sleep(0.5) -------------------------------------------------------------------------------- /02_Python-2-Seriale/parte1/sketchSensore/sketchSensore.ino: -------------------------------------------------------------------------------- 1 | void setup() 2 | { 3 | Serial.begin(9600); 4 | } 5 | void loop() 6 | { 7 | int num = analogRead(A0); 8 | Serial.println(num); 9 | delay(1000); 10 | } 11 | -------------------------------------------------------------------------------- /02_Python-2-Seriale/parte2/fase 2.2/sketchAttuatore/sketchAttuatore.ino: -------------------------------------------------------------------------------- 1 | char comando; 2 | int velocita = 500; 3 | 4 | void setup() { 5 | pinMode(13, OUTPUT); 6 | Serial.begin(9600); 7 | } 8 | 9 | void loop() { 10 | comando = Serial.read(); 11 | if (comando == 'a') { 12 | digitalWrite(7, 1); 13 | digitalWrite(8, 0); 14 | analogWrite(6, velocita); 15 | Serial.println("ON"); 16 | } 17 | if (comando == 's') { 18 | digitalWrite(7, 0); 19 | digitalWrite(8, 1); 20 | analogWrite(6, 0); 21 | Serial.println("OFF"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /02_Python-2-Seriale/parte2/fase 2.3/sketchAttuatore/sketchAttuatore.ino: -------------------------------------------------------------------------------- 1 | void setup() 2 | { 3 | Serial.begin(9600); 4 | pinMode(3, OUTPUT); 5 | pinMode(5, OUTPUT); 6 | } 7 | 8 | void loop() 9 | { 10 | if (Serial.available()) 11 | { 12 | String str = Serial.readStringUntil('\n'); 13 | if (str.length() > 0) 14 | { 15 | int n = str.indexOf(";"); 16 | String rotazione = str.substring(0, n); 17 | Serial.println(rotazione); 18 | n += 1; 19 | int vel = str.substring(n, str.length()).toInt(); 20 | Serial.println(vel); 21 | if (rotazione == "avanti") 22 | { 23 | digitalWrite(5, LOW); 24 | digitalWrite(3, HIGH); 25 | analogWrite(9, vel); 26 | Serial.println("avanti"); 27 | } 28 | 29 | if (rotazione == "indietro") 30 | { 31 | digitalWrite(5, HIGH); 32 | digitalWrite(3, LOW); 33 | analogWrite(9, vel); 34 | Serial.println("indietro"); 35 | } 36 | if (rotazione == "stop") 37 | { 38 | digitalWrite(5, LOW); 39 | digitalWrite(3, LOW); 40 | analogWrite(9, 0); 41 | Serial.println("spento"); 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /02_Python-2-Seriale/parte2/fase 2.4/attuatorePython.py: -------------------------------------------------------------------------------- 1 | import serial 2 | import time 3 | 4 | arduino = serial.Serial('COM3', 9600) 5 | time.sleep(1) 6 | 7 | print('inizio invio dei dati') 8 | while True: 9 | val = input("direzione;velocità"+"\n").encode() 10 | arduino.write(val) -------------------------------------------------------------------------------- /02_Python-2-Seriale/parte2/fase 2.4/sketchAttuatore_fase_2.4/sketchAttuatore_fase_2.4.ino: -------------------------------------------------------------------------------- 1 | void setup() 2 | { 3 | Serial.begin(9600); 4 | pinMode(9, OUTPUT); 5 | pinMode(5, OUTPUT); 6 | } 7 | 8 | void loop() 9 | { 10 | if (Serial.available()) 11 | { 12 | String str = Serial.readStringUntil('\n'); 13 | if (str.length() > 0) 14 | { 15 | int n = str.indexOf(";"); 16 | String rotazione = str.substring(0, n); 17 | n += 1; 18 | int vel = str.substring(n, str.length()).toInt(); 19 | if (rotazione == "A") 20 | { 21 | digitalWrite(9, LOW); 22 | digitalWrite(5, HIGH); 23 | analogWrite(3, vel); 24 | } 25 | if (rotazione == "I") 26 | { 27 | digitalWrite(9, HIGH); 28 | digitalWrite(5, LOW); 29 | analogWrite(3, vel); 30 | } 31 | if (rotazione == "S") 32 | { 33 | digitalWrite(9, HIGH); 34 | digitalWrite(5, LOW); 35 | analogWrite(3, 0); 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /03_Python-3-Pacchetto_livello_3_7_del modello_ISO-OSI_su_seriale/03_Python_3_Pacchetto_livello_3_7_modello_ISOOSI_su_seriale_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/03_Python-3-Pacchetto_livello_3_7_del modello_ISO-OSI_su_seriale/03_Python_3_Pacchetto_livello_3_7_modello_ISOOSI_su_seriale_Relazione.pdf -------------------------------------------------------------------------------- /03_Python-3-Pacchetto_livello_3_7_del modello_ISO-OSI_su_seriale/Python - 3 - Pacchetto Livello 3 e 7 ISO-OSI su seriale.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/03_Python-3-Pacchetto_livello_3_7_del modello_ISO-OSI_su_seriale/Python - 3 - Pacchetto Livello 3 e 7 ISO-OSI su seriale.pdf -------------------------------------------------------------------------------- /03_Python-3-Pacchetto_livello_3_7_del modello_ISO-OSI_su_seriale/parte3/fase 3.1/sketch_sensore/sketch_sensore.ino: -------------------------------------------------------------------------------- 1 | #define ID "BE" 2 | #define MITTENTE "M001" 3 | #define DESTINATARIO "D031" 4 | #define TIPO "S1" 5 | #define VUOTO "----------------" 6 | 7 | struct pacchettoS1 { 8 | char id[2]; 9 | char mittente[4]; 10 | char destinatario[4]; 11 | char tipo[2]; 12 | char valoreSensore[4]; 13 | char vuoto[16]; 14 | }; 15 | 16 | void setup() 17 | { 18 | Serial.begin(9600); 19 | } 20 | void loop() 21 | { 22 | int num = analogRead(A0); 23 | char s[5]; 24 | sprintf(s, "%04d", num); 25 | 26 | struct pacchettoS1 msg; 27 | memcpy(msg.id, ID, sizeof(msg.id)); 28 | memcpy(msg.mittente, MITTENTE, sizeof(msg.mittente)); 29 | memcpy(msg.destinatario, DESTINATARIO, sizeof(msg.destinatario)); 30 | memcpy(msg.tipo, TIPO, sizeof(msg.tipo)); 31 | memcpy(msg.valoreSensore, s, sizeof(msg.valoreSensore)); 32 | memcpy(msg.vuoto, VUOTO, sizeof(msg.vuoto)); 33 | 34 | Serial.write((byte *)&msg, sizeof(msg)); 35 | 36 | delay(1000); 37 | } 38 | -------------------------------------------------------------------------------- /03_Python-3-Pacchetto_livello_3_7_del modello_ISO-OSI_su_seriale/parte3/fase 3.2/ricezione_dati_sensore.py: -------------------------------------------------------------------------------- 1 | import serial 2 | import struct 3 | IDCORRETTO = "BE" 4 | DESTINATARIOCORRETTO = "D031" 5 | 6 | arduino = serial.Serial('COM3', 9600) 7 | 8 | print('inizio ricezione dei dati') 9 | while True: 10 | val = arduino.read(32) 11 | pack = struct.unpack("2s 4s 4s 2s 4s 16s", val) 12 | id=pack[0].decode() 13 | mittente=pack[1].decode() 14 | destinatario=pack[2].decode() 15 | tipo=pack[3].decode() 16 | valoreSensore=pack[4].decode() 17 | vuoto=pack[5].decode() 18 | if (id==IDCORRETTO)and(destinatario==DESTINATARIOCORRETTO): 19 | print("id e destinatario corretti") 20 | print(valoreSensore) 21 | else: 22 | print("pacchetto scartato") -------------------------------------------------------------------------------- /03_Python-3-Pacchetto_livello_3_7_del modello_ISO-OSI_su_seriale/parte3/fase 3.3/invio_comandi_al_motore.py: -------------------------------------------------------------------------------- 1 | import serial; 2 | import struct; 3 | ID=b"BE" 4 | MITTENTE=b"M001" 5 | DESTINATARIO=b"D031" 6 | TIPO=b"A1" 7 | VUOTO=b"----------------" 8 | 9 | arduino = serial.Serial('COM3', 9600) 10 | 11 | print('inizio invio dei dati') 12 | while True: 13 | d = input("direzione A/I/S: ") 14 | if (d=="S"): 15 | v=0 16 | else: 17 | v = input("velocità: ") 18 | VELOCITA=str(v).zfill(3).encode() 19 | DIREZIONE = str(d).zfill(1).encode() 20 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, DIREZIONE, VELOCITA, VUOTO) 21 | arduino.write(pack) 22 | print(pack) -------------------------------------------------------------------------------- /03_Python-3-Pacchetto_livello_3_7_del modello_ISO-OSI_su_seriale/parte3/fase 3.4/sketch_motore/sketch_motore.ino: -------------------------------------------------------------------------------- 1 | #define ID "BE" 2 | #define DESTINATARIO "D031" 3 | 4 | struct pacchettoA1 5 | { 6 | char id[2]; 7 | char mittente[4]; 8 | char destinatario[4]; 9 | char tipo[2]; 10 | char direzione[1]; 11 | char velocita[3]; 12 | char vuoto[16]; 13 | }; 14 | 15 | void setup() 16 | { 17 | Serial.begin(9600); 18 | pinMode(9, OUTPUT); 19 | pinMode(5, OUTPUT); 20 | } 21 | 22 | void loop() 23 | { 24 | struct pacchettoA1 msg; 25 | if (Serial.available()) 26 | { 27 | Serial.readBytes((byte*) &msg, sizeof(msg)); 28 | int controlloId = memcmp(ID, msg.id, 2); 29 | int controlloDest = memcmp(DESTINATARIO, msg.destinatario, 4); 30 | char vel[4]; 31 | if (controlloId == 0 && controlloDest == 0) 32 | { 33 | memcpy(vel,msg.velocita,sizeof(msg.velocita)); 34 | vel[3] = '\0'; 35 | int velocita = atoi(vel); 36 | if (memcmp("A",msg.direzione, 1) == 0) 37 | { 38 | digitalWrite(5, LOW); 39 | digitalWrite(9, HIGH); 40 | analogWrite(3, velocita); 41 | } 42 | 43 | if (memcmp("I",msg.direzione, 1) == 0) 44 | { 45 | digitalWrite(5, HIGH); 46 | digitalWrite(9, LOW); 47 | analogWrite(3, velocita); 48 | } 49 | if (memcmp("S",msg.direzione, 1) == 0) 50 | { 51 | digitalWrite(5, LOW); 52 | digitalWrite(9, LOW); 53 | analogWrite(3, 0); 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /04_Python-4-GUI/04_Python_4_GUI_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/04_Python-4-GUI/04_Python_4_GUI_Relazione.pdf -------------------------------------------------------------------------------- /04_Python-4-GUI/Python - 4 - GUI 1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/04_Python-4-GUI/Python - 4 - GUI 1.pdf -------------------------------------------------------------------------------- /04_Python-4-GUI/parte2/soluzione1/guiAttuatore1.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import serial 3 | import struct 4 | import serial.tools.list_ports 5 | ID=b"BE" 6 | MITTENTE=b"M001" 7 | DESTINATARIO=b"D031" 8 | TIPO=b"A1" 9 | VUOTO=b"----------------" 10 | direzione = b"A" 11 | velocita = 0 12 | 13 | ports = serial.tools.list_ports.comports() 14 | comDescList = [] 15 | for port, desc, _ in sorted(ports): 16 | comDescList.append(port) 17 | 18 | porta = comDescList[0] 19 | arduino = serial.Serial(porta, 9600) 20 | window = tk.Tk() 21 | window.geometry("265x100") 22 | window.title("Controllo motore") 23 | window.resizable(False, False) 24 | 25 | def StampaVelocità(vel): 26 | velocitaText_Label = tk.Label(window, text = "Velocità = " + str(vel)).grid(row=2, column=0, pady=3) 27 | 28 | def AumentaVelocita10(): 29 | global velocita 30 | if velocita >= 250: 31 | velocita = 250 32 | else: 33 | velocita += 10 34 | StampaVelocità(velocita) 35 | v=str(velocita).zfill(3).encode() 36 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 37 | arduino.write(pack) 38 | print(pack) 39 | 40 | def DiminuisciVelocita10(): 41 | global velocita 42 | if velocita <= 0: 43 | velocita = 0 44 | else: 45 | velocita -= 10 46 | StampaVelocità(velocita) 47 | v=str(velocita).zfill(3).encode() 48 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 49 | arduino.write(pack) 50 | print(pack) 51 | 52 | def DirezioneAvanti(): 53 | global direzione 54 | direzione = b"A" 55 | StampaVelocità(velocita) 56 | v=str(velocita).zfill(3).encode() 57 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 58 | arduino.write(pack) 59 | 60 | def DirezioneIndietro(): 61 | global direzione 62 | direzione = b"I" 63 | StampaVelocità(velocita) 64 | v=str(velocita).zfill(3).encode() 65 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 66 | arduino.write(pack) 67 | 68 | aumentaVel_button = tk.Button(text="Aumenta velocità di 10", command=AumentaVelocita10).grid(row=0, column=0, sticky="W") 69 | 70 | dimiuisciVel_button = tk.Button(text="Dimiuisci velocità di 10", command=DiminuisciVelocita10).grid(row=0, column=1, sticky="E") 71 | 72 | avantiDir_button = tk.Button(text="Avanti", command=DirezioneAvanti).grid(row=1, column=0, sticky="W") 73 | 74 | indietroDir_button = tk.Button(text="Indietro", command=DirezioneIndietro).grid(row=1, column=1, sticky="E") 75 | 76 | if __name__ == "__main__": 77 | window.mainloop() 78 | 79 | -------------------------------------------------------------------------------- /04_Python-4-GUI/parte2/soluzione2/guiAttuatore2.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import serial 3 | import struct 4 | ID=b"BE" 5 | MITTENTE=b"M001" 6 | DESTINATARIO=b"D031" 7 | TIPO=b"A1" 8 | VUOTO=b"----------------" 9 | direzione = b"A" 10 | velocita = 0 11 | 12 | arduino = serial.Serial('COM3', 9600) 13 | window = tk.Tk() 14 | window.geometry("225x60") 15 | window.title("Controllo motore") 16 | window.resizable(False, False) 17 | 18 | def DirezioneAvanti(): 19 | global direzione 20 | global velocita 21 | direzione = b"A" 22 | velocita = entry1.get() 23 | if int(velocita) > 255: 24 | velocita = 255 25 | entry1.delete(0, tk.END) 26 | entry1.insert(0, "255") 27 | elif int(velocita) < 0: 28 | velocita = 0 29 | entry1.delete(0, tk.END) 30 | entry1.insert(0, "0") 31 | v = str(velocita).zfill(3).encode() 32 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 33 | print(pack) 34 | arduino.write(pack) 35 | 36 | def DirezioneIndietro(): 37 | global direzione 38 | global velocita 39 | direzione = b"I" 40 | velocita = entry1.get() 41 | if int(velocita)>255: 42 | velocita = 255 43 | entry1.delete(0, tk.END) 44 | entry1.insert(0, "255") 45 | elif int(velocita) < 0: 46 | velocita = 0 47 | entry1.delete(0, tk.END) 48 | entry1.insert(0, "0") 49 | v = str(velocita).zfill(3).encode() 50 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 51 | print(pack) 52 | arduino.write(pack) 53 | 54 | def InviaVelocita(event): 55 | global direzione 56 | global velocita 57 | velocita = entry1.get() 58 | if int(velocita)>255: 59 | velocita = 255 60 | entry1.delete(0, tk.END) 61 | entry1.insert(0, "255") 62 | elif int(velocita) < 0: 63 | velocita = 0 64 | entry1.delete(0, tk.END) 65 | entry1.insert(0, "0") 66 | v = str(velocita).zfill(3).encode() 67 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 68 | print(pack) 69 | arduino.write(pack) 70 | 71 | avantiDir_button = tk.Button(text="Avanti", command=DirezioneAvanti).grid(row=0, column=0) 72 | 73 | indietroDir_button = tk.Button(text="Indietro", command=DirezioneIndietro).grid(row=0, column=2) 74 | 75 | velocitaText_Label = tk.Label(window, text = "Velocità:").grid(row=1, column=0, pady=5) 76 | 77 | entry1 = tk.Entry(window, width=20) 78 | entry1.grid(row=1, column=1) 79 | 80 | enterEvent = window.bind('', InviaVelocita) 81 | 82 | if __name__ == "__main__": 83 | window.mainloop() -------------------------------------------------------------------------------- /04_Python-4-GUI/parte2/soluzione3/guiAttuatore3.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import serial 3 | import time 4 | import struct 5 | ID=b"BE" 6 | MITTENTE=b"M001" 7 | DESTINATARIO=b"D031" 8 | TIPO=b"A1" 9 | VUOTO=b"----------------" 10 | direzione = b"A" 11 | 12 | arduino = serial.Serial('COM3', 9600) 13 | window = tk.Tk() 14 | window.geometry("570x100") 15 | window.title("Controllo motore") 16 | window.resizable(False, False) 17 | 18 | def update_lbl(val): 19 | if int(val)<0: 20 | direzione = b"I" 21 | vel = ~int(val)+1 22 | v = str(vel).zfill(3).encode() 23 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 24 | print(pack) 25 | arduino.write(pack) 26 | else: 27 | direzione = b"A" 28 | v = str(val).zfill(3).encode() 29 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 30 | print(pack) 31 | arduino.write(pack) 32 | 33 | velocitaText_Label = tk.Label(window, text = "Velocità:").grid(row=0, column=0, pady=4) 34 | 35 | scale = tk.Scale(window, orient="horizontal", length=510, from_=-255.0, to=255.0, command=update_lbl, cursor="target") 36 | scale.grid(column=1, row=0) 37 | scale.set(0) 38 | 39 | if __name__ == "__main__": 40 | window.mainloop() -------------------------------------------------------------------------------- /04_Python-4-GUI/parte3/soluzione1/guiSensore1.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import serial 3 | import struct 4 | IDCORRETTO = "BE" 5 | DESTINATARIOCORRETTO = "D031" 6 | 7 | arduino = serial.Serial('COM3', 9600) 8 | window = tk.Tk() 9 | window.geometry("225x60") 10 | window.title("Controllo sensore") 11 | window.resizable(False, False) 12 | 13 | def StampaValori(val): 14 | valoreText_Label = tk.Label(window, text = "Valore sensore = " + str(val), font=('Courier New', 10)).grid(row=1, column=0, pady=13) 15 | 16 | def funz(window): 17 | val = arduino.read(32) 18 | pack = struct.unpack("2s 4s 4s 2s 4s 16s", val) 19 | print(pack) 20 | id=pack[0].decode() 21 | mittente=pack[1].decode() 22 | destinatario=pack[2].decode() 23 | tipo=pack[3].decode() 24 | valoreSensore=pack[4].decode() 25 | vuoto=pack[5].decode() 26 | if (id==IDCORRETTO)and(destinatario==DESTINATARIOCORRETTO): 27 | print("id e destinatario corretti") 28 | print(valoreSensore) 29 | s=int(valoreSensore) 30 | StampaValori(valoreSensore) 31 | else: 32 | print("pacchetto scartato") 33 | window.after(1000, funz, window) 34 | 35 | window.after(1000, funz, window) 36 | 37 | if __name__ == "__main__": 38 | window.mainloop() -------------------------------------------------------------------------------- /04_Python-4-GUI/parte3/soluzione2/guiSensore2.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import serial 3 | import struct 4 | IDCORRETTO = "BE" 5 | DESTINATARIOCORRETTO = "D031" 6 | 7 | arduino = serial.Serial('COM3', 9600) 8 | window = tk.Tk() 9 | C = tk.Canvas(window, bg="purple", height=250, width=255) 10 | C.pack() 11 | 12 | rettangolo = C.create_rectangle(0, 0, 0, 0) 13 | 14 | def funz(window): 15 | global rettangolo 16 | C.delete(rettangolo) 17 | val = arduino.read(32) 18 | pack = struct.unpack("2s 4s 4s 2s 4s 16s", val) 19 | print(pack) 20 | id=pack[0].decode() 21 | mittente=pack[1].decode() 22 | destinatario=pack[2].decode() 23 | tipo=pack[3].decode() 24 | valoreSensore=pack[4].decode() 25 | vuoto=pack[5].decode() 26 | if (id==IDCORRETTO)and(destinatario==DESTINATARIOCORRETTO): 27 | print("id e destinatario corretti, valore del sensore = "+valoreSensore) 28 | v = int(valoreSensore) 29 | coordinate = 0, 70, v/4, 150 30 | rettangolo = C.create_rectangle(coordinate, fill="yellow") 31 | else: 32 | print("pacchetto scartato") 33 | 34 | window.after(1000, funz, window) 35 | 36 | window.after(1000, funz, window) 37 | 38 | if __name__ == "__main__": 39 | window.mainloop() -------------------------------------------------------------------------------- /04_Python-4-GUI/parte3/soluzione3/guiSensore3.py: -------------------------------------------------------------------------------- 1 | import serial 2 | import struct 3 | import matplotlib.pyplot as plt 4 | import matplotlib.animation as animation 5 | import datetime as dt 6 | import serial.tools.list_ports 7 | IDCORRETTO = "BE" 8 | DESTINATARIOCORRETTO = "D031" 9 | 10 | ports = serial.tools.list_ports.comports() 11 | comDescList = [] 12 | for port, desc, _ in sorted(ports): 13 | comDescList.append(port) 14 | 15 | porta = comDescList[0] 16 | print(porta) 17 | arduino = serial.Serial(porta, 9600) 18 | fig = plt.figure() 19 | ax = fig.add_subplot(1, 1, 1) 20 | xs = [] 21 | ys = [] 22 | 23 | def animate(i, xs, ys): 24 | val = arduino.read(32) 25 | pack = struct.unpack("2s 4s 4s 2s 4s 16s", val) 26 | print(pack) 27 | id=pack[0].decode() 28 | mittente=pack[1].decode() 29 | destinatario=pack[2].decode() 30 | tipo=pack[3].decode() 31 | valoreSensore=pack[4].decode() 32 | vuoto=pack[5].decode() 33 | if (id==IDCORRETTO)and(destinatario==DESTINATARIOCORRETTO): 34 | print("id e destinatario corretti, valore del sensore = "+valoreSensore) 35 | xs.append(dt.datetime.now().strftime('%H:%M:%S')) 36 | ys.append(int(valoreSensore)) 37 | xs = xs[-21:-1] 38 | ys = ys[-21:-1] 39 | ax.clear() 40 | ax.plot(xs, ys, marker="o") 41 | plt.xticks(rotation=45, ha='right') 42 | plt.subplots_adjust(bottom=0.30) 43 | plt.title("Grafico dei valori del sensore") 44 | plt.xlabel("X - Tempo") 45 | plt.ylabel("Y - Valori sensore") 46 | else: 47 | print("pacchetto scartato") 48 | 49 | ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=1000) 50 | plt.show() -------------------------------------------------------------------------------- /05_Python-5-JSON/05_Python_5_JSON_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/05_Python-5-JSON/05_Python_5_JSON_Relazione.pdf -------------------------------------------------------------------------------- /05_Python-5-JSON/Python - 5 - JSON.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/05_Python-5-JSON/Python - 5 - JSON.pdf -------------------------------------------------------------------------------- /05_Python-5-JSON/parte1/esercizioDiz1.py: -------------------------------------------------------------------------------- 1 | lista = [] 2 | 3 | for i in range(7): 4 | dataOra = input("inserire la data e l'ora: ") 5 | val = int(input("inserire il valore: ")) 6 | dizionario = {'DataOra': dataOra, 'Valore' : val} 7 | lista.append(dizionario) 8 | 9 | print("\n") 10 | print(lista[-5:]) -------------------------------------------------------------------------------- /05_Python-5-JSON/parte2/esDiz1.json: -------------------------------------------------------------------------------- 1 | [{"DataOra": 1, "Valore": 1}, {"DataOra": 2, "Valore": 2}, {"DataOra": 3, "Valore": 3}, {"DataOra": 4, "Valore": 4}, {"DataOra": 5, "Valore": 5}, {"DataOra": 6, "Valore": 6}, {"DataOra": 7, "Valore": 7}] -------------------------------------------------------------------------------- /05_Python-5-JSON/parte2/esercizioDiz2.py: -------------------------------------------------------------------------------- 1 | import json 2 | lista = [] 3 | lista2 = [] 4 | 5 | for i in range(7): 6 | #dizionario = {'DataOra': i+1, 'Valore' : i+1} 7 | dataOra = input("inserire la data e l'ora: ") 8 | val = int(input("inserire il valore: ")) 9 | dizionario = {'DataOra': dataOra, 'Valore' : val} 10 | lista.append(dizionario) 11 | 12 | print("\n") 13 | data = json.dumps(lista) 14 | file = open('05_Python-5-JSON/parte2/esDiz1.json', 'w') 15 | file.write(data) 16 | file.close() 17 | 18 | with open('05_Python-5-JSON/parte2/esDiz1.json', 'r') as fp: 19 | lista2 = json.load(fp) 20 | 21 | print(lista2[-5:]) 22 | -------------------------------------------------------------------------------- /05_Python-5-JSON/parte3/datiSensore.json: -------------------------------------------------------------------------------- 1 | [{"DataOra": "2023-01-19 18:17:42", "Valore": 341}, {"DataOra": "2023-01-19 18:17:43", "Valore": 1023}, {"DataOra": "2023-01-19 18:17:44", "Valore": 595}, {"DataOra": "2023-01-19 18:17:45", "Valore": 164}, {"DataOra": "2023-01-19 18:17:46", "Valore": 1023}, {"DataOra": "2023-01-19 18:17:47", "Valore": 252}, {"DataOra": "2023-01-19 18:17:48", "Valore": 376}, {"DataOra": "2023-01-19 18:17:49", "Valore": 1023}, {"DataOra": "2023-01-19 18:17:50", "Valore": 1023}, {"DataOra": "2023-01-19 18:17:51", "Valore": 1023}] -------------------------------------------------------------------------------- /05_Python-5-JSON/parte3/esercizioSensJ.py: -------------------------------------------------------------------------------- 1 | import serial 2 | import struct 3 | import json 4 | import time 5 | import serial.tools.list_ports 6 | IDCORRETTO = "BE" 7 | DESTINATARIOCORRETTO = "D031" 8 | 9 | ports = serial.tools.list_ports.comports() 10 | comDescList = [] 11 | for port, desc, _ in sorted(ports): 12 | comDescList.append(port) 13 | 14 | arduino = serial.Serial(comDescList[0], 9600) 15 | lista = [] 16 | 17 | while True: 18 | val = arduino.read(32) 19 | pack = struct.unpack("2s 4s 4s 2s 4s 16s", val) 20 | print(pack) 21 | id=pack[0].decode() 22 | mittente=pack[1].decode() 23 | destinatario=pack[2].decode() 24 | tipo=pack[3].decode() 25 | valoreSensore=pack[4].decode() 26 | vuoto=pack[5].decode() 27 | if (id==IDCORRETTO)and(destinatario==DESTINATARIOCORRETTO): 28 | print("id e destinatario corretti e valoreSensore = " + valoreSensore) 29 | s=int(valoreSensore) 30 | dataOra = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) 31 | dizionario = {'DataOra': dataOra, 'Valore' : s} 32 | lista.append(dizionario) 33 | else: 34 | print("pacchetto scartato") 35 | data = json.dumps(lista[-10:]) 36 | #with open('05_Python-5-JSON/parte3/datiSensore.json', 'w') as fp: 37 | #fp.write(data) 38 | #with open('05_Python-5-JSON/parte3/datiSensore.json', 'r') as fp: 39 | #lista2 = json.load(fp) 40 | with open('08_Python-8-Form/parte2/datiSensore.json', 'w') as fp: 41 | fp.write(data) 42 | with open('08_Python-8-Form/parte2/datiSensore.json', 'r') as fp: 43 | lista2 = json.load(fp) 44 | with open('07_Python-7-Flask/parte6/template/datiSensore.json', 'w') as fp: 45 | fp.write(data) 46 | with open('07_Python-7-Flask/parte6/template/datiSensore.json', 'r') as fp: 47 | lista2 = json.load(fp) 48 | print(lista2) -------------------------------------------------------------------------------- /05_Python-5-JSON/parte3/sketch_sensore_json/sketch_sensore_json.ino: -------------------------------------------------------------------------------- 1 | #define ID "BE" 2 | #define MITTENTE "M001" 3 | #define DESTINATARIO "D031" 4 | #define TIPO "S1" 5 | #define VUOTO "----------------" 6 | 7 | struct pacchettoS1 { 8 | char id[2]; 9 | char mittente[4]; 10 | char destinatario[4]; 11 | char tipo[2]; 12 | char valoreSensore[4]; 13 | char vuoto[16]; 14 | }; 15 | 16 | void setup() 17 | { 18 | Serial.begin(9600); 19 | } 20 | void loop() 21 | { 22 | int num = analogRead(A0); 23 | char s[5]; 24 | sprintf(s, "%04d", num); 25 | 26 | struct pacchettoS1 msg; 27 | memcpy(msg.id, ID, sizeof(msg.id)); 28 | memcpy(msg.mittente, MITTENTE, sizeof(msg.mittente)); 29 | memcpy(msg.destinatario, DESTINATARIO, sizeof(msg.destinatario)); 30 | memcpy(msg.tipo, TIPO, sizeof(msg.tipo)); 31 | memcpy(msg.valoreSensore, s, sizeof(msg.valoreSensore)); 32 | memcpy(msg.vuoto, VUOTO, sizeof(msg.vuoto)); 33 | 34 | Serial.write((byte *)&msg, sizeof(msg)); 35 | 36 | delay(1000); 37 | } 38 | -------------------------------------------------------------------------------- /07_Python-7-Flask/07_Python_7_Flask_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/07_Python-7-Flask/07_Python_7_Flask_Relazione.pdf -------------------------------------------------------------------------------- /07_Python-7-Flask/Python - 7 - Flask 3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/07_Python-7-Flask/Python - 7 - Flask 3.pdf -------------------------------------------------------------------------------- /07_Python-7-Flask/parte1/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | parte1 8 | 9 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 |
Data e oraValore
2021-11-17 17.53.10125
2021-11-17 17.54.10127
2021-11-17 17.55.10131
34 |
35 | 36 | -------------------------------------------------------------------------------- /07_Python-7-Flask/parte2/index.html: -------------------------------------------------------------------------------- 1 |
Data e oraValore
2023-01-19 18:17:42341
2023-01-19 18:17:431023
2023-01-19 18:17:44595
2023-01-19 18:17:45164
2023-01-19 18:17:461023
2023-01-19 18:17:47252
2023-01-19 18:17:48376
2023-01-19 18:17:491023
2023-01-19 18:17:501023
2023-01-19 18:17:511023
-------------------------------------------------------------------------------- /07_Python-7-Flask/parte2/pyTohtml.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | with open('05_Python-5-JSON/parte3/datiSensore.json', 'r') as fp: 4 | lista = json.load(fp) 5 | date = [] 6 | valoriSensori = [] 7 | stringa = "" 8 | for i in range(len(lista)): 9 | date.append(lista[i]["DataOra"]) 10 | valoriSensori.append(lista[i]["Valore"]) 11 | stringa += ""+str(date[i])+""+str(valoriSensori[i])+"" 12 | stringaFinale= ""+stringa+"
Data e oraValore
" 13 | print (stringaFinale) 14 | with open("07_Python-7-Flask/parte2/index.html", "w") as ft: 15 | ft.write(stringaFinale) -------------------------------------------------------------------------------- /07_Python-7-Flask/parte3/datiSensore.json: -------------------------------------------------------------------------------- 1 | [{"DataOra": "2023-02-07 10:49:03", "Valore": 783}, {"DataOra": "2023-02-07 10:49:04", "Valore": 986}, {"DataOra": "2023-02-07 10:49:05", "Valore": 518}, {"DataOra": "2023-02-07 10:49:06", "Valore": 873}, {"DataOra": "2023-02-07 10:49:07", "Valore": 1023}, {"DataOra": "2023-02-07 10:49:08", "Valore": 942}, {"DataOra": "2023-02-07 10:49:09", "Valore": 11}, {"DataOra": "2023-02-07 10:49:10", "Valore": 469}, {"DataOra": "2023-02-07 10:49:11", "Valore": 513}, {"DataOra": "2023-02-07 10:49:12", "Valore": 225}] -------------------------------------------------------------------------------- /07_Python-7-Flask/parte3/flask1.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | import json 3 | import os 4 | 5 | path = os.getcwd()+'/datiSensore.json' 6 | app = Flask(__name__) 7 | @app.route('/') 8 | 9 | def returnHtml(): 10 | with open(path, 'r') as fp: 11 | lista = json.load(fp) 12 | date = [] 13 | valoriSensori = [] 14 | stringa = "" 15 | for i in range(len(lista)): 16 | date.append(lista[i]["DataOra"]) 17 | valoriSensori.append(lista[i]["Valore"]) 18 | stringa += ""+str(date[i])+""+str(valoriSensori[i])+"" 19 | stringaFinale= "Dati sensore"+stringa+"
Data e oraValore
" 20 | print(stringaFinale) 21 | return stringaFinale -------------------------------------------------------------------------------- /07_Python-7-Flask/parte4/fileComandi.txt: -------------------------------------------------------------------------------- 1 | ssh -N -4 -v -R 8105:172.23.224.1:5000 greppi@tunnel.vincenzov.net 2 | tunnel.vincenzov.net:8105 3 | 4 | ssh –N -4 –v –R 8106:172.17.3.95:5000 greppi@tunnel.vincenzov.net 5 | tunnel.vincenzov.net:8106 6 | 7 | py -m flask --app flask1 run --host 0.0.0.0 8 | ssh -N -4 -v -R 8105:172.23.224.1:5000 greppi@tunnel.vincenzov.net -------------------------------------------------------------------------------- /07_Python-7-Flask/parte6/plotly/datiSensore.json: -------------------------------------------------------------------------------- 1 | [{"DataOra": "2023-02-08 16:40:26", "Valore": 271}, {"DataOra": "2023-02-08 16:40:27", "Valore": 271}, {"DataOra": "2023-02-08 16:40:28", "Valore": 271}, {"DataOra": "2023-02-08 16:40:29", "Valore": 271}, {"DataOra": "2023-02-08 16:40:30", "Valore": 271}, {"DataOra": "2023-02-08 16:40:31", "Valore": 271}, {"DataOra": "2023-02-08 16:40:32", "Valore": 271}, {"DataOra": "2023-02-08 16:40:33", "Valore": 271}, {"DataOra": "2023-02-08 16:40:34", "Valore": 271}, {"DataOra": "2023-02-08 16:40:35", "Valore": 271}] -------------------------------------------------------------------------------- /07_Python-7-Flask/parte6/plotly/plotly1.py: -------------------------------------------------------------------------------- 1 | import json 2 | import plotly.express as px 3 | import pandas as pd 4 | import plotly 5 | from flask import Flask, render_template 6 | import os 7 | 8 | path = os.getcwd()+'/datiSensore.json' 9 | app = Flask(__name__) 10 | @app.route('/') 11 | 12 | def returnHtml(): 13 | with open(path, 'r') as fp: 14 | lista = json.load(fp) 15 | date = [] 16 | valoriSensori = [] 17 | for i in range(len(lista)): 18 | date.append(lista[i]["DataOra"]) 19 | valoriSensori.append(lista[i]["Valore"]) 20 | df = pd.DataFrame({ 21 | 'DataOra': date, 22 | 'Valore': valoriSensori}) 23 | fig = px.bar(df, x='DataOra', y='Valore', barmode='group') 24 | graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) 25 | return render_template('index.html', graphJSON=graphJSON) -------------------------------------------------------------------------------- /07_Python-7-Flask/parte6/plotly/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Dati sensore plotly 9 | 10 | 11 |

Hello Plotly (but not Dash)

12 |
13 | 14 | 18 | -------------------------------------------------------------------------------- /07_Python-7-Flask/parte6/template/datiSensore.json: -------------------------------------------------------------------------------- 1 | [{"DataOra": "2023-01-12 08:54:25", "Valore": 766}, {"DataOra": "2023-01-12 08:54:26", "Valore": 766}, {"DataOra": "2023-01-12 08:54:27", "Valore": 766}, {"DataOra": "2023-01-12 08:54:28", "Valore": 391}, {"DataOra": "2023-01-12 08:54:29", "Valore": 848}, {"DataOra": "2023-01-12 08:54:30", "Valore": 282}, {"DataOra": "2023-01-12 08:54:31", "Valore": 282}, {"DataOra": "2023-01-12 08:54:32", "Valore": 282}, {"DataOra": "2023-01-12 08:54:33", "Valore": 282}] -------------------------------------------------------------------------------- /07_Python-7-Flask/parte6/template/template1.py: -------------------------------------------------------------------------------- 1 | from flask import render_template 2 | from flask import Flask 3 | import json 4 | import os 5 | 6 | pathJ = os.getcwd()+'/datiSensore.json' 7 | app = Flask(__name__) 8 | @app.route('/') 9 | 10 | def returnHtml(): 11 | with open(pathJ, 'r') as fp: 12 | lista = json.load(fp) 13 | return render_template('index.html', dizValori=lista) 14 | if __name__=="__main__": 15 | app.run(debug=True) -------------------------------------------------------------------------------- /07_Python-7-Flask/parte6/template/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Dati sensore 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | {% for i in dizValori %} 17 | 18 | 19 | 20 | 21 | {% endfor %} 22 | 23 |
Data e oraValore
{{i["DataOra"]}}{{i["Valore"]}}
24 | 25 | -------------------------------------------------------------------------------- /08_Python-8-Form/08_Python_8_Form_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/08_Python-8-Form/08_Python_8_Form_Relazione.pdf -------------------------------------------------------------------------------- /08_Python-8-Form/Python - 8 - Form.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/08_Python-8-Form/Python - 8 - Form.pdf -------------------------------------------------------------------------------- /08_Python-8-Form/parte1/ricevi.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, render_template 2 | import serial 3 | import struct 4 | import serial.tools.list_ports 5 | ID=b"BE" 6 | MITTENTE=b"M001" 7 | DESTINATARIO=b"D031" 8 | TIPO=b"A1" 9 | VUOTO=b"----------------" 10 | direzione = b"A" 11 | 12 | ports = serial.tools.list_ports.comports() 13 | comDescList = [] 14 | for port, desc, _ in sorted(ports): 15 | comDescList.append(port) 16 | 17 | arduino = serial.Serial(comDescList[0], 9600) 18 | app = Flask(__name__) 19 | 20 | @app.route("/") 21 | def inviaFormVuoto(): 22 | return(render_template("index.html")) 23 | 24 | @app.route("/ricevi") 25 | def riceviForm(): 26 | val = request.args["velocita"] 27 | if(request.args["btn"] == "avanti"): 28 | direzione = b"A" 29 | else: 30 | direzione = b"I" 31 | v = str(val).zfill(3).encode() 32 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 33 | print(pack) 34 | arduino.write(pack) 35 | return("Velocità: "+request.args["velocita"] + " " + "Direzione: " + request.args["btn"]) -------------------------------------------------------------------------------- /08_Python-8-Form/parte1/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Controllo motore 8 | 9 | 10 |

Controllo motore

11 |
12 | 13 | 14 |
15 | 16 | 17 |
18 | 19 | 20 |
21 | 22 |
23 | 24 | -------------------------------------------------------------------------------- /08_Python-8-Form/parte2/datiSensore.json: -------------------------------------------------------------------------------- 1 | [{"DataOra": "2023-02-09 08:23:43", "Valore": 606}, {"DataOra": "2023-02-09 08:23:44", "Valore": 606}, {"DataOra": "2023-02-09 08:23:45", "Valore": 606}, {"DataOra": "2023-02-09 08:23:46", "Valore": 606}, {"DataOra": "2023-02-09 08:23:47", "Valore": 606}, {"DataOra": "2023-02-09 08:23:48", "Valore": 606}, {"DataOra": "2023-02-09 08:23:49", "Valore": 606}, {"DataOra": "2023-02-09 08:23:50", "Valore": 606}, {"DataOra": "2023-02-09 08:23:51", "Valore": 606}, {"DataOra": "2023-02-09 08:23:52", "Valore": 606}] -------------------------------------------------------------------------------- /08_Python-8-Form/parte2/ricevi2.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, render_template, redirect 2 | import serial 3 | import struct 4 | import os 5 | import json 6 | import plotly.express as px 7 | import pandas as pd 8 | import plotly 9 | import serial.tools.list_ports 10 | ID=b"BE" 11 | MITTENTE=b"M001" 12 | DESTINATARIO=b"D031" 13 | TIPO=b"A1" 14 | VUOTO=b"----------------" 15 | IDCORRETTO = "BE" 16 | DESTINATARIOCORRETTO = "D031" 17 | direzione = b"A" 18 | 19 | pathJ = os.getcwd()+'/datiSensore.json' 20 | 21 | ports = serial.tools.list_ports.comports() 22 | comDescList = [] 23 | for port, desc, _ in sorted(ports): 24 | comDescList.append(port) 25 | 26 | arduinoAttuatore = serial.Serial(comDescList[0], 9600) 27 | app = Flask(__name__) 28 | 29 | lista = [] 30 | @app.route('/') 31 | def returnHtml(): 32 | with open(pathJ, 'r') as fp: 33 | lista = json.load(fp) 34 | date = [] 35 | valoriSensori = [] 36 | for i in range(len(lista)): 37 | date.append(lista[i]["DataOra"]) 38 | valoriSensori.append(lista[i]["Valore"]) 39 | df = pd.DataFrame({ 40 | 'DataOra': date, 41 | 'Valore': valoriSensori}) 42 | fig = px.bar(df, x='DataOra', y='Valore', barmode='group') 43 | graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) 44 | return render_template('index.html', dizValori=lista, graphJSON=graphJSON) 45 | 46 | @app.route("/ricevi") 47 | def riceviForm(): 48 | val = request.args["velocita"] 49 | if(request.args["btn"] == "avanti"): 50 | direzione = b"A" 51 | else: 52 | direzione = b"I" 53 | v = str(val).zfill(3).encode() 54 | pack=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 55 | print(pack) 56 | arduinoAttuatore.write(pack) 57 | return redirect("Velocità: "+request.args["velocita"] + " " + "Direzione: " + request.args["btn"]) -------------------------------------------------------------------------------- /08_Python-8-Form/parte2/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Controllo motore e sensore 9 | 12 | 13 | 14 |

Controllo motore

15 |
16 | 17 | 18 | 19 |
20 | 21 | 22 |
23 | 24 | 25 |
26 |

Tabella valori del sensore

27 | 28 | 29 | 30 | 31 | {% for i in dizValori %} 32 | 33 | 34 | 35 | 36 | {% endfor %} 37 | 38 |
Data e oraValore
{{i["DataOra"]}}{{i["Valore"]}}
39 |

Grafico valori del sensore

40 |
41 | 42 | 46 | 47 | -------------------------------------------------------------------------------- /09_Raspberry/Raspberry -Installazione senza monitor e senza tastiera - Lite 3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/09_Raspberry/Raspberry -Installazione senza monitor e senza tastiera - Lite 3.pdf -------------------------------------------------------------------------------- /09_Raspberry/imp.txt: -------------------------------------------------------------------------------- 1 | indirizzo ip: 172.17.2.44 2 | nome: 4IB-6 3 | nome utente: pi 4 | pass: admin 5 | indirizzo ip statico: 172.17.200.6 6 | 7 | ssh pi@172.17.200.6 8 | 9 | comandi: 10 | python3 -m flask --app FLASKAPP run --host 0.0.0.0 11 | python3 prog.py 12 | cd C:\00_Scuola\Tps\tps_2022_2023 13 | scp -r CARTELLA pi@172.17.200.6:/home/pi/tps 14 | -------------------------------------------------------------------------------- /10_Pacchetto-RF24-Arduino/10_Pacchetto_RF24_Arduino_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/10_Pacchetto-RF24-Arduino/10_Pacchetto_RF24_Arduino_Relazione.pdf -------------------------------------------------------------------------------- /10_Pacchetto-RF24-Arduino/Pacchetto Livello 3 e 7 - RF24 - Arduino.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/10_Pacchetto-RF24-Arduino/Pacchetto Livello 3 e 7 - RF24 - Arduino.pdf -------------------------------------------------------------------------------- /10_Pacchetto-RF24-Arduino/parte0/sketch_prova/sketch_prova.ino: -------------------------------------------------------------------------------- 1 | #include 2 | RF24 radio(7, 8); // Imposta CE e nCSN conformemente all'hardware 3 | 4 | void setup() { 5 | Serial.begin(9600); 6 | radio.begin(); 7 | } 8 | 9 | void loop() { 10 | if (radio.isChipConnected()) 11 | Serial.println ("nRF24L01p presente"); 12 | else 13 | Serial.println ("nRF24L01p non rilevato"); 14 | delay(1000); 15 | } 16 | -------------------------------------------------------------------------------- /10_Pacchetto-RF24-Arduino/parte1/sketch_sensore/sketch_sensore.ino: -------------------------------------------------------------------------------- 1 | #include 2 | RF24 radio(7, 8); 3 | 4 | #define ID "BE" 5 | #define TIPO "S1" 6 | #define MITTENTE "M001" 7 | #define DESTINATARIO "P001" 8 | #define WRITINGPIPE "00001" 9 | #define VUOTO "----------------" 10 | 11 | struct pacchettoS1 { 12 | char id[2]; 13 | char mittente[4]; 14 | char destinatario[4]; 15 | char tipo[2]; 16 | char valoreSensore[4]; 17 | char vuoto[16]; 18 | }; 19 | 20 | void setup() { 21 | Serial.begin(9600); 22 | 23 | radio.begin(); 24 | radio.setPALevel(RF24_PA_MIN); 25 | radio.setPayloadSize(32); 26 | radio.setDataRate(RF24_2MBPS); 27 | radio.openWritingPipe((byte *)WRITINGPIPE); 28 | radio.stopListening(); 29 | if (radio.isChipConnected()) 30 | Serial.println ("nRF24L01p presente"); 31 | else 32 | Serial.println ("nRF24L01p non rilevato"); 33 | } 34 | 35 | void loop() { 36 | int num = analogRead(A0); 37 | char s[5]; 38 | sprintf(s, "%04d", num); 39 | 40 | struct pacchettoS1 msg; 41 | memcpy(msg.id, ID, sizeof(msg.id)); 42 | memcpy(msg.mittente, MITTENTE, sizeof(msg.mittente)); 43 | memcpy(msg.destinatario, DESTINATARIO, sizeof(msg.destinatario)); 44 | memcpy(msg.tipo, TIPO, sizeof(msg.tipo)); 45 | memcpy(msg.valoreSensore, s, sizeof(msg.valoreSensore)); 46 | memcpy(msg.vuoto, VUOTO, sizeof(msg.vuoto)); 47 | 48 | Serial.write((char *)&msg, sizeof(msg)); 49 | Serial.println(); 50 | 51 | radio.write((char *)&msg, sizeof(msg)); 52 | 53 | 54 | delay(5000); 55 | 56 | } 57 | -------------------------------------------------------------------------------- /10_Pacchetto-RF24-Arduino/parte2/sketch_motore/sketch_motore.ino: -------------------------------------------------------------------------------- 1 | #include 2 | RF24 radio(7, 8); 3 | 4 | #define ID "BE" 5 | #define TIPO "A1" 6 | #define DESTINATARIO "A001" 7 | #define READINGPIPE "00001" 8 | 9 | struct pacchettoA1 { 10 | char id[2]; 11 | char mittente[4]; 12 | char destinatario[4]; 13 | char tipo[2]; 14 | char direzione[1]; 15 | char velocita[3]; 16 | char vuoto[16]; 17 | }; 18 | 19 | void setup() { 20 | Serial.begin(9600); 21 | pinMode(9, OUTPUT); 22 | pinMode(5, OUTPUT); 23 | 24 | radio.begin(); 25 | radio.setPALevel(RF24_PA_MIN); 26 | radio.setPayloadSize(32); 27 | radio.setDataRate(RF24_2MBPS); 28 | radio.openReadingPipe(0, (byte *) READINGPIPE); 29 | radio.startListening(); 30 | if (radio.isChipConnected()) 31 | Serial.println ("nRF24L01p presente"); 32 | else 33 | Serial.println ("nRF24L01p non rilevato"); 34 | } 35 | 36 | void loop() { 37 | struct pacchettoA1 msg; 38 | if (radio.available()) 39 | { 40 | radio.read((char*) &msg, sizeof(msg)); 41 | int controlloId = memcmp(ID, msg.id, 2); 42 | int controlloDest = memcmp(DESTINATARIO, msg.destinatario, 4); 43 | char vel[4]; 44 | if (controlloId == 0 && controlloDest == 0) 45 | { 46 | Serial.println((char *)&msg); 47 | memcpy(vel,msg.velocita,sizeof(msg.velocita)); 48 | vel[3] = '\0'; 49 | int velocita = atoi(vel); 50 | if (memcmp("A",msg.direzione, 1) == 0) 51 | { 52 | digitalWrite(5, LOW); 53 | digitalWrite(9, HIGH); 54 | analogWrite(3, velocita); 55 | } 56 | if (memcmp("I",msg.direzione, 1) == 0) 57 | { 58 | digitalWrite(5, HIGH); 59 | digitalWrite(9, LOW); 60 | analogWrite(3, velocita); 61 | } 62 | if (memcmp("S",msg.direzione, 1) == 0) 63 | { 64 | digitalWrite(5, LOW); 65 | digitalWrite(9, LOW); 66 | analogWrite(3, 0); 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /11_Pacchetto-RF24-Raspberry/11_Pacchetto-RF24-Raspberry_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/11_Pacchetto-RF24-Raspberry/11_Pacchetto-RF24-Raspberry_Relazione.pdf -------------------------------------------------------------------------------- /11_Pacchetto-RF24-Raspberry/Pacchetto Livello 3 e 7 - RF24 - Raspberry.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/11_Pacchetto-RF24-Raspberry/Pacchetto Livello 3 e 7 - RF24 - Raspberry.pdf -------------------------------------------------------------------------------- /11_Pacchetto-RF24-Raspberry/parte2/rf24SensoreJSON.py: -------------------------------------------------------------------------------- 1 | import time 2 | import sys 3 | import struct 4 | import json 5 | import pigpio 6 | from nrf24 import * 7 | import os 8 | 9 | PIGPIONAME='localhost' 10 | PIGPIOPORT=8888 11 | READINGPIPE='00001' 12 | IDCORRETTO='BE' 13 | DESTINATARIOCORRETTO='P001' 14 | MIO_TIPO='S1' 15 | lista = [] 16 | pathJ = os.getcwd()+'/datiSensore.json' 17 | 18 | # connessione a pigpiod 19 | pi = pigpio.pi(PIGPIONAME, PIGPIOPORT) 20 | if not pi.connected: 21 | print("Pigpiod non connesso. Lanciare: SUDO PIGPIOD") 22 | sys.exit() 23 | 24 | # Crea l'oggetto NRF24 25 | nrf = NRF24(pi, ce=17, payload_size=32, channel=76,data_rate=RF24_DATA_RATE.RATE_2MBPS, pa_level=RF24_PA.LOW) 26 | 27 | # apre la pipe 28 | nrf.set_address_bytes(5) 29 | nrf.open_reading_pipe(RF24_RX_ADDR.P1, READINGPIPE) 30 | 31 | #lettura pacchetto 32 byte 32 | while True: 33 | if nrf.data_ready(): 34 | pack=(struct.unpack("2s 4s 4s 2s 4s 16s",nrf.get_payload())) 35 | id=pack[0].decode() 36 | mittente=pack[1].decode() 37 | destinatario=pack[2].decode() 38 | tipo=pack[3].decode() 39 | valoreSensore=pack[4].decode() 40 | vuoto=pack[5].decode() 41 | if ((id==IDCORRETTO)and(destinatario==DESTINATARIOCORRETTO)): 42 | print(pack) 43 | print("id e destinatario corretti e valoreSensore = " + valoreSensore) 44 | s=int(valoreSensore) 45 | dataOra = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) 46 | dizionario = {'DataOra': dataOra, 'Valore' : s} 47 | lista.append(dizionario) 48 | data = json.dumps(lista[-10:]) 49 | with open(pathJ, 'w') as fp: 50 | fp.write(data) 51 | with open(pathJ, 'r') as fp: 52 | lista2 = json.load(fp) 53 | print(lista2) -------------------------------------------------------------------------------- /11_Pacchetto-RF24-Raspberry/parte2/rf24SensoreTemplate.py: -------------------------------------------------------------------------------- 1 | from flask import render_template 2 | from flask import Flask 3 | import os 4 | import json 5 | 6 | pathJ = os.getcwd()+'/datiSensore.json' 7 | app = Flask(__name__) 8 | @app.route('/') 9 | 10 | def returnHtml(): 11 | with open(pathJ, 'r') as fp: 12 | lista = json.load(fp) 13 | return render_template('index.html', dizValori=lista) 14 | if __name__=="__main__": 15 | app.run(debug=True) -------------------------------------------------------------------------------- /11_Pacchetto-RF24-Raspberry/parte2/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Dati sensore 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | {% for i in dizValori %} 17 | 18 | 19 | 20 | 21 | {% endfor %} 22 | 23 |
Data e oraValore
{{i["DataOra"]}}{{i["Valore"]}}
24 | 25 | -------------------------------------------------------------------------------- /11_Pacchetto-RF24-Raspberry/parte3/rf24Attuatore.py: -------------------------------------------------------------------------------- 1 | import time 2 | import sys 3 | import pigpio 4 | from nrf24 import * 5 | import struct 6 | from flask import Flask, request, render_template, redirect 7 | 8 | PIGPIONAME='localhost' 9 | PIGPIOPORT=8888 10 | WRITINGPIPE='00001' 11 | ID=b"BE" 12 | MITTENTE=b"P001" 13 | DESTINATARIO=b"A001" 14 | TIPO=b"A1" 15 | VUOTO=("-"*16).encode() 16 | app = Flask(__name__) 17 | 18 | # connessione a pigpiod 19 | pi = pigpio.pi(PIGPIONAME, PIGPIOPORT) 20 | if not pi.connected: 21 | print("Pigpiod non connesso. Lanciare: SUDO PIGPIOD") 22 | sys.exit() 23 | 24 | # Crea l'oggetto NRF24 25 | nrf = NRF24(pi, ce=17, payload_size=32, channel=76,data_rate=RF24_DATA_RATE.RATE_2MBPS, pa_level=RF24_PA.LOW) 26 | 27 | # apre le pipe 28 | nrf.set_address_bytes(5) 29 | nrf.open_writing_pipe(WRITINGPIPE) 30 | 31 | #scrittura pacchetto 32 byte 32 | @app.route("/") 33 | def inviaFormVuoto(): 34 | return(render_template("index.html")) 35 | 36 | @app.route("/ricevi") 37 | def riceviForm(): 38 | val = request.args["velocita"] 39 | if(request.args["btn"] == "avanti"): 40 | direzione = b"A" 41 | else: 42 | direzione = b"I" 43 | v = str(val).zfill(3).encode() 44 | msg=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO,TIPO,direzione,v,VUOTO) 45 | nrf.send(msg) 46 | print(msg) 47 | return redirect('/') -------------------------------------------------------------------------------- /11_Pacchetto-RF24-Raspberry/parte3/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Controllo motore 8 | 9 | 10 |

Controllo motore

11 |
12 | 13 | 14 |
15 | 16 | 17 |
18 | 19 | 20 |
21 | 22 |
23 | 24 | -------------------------------------------------------------------------------- /11_Pacchetto-RF24-Raspberry/parte4/rf24SensAtt.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, render_template, redirect 2 | import struct 3 | import os 4 | import json 5 | import time 6 | import sys 7 | import pigpio 8 | from nrf24 import * 9 | 10 | #costanti rf24 11 | PIGPIONAME='localhost' 12 | PIGPIOPORT=8888 13 | WRITINGPIPE='00001' 14 | 15 | #costanti motore 16 | ID=b"BE" 17 | MITTENTE=b"P001" 18 | DESTINATARIO=b"A001" 19 | TIPO=b"A1" 20 | VUOTO=("-"*16).encode() 21 | 22 | lista = [] 23 | pathJ = os.getcwd()+'/datiSensore.json' 24 | direzione = b"A" 25 | app = Flask(__name__) 26 | 27 | # connessione a pigpiod 28 | pi = pigpio.pi(PIGPIONAME, PIGPIOPORT) 29 | if not pi.connected: 30 | print("Pigpiod non connesso. Lanciare: SUDO PIGPIOD") 31 | sys.exit() 32 | 33 | # Crea l'oggetto NRF24 34 | nrf = NRF24(pi, ce=17, payload_size=32, channel=76,data_rate=RF24_DATA_RATE.RATE_2MBPS, pa_level=RF24_PA.LOW) 35 | 36 | # apre le pipe 37 | nrf.set_address_bytes(5) 38 | nrf.open_writing_pipe(WRITINGPIPE) 39 | 40 | #programma sensore 41 | @app.route('/') 42 | def returnHtml(): 43 | with open(pathJ, 'r') as fp: 44 | lista = json.load(fp) 45 | return render_template('index.html', dizValori=lista) 46 | if __name__=="__main__": 47 | app.run(debug=True) 48 | 49 | #programma attuatore 50 | @app.route("/ricevi") 51 | def riceviForm(): 52 | val = request.args["velocita"] 53 | if(request.args["btn"] == "avanti"): 54 | direzione = b"A" 55 | else: 56 | direzione = b"I" 57 | v = str(val).zfill(3).encode() 58 | msg=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO,TIPO,direzione,v,VUOTO) 59 | nrf.send(msg) 60 | print(msg) 61 | nrf.wait_until_sent() #funzione per la sincronizzazione del modulo rf24 dopo l'invio 62 | nrf.power_up_rx() #funzione che rimette il modulo in ascolto 63 | return redirect("/") -------------------------------------------------------------------------------- /11_Pacchetto-RF24-Raspberry/parte4/rf24SensoreJSON.py: -------------------------------------------------------------------------------- 1 | import time 2 | import sys 3 | import struct 4 | import json 5 | import pigpio 6 | from nrf24 import * 7 | import os 8 | 9 | PIGPIONAME='localhost' 10 | PIGPIOPORT=8888 11 | READINGPIPE='00001' 12 | IDCORRETTO='BE' 13 | DESTINATARIOCORRETTO='P001' 14 | MIO_TIPO='S1' 15 | lista = [] 16 | pathJ = os.getcwd()+'/datiSensore.json' 17 | 18 | # connessione a pigpiod 19 | pi = pigpio.pi(PIGPIONAME, PIGPIOPORT) 20 | if not pi.connected: 21 | print("Pigpiod non connesso. Lanciare: SUDO PIGPIOD") 22 | sys.exit() 23 | 24 | # Crea l'oggetto NRF24 25 | nrf = NRF24(pi, ce=17, payload_size=32, channel=76,data_rate=RF24_DATA_RATE.RATE_2MBPS, pa_level=RF24_PA.LOW) 26 | 27 | # apre la pipe 28 | nrf.set_address_bytes(5) 29 | nrf.open_reading_pipe(RF24_RX_ADDR.P1, READINGPIPE) 30 | 31 | #lettura pacchetto 32 byte 32 | while True: 33 | if nrf.data_ready(): 34 | pack=(struct.unpack("2s 4s 4s 2s 4s 16s",nrf.get_payload())) 35 | id=pack[0].decode() 36 | mittente=pack[1].decode() 37 | destinatario=pack[2].decode() 38 | tipo=pack[3].decode() 39 | valoreSensore=pack[4].decode() 40 | vuoto=pack[5].decode() 41 | if ((id==IDCORRETTO)and(destinatario==DESTINATARIOCORRETTO)): 42 | print(pack) 43 | print("id e destinatario corretti e valoreSensore = " + valoreSensore) 44 | s=int(valoreSensore) 45 | dataOra = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) 46 | dizionario = {'DataOra': dataOra, 'Valore' : s} 47 | lista.append(dizionario) 48 | data = json.dumps(lista[-10:]) 49 | with open(pathJ, 'w') as fp: 50 | fp.write(data) 51 | with open(pathJ, 'r') as fp: 52 | lista2 = json.load(fp) 53 | print(lista2) -------------------------------------------------------------------------------- /11_Pacchetto-RF24-Raspberry/parte4/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Controllo motore e sensore 9 | 12 | 13 | 14 |

Controllo motore

15 |
16 | 17 | 18 | 19 |
20 | 21 | 22 |
23 | 24 | 25 |
26 |

Tabella valori del sensore

27 | 28 | 29 | 30 | 31 | {% for i in dizValori %} 32 | 33 | 34 | 35 | 36 | {% endfor %} 37 | 38 |
Data e oraValore
{{i["DataOra"]}}{{i["Valore"]}}
39 | 40 | -------------------------------------------------------------------------------- /12_Cloud-MQTT/12_Cloud_MQTT_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/12_Cloud-MQTT/12_Cloud_MQTT_Relazione.pdf -------------------------------------------------------------------------------- /12_Cloud-MQTT/Cloud - MQTT 1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/12_Cloud-MQTT/Cloud - MQTT 1.pdf -------------------------------------------------------------------------------- /12_Cloud-MQTT/imp.txt: -------------------------------------------------------------------------------- 1 | start mosquitto: 2 | cd .. (*2) 3 | cd Program Files/mosquitto 4 | mosquitto -v -c mosquitto.conf 5 | 6 | cd tps/12_Cloud-MQTT/parte7/ 7 | 8 | ssh pi@172.17.200.6 9 | cd C:\00_Scuola\Tps\tps_2022_2023 10 | scp -r pi@172.17.200.6:/home/pi/tps -------------------------------------------------------------------------------- /12_Cloud-MQTT/parte3/provaPublish.py: -------------------------------------------------------------------------------- 1 | import paho.mqtt.publish as publish 2 | import time 3 | TOPIC = "umbeGio2" 4 | BROKER = "172.17.4.29" 5 | 6 | i = 0 7 | while True: 8 | i += 1 9 | msg=str(i) 10 | print(msg) 11 | 12 | publish.single(TOPIC, msg, hostname=BROKER) 13 | 14 | time.sleep(5) -------------------------------------------------------------------------------- /12_Cloud-MQTT/parte3/provaRead.py: -------------------------------------------------------------------------------- 1 | import paho.mqtt.client as client 2 | TOPIC="umbeGio2" 3 | BROKER = "172.17.4.29" 4 | 5 | def on_connect(subscriber, userdata, flags, rc): 6 | print("Connesso con return code" + str(rc)) 7 | 8 | subscriber.subscribe(TOPIC) 9 | 10 | def on_message(subscriber, userdata, msg): 11 | print(msg.topic+" "+str(msg.payload)) 12 | 13 | subscriber = client.Client() 14 | subscriber.on_connect = on_connect 15 | subscriber.on_message = on_message 16 | 17 | subscriber.connect(BROKER, 1883, 60) 18 | 19 | subscriber.loop_forever() -------------------------------------------------------------------------------- /12_Cloud-MQTT/parte7/attuatore/subscribeAttuatore.py: -------------------------------------------------------------------------------- 1 | import paho.mqtt.client as client 2 | import struct 3 | import time 4 | import json 5 | import sys 6 | import pigpio 7 | from nrf24 import * 8 | 9 | #costanti rf24 10 | PIGPIONAME='localhost' 11 | PIGPIOPORT=8888 12 | WRITINGPIPE='00001' 13 | 14 | #costanti motore 15 | ID=b"BE" 16 | MITTENTE=b"P001" 17 | DESTINATARIO=b"A001" 18 | TIPO=b"A1" 19 | VUOTO=("-"*16).encode() 20 | direzione = b"A" 21 | 22 | #costanti mqtt 23 | TOPIC="tps/motoreAtt" 24 | BROKER = "172.17.4.29" 25 | 26 | # connessione a pigpiod 27 | pi = pigpio.pi(PIGPIONAME, PIGPIOPORT) 28 | if not pi.connected: 29 | print("Pigpiod non connesso. Lanciare: SUDO PIGPIOD") 30 | sys.exit() 31 | 32 | # Crea l'oggetto NRF24 33 | nrf = NRF24(pi, ce=17, payload_size=32, channel=76,data_rate=RF24_DATA_RATE.RATE_2MBPS, pa_level=RF24_PA.LOW) 34 | 35 | # apre le pipe 36 | nrf.set_address_bytes(5) 37 | nrf.open_writing_pipe(WRITINGPIPE) 38 | 39 | def on_connect(subscriber, userdata, flags, rc): 40 | print("Connesso con return code" + str(rc)) 41 | 42 | subscriber.subscribe(TOPIC) 43 | 44 | def on_message(subscriber, userdata, msg): 45 | #print(msg.topic+" "+str(msg.payload)) 46 | data = json.loads(msg.payload) 47 | print(data) 48 | dir = data["direzione"] 49 | direzione = str(dir).encode() 50 | val = data["velocita"] 51 | v = str(val).zfill(3).encode() 52 | msg=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO,TIPO,direzione,v,VUOTO) 53 | nrf.send(msg) 54 | print(msg) 55 | nrf.wait_until_sent() 56 | nrf.power_up_rx() 57 | 58 | subscriber = client.Client() 59 | subscriber.on_connect = on_connect 60 | subscriber.on_message = on_message 61 | 62 | subscriber.connect(BROKER, 1883, 60) 63 | 64 | subscriber.loop_forever() -------------------------------------------------------------------------------- /12_Cloud-MQTT/parte7/sensore/publishSensore.py: -------------------------------------------------------------------------------- 1 | import paho.mqtt.publish as publish 2 | import time 3 | import sys 4 | import struct 5 | import json 6 | import pigpio 7 | from nrf24 import * 8 | 9 | #costanti mqtt 10 | TOPIC = "tps/sensorePotenza" 11 | BROKER = "172.17.4.29" 12 | 13 | #costanti sensore 14 | PIGPIONAME='localhost' 15 | PIGPIOPORT=8888 16 | READINGPIPE='00001' 17 | IDCORRETTO='BE' 18 | DESTINATARIOCORRETTO='P001' 19 | MIO_TIPO='S1' 20 | 21 | # connessione a pigpiod 22 | pi = pigpio.pi(PIGPIONAME, PIGPIOPORT) 23 | if not pi.connected: 24 | print("Pigpiod non connesso. Lanciare: SUDO PIGPIOD") 25 | sys.exit() 26 | 27 | # Crea l'oggetto NRF24 28 | nrf = NRF24(pi, ce=17, payload_size=32, channel=76,data_rate=RF24_DATA_RATE.RATE_2MBPS, pa_level=RF24_PA.LOW) 29 | 30 | # apre la pipe 31 | nrf.set_address_bytes(5) 32 | nrf.open_reading_pipe(RF24_RX_ADDR.P1, READINGPIPE) 33 | 34 | #lettura pacchetto 32 byte 35 | while True: 36 | if nrf.data_ready(): 37 | pack=(struct.unpack("2s 4s 4s 2s 4s 16s",nrf.get_payload())) 38 | id=pack[0].decode() 39 | mittente=pack[1].decode() 40 | destinatario=pack[2].decode() 41 | tipo=pack[3].decode() 42 | valoreSensore=pack[4].decode() 43 | vuoto=pack[5].decode() 44 | if ((id==IDCORRETTO)and(destinatario==DESTINATARIOCORRETTO)): 45 | print(pack) 46 | print("id e destinatario corretti e valoreSensore = " + valoreSensore) 47 | s=int(valoreSensore) 48 | dataOra = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) 49 | dizionario = {'DataOra': dataOra, 'Valore' : s} 50 | data = json.dumps(dizionario) 51 | publish.single(TOPIC, data, hostname=BROKER) -------------------------------------------------------------------------------- /12_Cloud-MQTT/parte8/attuatore.py: -------------------------------------------------------------------------------- 1 | import paho.mqtt.client as client 2 | import struct 3 | import time 4 | import sys 5 | import pigpio 6 | from nrf24 import * 7 | 8 | #costanti rf24 9 | PIGPIONAME='localhost' 10 | PIGPIOPORT=8888 11 | WRITINGPIPE='00001' 12 | 13 | #costanti motore 14 | ID=b"BE" 15 | MITTENTE=b"P001" 16 | DESTINATARIO=b"A001" 17 | TIPO=b"A1" 18 | VUOTO=("-"*16).encode() 19 | direzione = b"A" 20 | 21 | #costanti mqtt 22 | TOPIC="tps/motoreAtt" 23 | BROKER = "172.17.4.29" 24 | 25 | # connessione a pigpiod 26 | pi = pigpio.pi(PIGPIONAME, PIGPIOPORT) 27 | if not pi.connected: 28 | print("Pigpiod non connesso. Lanciare: SUDO PIGPIOD") 29 | sys.exit() 30 | 31 | # Crea l'oggetto NRF24 32 | nrf = NRF24(pi, ce=17, payload_size=32, channel=76,data_rate=RF24_DATA_RATE.RATE_2MBPS, pa_level=RF24_PA.LOW) 33 | 34 | # apre le pipe 35 | nrf.set_address_bytes(5) 36 | nrf.open_writing_pipe(WRITINGPIPE) 37 | 38 | def on_connect(subscriber, userdata, flags, rc): 39 | print("Connesso con return code" + str(rc)) 40 | subscriber.subscribe(TOPIC) 41 | 42 | def on_message(subscriber, userdata, msg): 43 | print(msg.topic+" "+str(msg.payload)) 44 | val = float(msg.payload.decode()) 45 | val = int(val) 46 | if val < 0: 47 | direzione = b"I" 48 | vel = ~int(val)+1 49 | v = str(vel).zfill(3).encode() 50 | msg=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 51 | else: 52 | direzione = b"A" 53 | v = str(val).zfill(3).encode() 54 | msg=struct.pack("2s 4s 4s 2s 1s 3s 16s",ID,MITTENTE,DESTINATARIO, TIPO, direzione, v, VUOTO) 55 | nrf.send(msg) 56 | print(msg) 57 | nrf.wait_until_sent() 58 | nrf.power_up_rx() 59 | 60 | subscriber = client.Client() 61 | subscriber.on_connect = on_connect 62 | subscriber.on_message = on_message 63 | 64 | subscriber.connect(BROKER, 1883, 60) 65 | 66 | subscriber.loop_forever() -------------------------------------------------------------------------------- /12_Cloud-MQTT/parte8/sensore.py: -------------------------------------------------------------------------------- 1 | import paho.mqtt.publish as publish 2 | import time 3 | import sys 4 | import struct 5 | import json 6 | import pigpio 7 | from nrf24 import * 8 | 9 | #costanti mqtt 10 | TOPIC = "tps/sensorePotenza" 11 | BROKER = "172.17.4.29" 12 | 13 | #costanti sensore 14 | PIGPIONAME='localhost' 15 | PIGPIOPORT=8888 16 | READINGPIPE='00001' 17 | IDCORRETTO='BE' 18 | DESTINATARIOCORRETTO='P001' 19 | MIO_TIPO='S1' 20 | 21 | # connessione a pigpiod 22 | pi = pigpio.pi(PIGPIONAME, PIGPIOPORT) 23 | if not pi.connected: 24 | print("Pigpiod non connesso. Lanciare: SUDO PIGPIOD") 25 | sys.exit() 26 | 27 | # Crea l'oggetto NRF24 28 | nrf = NRF24(pi, ce=17, payload_size=32, channel=76,data_rate=RF24_DATA_RATE.RATE_2MBPS, pa_level=RF24_PA.LOW) 29 | 30 | # apre la pipe 31 | nrf.set_address_bytes(5) 32 | nrf.open_reading_pipe(RF24_RX_ADDR.P1, READINGPIPE) 33 | 34 | #lettura pacchetto 32 byte 35 | while True: 36 | if nrf.data_ready(): 37 | pack=(struct.unpack("2s 4s 4s 2s 4s 16s",nrf.get_payload())) 38 | id=pack[0].decode() 39 | mittente=pack[1].decode() 40 | destinatario=pack[2].decode() 41 | tipo=pack[3].decode() 42 | valoreSensore=pack[4].decode() 43 | vuoto=pack[5].decode() 44 | if ((id==IDCORRETTO)and(destinatario==DESTINATARIOCORRETTO)): 45 | print(pack) 46 | print("id e destinatario corretti e valoreSensore = " + valoreSensore) 47 | s=int(valoreSensore) 48 | dataOra = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) 49 | dizionario = {'DataOra': dataOra, 'Valore' : s} 50 | data = json.dumps(dizionario) 51 | publish.single(TOPIC, data, hostname=BROKER) -------------------------------------------------------------------------------- /13_Cloud-MQTT-ESP8266/13_Cloud_MQTT_ESP8266_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/13_Cloud-MQTT-ESP8266/13_Cloud_MQTT_ESP8266_Relazione.pdf -------------------------------------------------------------------------------- /13_Cloud-MQTT-ESP8266/Cloud - MQTT - ESP8266.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/13_Cloud-MQTT-ESP8266/Cloud - MQTT - ESP8266.pdf -------------------------------------------------------------------------------- /13_Cloud-MQTT-ESP8266/parte2/esp8266_motore/esp8266_motore.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define AVANTI_PIN 12 //D6 6 | #define INDIETRO_PIN 14 //D5 7 | #define VELOCITA_PIN 0 //D3 8 | 9 | // WiFi 10 | const char *WIFI_SSID = "Greppi-2G"; // inserire i dati della rete WiFi 11 | const char *WIFI_PASSWORD = "withProxy"; 12 | 13 | // MQTT Broker 14 | const char *MQTT_BROKER = "172.17.4.29"; // indirizzo IP del broker 15 | const char *MQTT_USERNAME = ""; // se necessario 16 | const char *MQTT_PASSWORD = ""; 17 | const int MQTT_PORT = 1883; 18 | 19 | // topic 20 | const char *RICEVI = "tps/riceviAttuatore"; 21 | 22 | // oggetti per wifi e mqtt 23 | WiFiClient espClient; 24 | PubSubClient client(espClient); 25 | 26 | // setup 27 | void setup() 28 | { 29 | pinMode(AVANTI_PIN, OUTPUT); 30 | pinMode(INDIETRO_PIN, OUTPUT); 31 | Serial.begin(111520); 32 | Serial.println("Inizio"); 33 | Serial.print("Connessione al WiFi.."); 34 | WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 35 | while (WiFi.status() != WL_CONNECTED) 36 | { 37 | delay(500); 38 | Serial.print("."); 39 | } 40 | 41 | Serial.println(""); 42 | Serial.println("Connesso"); 43 | 44 | // assegna un nome questo client 45 | String client_id = "esp8266-client-gioUmbe" + String(WiFi.macAddress()); 46 | Serial.printf("%s in connessione al MQTT ..", client_id.c_str()); 47 | client.setServer(MQTT_BROKER, MQTT_PORT); 48 | client.setCallback(callback); 49 | while (!client.connected()) 50 | { 51 | if (client.connect(client_id.c_str(), MQTT_USERNAME, MQTT_PASSWORD)) 52 | { 53 | Serial.println("Connesso al broker mqtt"); 54 | } 55 | else 56 | { 57 | Serial.print("Fallito con codice di errore: "); 58 | Serial.println(client.state()); 59 | Serial.println("Ritento"); 60 | delay(2000); 61 | } 62 | } 63 | //sottoscrizione 64 | client.subscribe(RICEVI); 65 | } 66 | 67 | void loop() 68 | { 69 | client.loop(); 70 | } 71 | 72 | // funzione di callback 73 | void callback(char *topic, byte *payload, unsigned int length) 74 | { 75 | StaticJsonDocument<200> jsonDoc; 76 | Serial.print("Arrivato un messaggio nel topic: "); 77 | Serial.println(topic); 78 | Serial.println("Messaggio:"); 79 | for (int i = 0; i < length; i++) 80 | { 81 | Serial.print((char) payload[i]); 82 | } 83 | Serial.println(); 84 | Serial.println("-----------------------"); 85 | 86 | deserializeJson(jsonDoc, payload, length); 87 | const char* direzione = jsonDoc["direzione"]; 88 | int velocita = jsonDoc["velocita"]; 89 | Serial.println(velocita); 90 | Serial.println(direzione); 91 | if (strcmp("A", direzione) == 0) 92 | { 93 | digitalWrite(INDIETRO_PIN, LOW); 94 | digitalWrite(AVANTI_PIN, HIGH); 95 | analogWrite(VELOCITA_PIN, velocita); 96 | } 97 | if (strcmp("I", direzione) == 0) 98 | { 99 | digitalWrite(INDIETRO_PIN, HIGH); 100 | digitalWrite(AVANTI_PIN, LOW); 101 | analogWrite(VELOCITA_PIN, velocita); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /13_Cloud-MQTT-ESP8266/parte2/esp8266_sensore/esp8266_sensore.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // WiFi 6 | const char *WIFI_SSID = "Greppi-2G"; // inserire i dati della rete WiFi 7 | const char *WIFI_PASSWORD = "withProxy"; 8 | 9 | // MQTT Broker 10 | const char *MQTT_BROKER = "172.17.4.29"; // indirizzo IP del broker 11 | const char *MQTT_USERNAME = ""; // se necessario 12 | const char *MQTT_PASSWORD = ""; 13 | const int MQTT_PORT = 1883; 14 | 15 | // topic 16 | const char *INVIA = "tps/inviaSensore"; 17 | 18 | // oggetti per wifi e mqtt 19 | WiFiClient espClient; 20 | PubSubClient client(espClient); 21 | 22 | // setup 23 | void setup() 24 | { 25 | Serial.begin(111520); 26 | Serial.println("Inizio"); 27 | Serial.print("Connessione al WiFi.."); 28 | WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 29 | while (WiFi.status() != WL_CONNECTED) 30 | { 31 | delay(500); 32 | Serial.print("."); 33 | } 34 | 35 | Serial.println(""); 36 | Serial.println("Connesso"); 37 | 38 | // assegna un nome questo client 39 | String client_id = "esp8266-client-gioUmbe" + String(WiFi.macAddress()); 40 | Serial.printf("%s in connessione al MQTT ..", client_id.c_str()); 41 | client.setServer(MQTT_BROKER, MQTT_PORT); 42 | while (!client.connected()) 43 | { 44 | if (client.connect(client_id.c_str(), MQTT_USERNAME, MQTT_PASSWORD)) 45 | { 46 | Serial.println("Connesso al broker mqtt"); 47 | } 48 | else 49 | { 50 | Serial.print("Fallito con codice di errore: "); 51 | Serial.println(client.state()); 52 | Serial.println("Ritento"); 53 | delay(2000); 54 | } 55 | } 56 | 57 | // pubblicazione di un primo messaggio 58 | client.publish(INVIA, "Attivo"); 59 | } 60 | 61 | // ciclo di invio messaggi 62 | void loop() 63 | { 64 | StaticJsonDocument<200> doc; 65 | int num = analogRead(A0); 66 | char s[5]; 67 | sprintf(s, "%04d", num); 68 | JsonObject jsonObj = doc.to(); 69 | jsonObj["valoreSensore"] = s; 70 | char buffer[200]; 71 | serializeJson(jsonObj, buffer); 72 | Serial.write(buffer); 73 | Serial.println(); 74 | client.publish(INVIA, buffer); 75 | delay(10000); 76 | client.loop(); 77 | } 78 | -------------------------------------------------------------------------------- /14_Cloud-Alexa/Cloud - Alexa.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/14_Cloud-Alexa/Cloud - Alexa.pdf -------------------------------------------------------------------------------- /14_Cloud-Alexa/imp.txt: -------------------------------------------------------------------------------- 1 | ssh pi@172.17.200.6 2 | ssh -N -4 -v -R 8105:172.17.4.29:5000 greppi@tunnel.vincenzov.net 3 | tunnel.vincenzov.net:8105 4 | 5 | { 6 | "direzione" : "A", 7 | "velocita" : 250 8 | } 9 | 10 | cd .. (*2) 11 | cd Program Files/mosquitto 12 | mosquitto -v -c mosquitto.conf -------------------------------------------------------------------------------- /14_Cloud-Alexa/parte6/interactionModels/custom/it-IT.json: -------------------------------------------------------------------------------- 1 | { 2 | "interactionModel": { 3 | "languageModel": { 4 | "invocationName": "prova uno", 5 | "intents": [ 6 | { 7 | "name": "AMAZON.CancelIntent", 8 | "samples": [] 9 | }, 10 | { 11 | "name": "AMAZON.HelpIntent", 12 | "samples": [] 13 | }, 14 | { 15 | "name": "AMAZON.StopIntent", 16 | "samples": [] 17 | }, 18 | { 19 | "name": "HelloWorldIntent", 20 | "slots": [], 21 | "samples": [ 22 | "ciao", 23 | "come stai", 24 | "dì ciao", 25 | "salutami", 26 | "salutarmi" 27 | ] 28 | }, 29 | { 30 | "name": "AMAZON.NavigateHomeIntent", 31 | "samples": [] 32 | }, 33 | { 34 | "name": "ProvaIntent", 35 | "slots": [], 36 | "samples": [ 37 | "prova intent", 38 | "dimmi", 39 | "parla" 40 | ] 41 | }, 42 | { 43 | "name": "Motore", 44 | "slots": [], 45 | "samples": [ 46 | "motore" 47 | ] 48 | }, 49 | { 50 | "name": "Sensore", 51 | "slots": [], 52 | "samples": [ 53 | "sensore" 54 | ] 55 | }, 56 | { 57 | "name": "Direzione", 58 | "slots": [], 59 | "samples": [ 60 | "I", 61 | "A", 62 | "indietro", 63 | "avanti" 64 | ] 65 | } 66 | ], 67 | "types": [] 68 | } 69 | }, 70 | "version": "26" 71 | } -------------------------------------------------------------------------------- /14_Cloud-Alexa/parte6/lambda/lambda_function.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK for Python. 4 | # Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management, 5 | # session persistence, api calls, and more. 6 | # This sample is built using the handler classes approach in skill builder. 7 | import logging 8 | import ask_sdk_core.utils as ask_utils 9 | import paho.mqtt.publish as publish 10 | 11 | from ask_sdk_core.skill_builder import SkillBuilder 12 | from ask_sdk_core.dispatch_components import AbstractRequestHandler 13 | from ask_sdk_core.dispatch_components import AbstractExceptionHandler 14 | from ask_sdk_core.handler_input import HandlerInput 15 | 16 | from ask_sdk_model import Response 17 | 18 | logger = logging.getLogger(__name__) 19 | logger.setLevel(logging.INFO) 20 | 21 | #costanti mqtt 22 | TOPIC = "tps/alexa" 23 | BROKER = "172.17.4.29" 24 | 25 | class LaunchRequestHandler(AbstractRequestHandler): 26 | """Handler for Skill Launch.""" 27 | def can_handle(self, handler_input): 28 | # type: (HandlerInput) -> bool 29 | 30 | return ask_utils.is_request_type("LaunchRequest")(handler_input) 31 | 32 | def handle(self, handler_input): 33 | # type: (HandlerInput) -> Response 34 | speak_output = "Ciao, dimmi cosa vuoi controllare, il motore o il sensore?" 35 | 36 | return ( 37 | handler_input.response_builder 38 | .speak(speak_output) 39 | .ask(speak_output) 40 | .response 41 | ) 42 | 43 | 44 | class HelloWorldIntentHandler(AbstractRequestHandler): 45 | """Handler for Hello World Intent.""" 46 | def can_handle(self, handler_input): 47 | # type: (HandlerInput) -> bool 48 | return ask_utils.is_intent_name("HelloWorldIntent")(handler_input) 49 | 50 | def handle(self, handler_input): 51 | # type: (HandlerInput) -> Response 52 | speak_output = "Hello World!" 53 | 54 | return ( 55 | handler_input.response_builder 56 | .speak(speak_output) 57 | # .ask("add a reprompt if you want to keep the session open for the user to respond") 58 | .response 59 | ) 60 | 61 | 62 | class HelpIntentHandler(AbstractRequestHandler): 63 | """Handler for Help Intent.""" 64 | def can_handle(self, handler_input): 65 | # type: (HandlerInput) -> bool 66 | return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input) 67 | 68 | def handle(self, handler_input): 69 | # type: (HandlerInput) -> Response 70 | speak_output = "You can say hello to me! How can I help?" 71 | 72 | return ( 73 | handler_input.response_builder 74 | .speak(speak_output) 75 | .ask(speak_output) 76 | .response 77 | ) 78 | 79 | 80 | class CancelOrStopIntentHandler(AbstractRequestHandler): 81 | """Single handler for Cancel and Stop Intent.""" 82 | def can_handle(self, handler_input): 83 | # type: (HandlerInput) -> bool 84 | return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or 85 | ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input)) 86 | 87 | def handle(self, handler_input): 88 | # type: (HandlerInput) -> Response 89 | speak_output = "Goodbye!" 90 | 91 | return ( 92 | handler_input.response_builder 93 | .speak(speak_output) 94 | .response 95 | ) 96 | 97 | 98 | class SessionEndedRequestHandler(AbstractRequestHandler): 99 | """Handler for Session End.""" 100 | def can_handle(self, handler_input): 101 | # type: (HandlerInput) -> bool 102 | return ask_utils.is_request_type("SessionEndedRequest")(handler_input) 103 | 104 | def handle(self, handler_input): 105 | # type: (HandlerInput) -> Response 106 | 107 | # Any cleanup logic goes here. 108 | 109 | return handler_input.response_builder.response 110 | 111 | 112 | class IntentReflectorHandler(AbstractRequestHandler): 113 | """The intent reflector is used for interaction model testing and debugging. 114 | It will simply repeat the intent the user said. You can create custom handlers 115 | for your intents by defining them above, then also adding them to the request 116 | handler chain below. 117 | """ 118 | def can_handle(self, handler_input): 119 | # type: (HandlerInput) -> bool 120 | return ask_utils.is_request_type("IntentRequest")(handler_input) 121 | 122 | def handle(self, handler_input): 123 | # type: (HandlerInput) -> Response 124 | intent_name = ask_utils.get_intent_name(handler_input) 125 | speak_output = "You just triggered " + intent_name + "." 126 | 127 | return ( 128 | handler_input.response_builder 129 | .speak(speak_output) 130 | # .ask("add a reprompt if you want to keep the session open for the user to respond") 131 | .response 132 | ) 133 | 134 | 135 | class CatchAllExceptionHandler(AbstractExceptionHandler): 136 | """Generic error handling to capture any syntax or routing errors. If you receive an error 137 | stating the request handler chain is not found, you have not implemented a handler for 138 | the intent being invoked or included it in the skill builder below. 139 | """ 140 | def can_handle(self, handler_input, exception): 141 | # type: (HandlerInput, Exception) -> bool 142 | return True 143 | 144 | def handle(self, handler_input, exception): 145 | # type: (HandlerInput, Exception) -> Response 146 | logger.error(exception, exc_info=True) 147 | 148 | speak_output = "Sorry, I had trouble doing what you asked. Please try again." 149 | 150 | return ( 151 | handler_input.response_builder 152 | .speak(speak_output) 153 | .ask(speak_output) 154 | .response 155 | ) 156 | 157 | class ProvaIntentHandler(AbstractRequestHandler): 158 | def can_handle(self, handler_input): 159 | return ask_utils.is_intent_name("ProvaIntent")(handler_input) 160 | 161 | def handle(self, handler_input): 162 | speak_output = "Prova intent sembra funzionare" 163 | 164 | return ( 165 | handler_input.response_builder 166 | .speak(speak_output) 167 | .ask(speak_output) 168 | .response 169 | ) 170 | 171 | class MotoreHandler(AbstractRequestHandler): 172 | def can_handle(self, handler_input): 173 | return ask_utils.is_intent_name("Motore")(handler_input) 174 | 175 | def handle(self, handler_input): 176 | speak_output = "Dimmi la direzione: " 177 | 178 | return ( 179 | handler_input.response_builder 180 | .speak(speak_output) 181 | .ask(speak_output) 182 | .response 183 | ) 184 | 185 | class SensoreHandler(AbstractRequestHandler): 186 | def can_handle(self, handler_input): 187 | return ask_utils.is_intent_name("Sensore")(handler_input) 188 | 189 | def handle(self, handler_input): 190 | speak_output = "Valori sensore: " 191 | 192 | return ( 193 | handler_input.response_builder 194 | .speak(speak_output) 195 | .ask(speak_output) 196 | .response 197 | ) 198 | 199 | class DirezioneHandler(AbstractRequestHandler): 200 | def can_handle(self, handler_input): 201 | return ask_utils.is_intent_name("Direzione")(handler_input) 202 | 203 | def handle(self, handler_input): 204 | #direzione = handler_input 205 | #speak_output = "Dimmi la velocità" 206 | #velocita = handler_input 207 | #dizionario = {'direzione': direzione, 'velocita' : velocita} 208 | #data = json.dumps(dizionario) 209 | #publish.single(TOPIC, data, hostname=BROKER) 210 | speak_output = "Inviato al motore" 211 | 212 | return ( 213 | handler_input.response_builder 214 | .speak(speak_output) 215 | .ask(speak_output) 216 | .response 217 | ) 218 | 219 | 220 | # The SkillBuilder object acts as the entry point for your skill, routing all request and response 221 | # payloads to the handlers above. Make sure any new handlers or interceptors you've 222 | # defined are included below. The order matters - they're processed top to bottom. 223 | 224 | sb = SkillBuilder() 225 | 226 | sb.add_request_handler(DirezioneHandler()) 227 | sb.add_request_handler(SensoreHandler()) 228 | sb.add_request_handler(MotoreHandler()) 229 | sb.add_request_handler(ProvaIntentHandler()) 230 | sb.add_request_handler(LaunchRequestHandler()) 231 | sb.add_request_handler(HelloWorldIntentHandler()) 232 | sb.add_request_handler(HelpIntentHandler()) 233 | sb.add_request_handler(CancelOrStopIntentHandler()) 234 | sb.add_request_handler(SessionEndedRequestHandler()) 235 | sb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers 236 | 237 | sb.add_exception_handler(CatchAllExceptionHandler()) 238 | 239 | lambda_handler = sb.lambda_handler() -------------------------------------------------------------------------------- /14_Cloud-Alexa/parte6/lambda/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.26.123 2 | ask-sdk-core==1.18.0 -------------------------------------------------------------------------------- /14_Cloud-Alexa/parte6/lambda/utils.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import boto3 4 | from botocore.exceptions import ClientError 5 | 6 | 7 | def create_presigned_url(object_name): 8 | """Generate a presigned URL to share an S3 object with a capped expiration of 60 seconds 9 | 10 | :param object_name: string 11 | :return: Presigned URL as string. If error, returns None. 12 | """ 13 | s3_client = boto3.client('s3', 14 | region_name=os.environ.get('S3_PERSISTENCE_REGION'), 15 | config=boto3.session.Config(signature_version='s3v4',s3={'addressing_style': 'path'})) 16 | try: 17 | bucket_name = os.environ.get('S3_PERSISTENCE_BUCKET') 18 | response = s3_client.generate_presigned_url('get_object', 19 | Params={'Bucket': bucket_name, 20 | 'Key': object_name}, 21 | ExpiresIn=60*1) 22 | except ClientError as e: 23 | logging.error(e) 24 | return None 25 | 26 | # The response contains the presigned URL 27 | return response -------------------------------------------------------------------------------- /14_Cloud-Alexa/parte6/skill.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest": { 3 | "apis": { 4 | "custom": { 5 | "endpoint": { 6 | "uri": "https://tunnel.vincenzov.net:8105/" 7 | }, 8 | "interfaces": [], 9 | "locales": {} 10 | } 11 | }, 12 | "manifestVersion": "1.0", 13 | "permissions": [ 14 | { 15 | "name": "alexa:devices:all:address:country_and_postal_code:read" 16 | } 17 | ], 18 | "publishingInformation": { 19 | "category": "KNOWLEDGE_AND_TRIVIA", 20 | "distributionCountries": [], 21 | "isAvailableWorldwide": true, 22 | "locales": { 23 | "it-IT": { 24 | "description": "Sample Full Description", 25 | "examplePhrases": [ 26 | "Alexa apri ciao mondo", 27 | "ciao", 28 | "aiuto" 29 | ], 30 | "keywords": [], 31 | "name": "Prova", 32 | "summary": "Sample Short Description" 33 | } 34 | }, 35 | "testingInstructions": "Sample Testing Instructions." 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /15_Cloud_BLE/15_Cloud_BLE_Relazione.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/15_Cloud_BLE/15_Cloud_BLE_Relazione.pdf -------------------------------------------------------------------------------- /15_Cloud_BLE/Cloud - BLE.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/15_Cloud_BLE/Cloud - BLE.pdf -------------------------------------------------------------------------------- /15_Cloud_BLE/indirizzi_ble_esp32.txt: -------------------------------------------------------------------------------- 1 | C8:C9:A3:CB:F5:66 2 | 58:BF:25:9D:E9:B6 -------------------------------------------------------------------------------- /15_Cloud_BLE/parte1/server_BLE/server_BLE.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // definizione degli UID del servizio e delle due caratteristiche 6 | #define SERVICE_UUID "00000000-1fb5-459e-8fcc-c5c9c331914b" 7 | #define CHARACTERISTIC_UUID1 "11111111-36e1-4688-b7f5-ea07361b26a8" 8 | #define CHARACTERISTIC_UUID2 "22222222-36e1-4688-b7f5-ea07361b26a8" 9 | #define CHARACTERISTIC_SENSOR "33333333-36e1-4688-b7f5-ea07361b26a8" 10 | #define ADCPIN A0 11 | 12 | BLEServer *pServer; 13 | BLEService *pService; 14 | BLECharacteristic *pCharacteristic1; 15 | BLECharacteristic *pCharacteristic2; 16 | BLECharacteristic *pCharacteristicSensor; 17 | 18 | 19 | void setup() 20 | { 21 | Serial.begin(115200); 22 | Serial.println("Starting BLE Server!"); 23 | 24 | // attivazione del device BLE e creazione delle caratteristiche 25 | // la prima in R/W la seconda solo R 26 | BLEDevice::init("Controllo ambiente gioUmbe"); 27 | pServer = BLEDevice::createServer(); 28 | pService = pServer->createService(SERVICE_UUID); 29 | pCharacteristic1 = pService->createCharacteristic( 30 | CHARACTERISTIC_UUID1, 31 | BLECharacteristic::PROPERTY_READ | 32 | BLECharacteristic::PROPERTY_WRITE); 33 | pCharacteristic2 = pService->createCharacteristic( 34 | CHARACTERISTIC_UUID2, 35 | BLECharacteristic::PROPERTY_READ); 36 | pCharacteristicSensor = pService->createCharacteristic( 37 | CHARACTERISTIC_SENSOR, 38 | BLECharacteristic::PROPERTY_READ); 39 | 40 | // impostazione dei valori iniziali delle caratteristiche 41 | pCharacteristic1->setValue("init"); 42 | pCharacteristic2->setValue("1"); 43 | pCharacteristicSensor->setValue("0"); 44 | 45 | // attivazione del servizio e del'advertising 46 | pService->start(); 47 | BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); 48 | pAdvertising->addServiceUUID(SERVICE_UUID); 49 | pAdvertising->setScanResponse(true); 50 | pAdvertising->setMinPreferred(0x12); 51 | BLEDevice::startAdvertising(); 52 | } 53 | int i = 0; 54 | void loop() 55 | { 56 | int num = analogRead(ADCPIN); 57 | char s[5]; 58 | sprintf(s, "%04d", num); 59 | pCharacteristicSensor -> setValue(s); 60 | 61 | // acquisizione del valore della prima caratteristica 62 | std::string value = pCharacteristic1->getValue(); 63 | 64 | // impostazione del valore della seconda caratteristica 65 | // (valore progressivo) 66 | char str[100]; 67 | sprintf(str, "%d", i++); 68 | pCharacteristic2->setValue(str); 69 | 70 | // stampa 71 | Serial.print("Caratteristica sensore: "); 72 | Serial.print(s); 73 | Serial.print(" - Caratteristica 1: "); 74 | Serial.print(value.c_str()); 75 | Serial.print(" - Caratteristica 2: "); 76 | Serial.println(i); 77 | 78 | // ripresa dell'advertising 79 | BLEDevice::startAdvertising(); 80 | 81 | delay(2000); 82 | } 83 | -------------------------------------------------------------------------------- /15_Cloud_BLE/parte4/client_ble.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from bleak import BleakClient 3 | import time 4 | 5 | #58:BF:25:9D:E9:B6 6 | ESP32_ADDRESS = "C8:C9:A3:CB:F5:66" 7 | CHARACTERISTIC_UUID2 = "22222222-36e1-4688-b7f5-ea07361b26a8" 8 | 9 | async def main(address,uuid): 10 | async with BleakClient(address) as client: 11 | while True: 12 | value = await client.read_gatt_char(uuid) 13 | print(value) 14 | time.sleep(5) 15 | 16 | asyncio.run(main(ESP32_ADDRESS,CHARACTERISTIC_UUID2)) -------------------------------------------------------------------------------- /15_Cloud_BLE/parte5/server_BLE_sensore_motore/server_BLE_sensore_motore.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // definizione degli UID del servizio e delle due caratteristiche 6 | #define SERVICE_UUID "177c5272-c6c8-4ecd-a2e4-6e6bb7651ce1" 7 | #define CHARACTERISTIC_UUID1 "776be67f-9fcb-40b7-87cb-458e23f15638" 8 | #define CHARACTERISTIC_SENSOR "a89adab3-fb71-488d-940f-dea867890df9" 9 | #define CHARACTERISTIC_MOTORDIRECTION "a395aaa4-12fd-484f-b2e7-b4941e0e001a" 10 | #define CHARACTERISTIC_MOTORSPEED "8f0a2fa8-cad4-435d-907b-38f44f4fe5d3" 11 | #define ADCPIN A0 //SP 12 | #define AVANTI_PIN 14 //GPIO14 13 | #define INDIETRO_PIN 27 //GPIO27 14 | #define VELOCITA_PIN 33 //GPIO33 15 | 16 | BLEServer *pServer; 17 | BLEService *pService; 18 | BLECharacteristic *pCharacteristic1; 19 | BLECharacteristic *pCharacteristicSensor; 20 | BLECharacteristic *pCharacteristicMotorDirection; 21 | BLECharacteristic *pCharacteristicMotorSpeed; 22 | 23 | 24 | void setup() 25 | { 26 | Serial.begin(115200); 27 | Serial.println("Starting BLE Server!"); 28 | pinMode(AVANTI_PIN, OUTPUT); 29 | pinMode(INDIETRO_PIN, OUTPUT); 30 | 31 | // attivazione del device BLE e creazione delle caratteristiche 32 | // la prima in R/W la seconda solo R 33 | BLEDevice::init("Controllo ambiente gioUmbe"); 34 | pServer = BLEDevice::createServer(); 35 | pService = pServer->createService(SERVICE_UUID); 36 | pCharacteristic1 = pService->createCharacteristic( 37 | CHARACTERISTIC_UUID1, 38 | BLECharacteristic::PROPERTY_READ | 39 | BLECharacteristic::PROPERTY_WRITE); 40 | pCharacteristicSensor = pService->createCharacteristic( 41 | CHARACTERISTIC_SENSOR, 42 | BLECharacteristic::PROPERTY_READ); 43 | pCharacteristicMotorDirection = pService->createCharacteristic( 44 | CHARACTERISTIC_MOTORDIRECTION, 45 | BLECharacteristic::PROPERTY_WRITE); 46 | pCharacteristicMotorSpeed = pService->createCharacteristic( 47 | CHARACTERISTIC_MOTORSPEED, 48 | BLECharacteristic::PROPERTY_WRITE); 49 | 50 | // impostazione dei valori iniziali delle caratteristiche 51 | pCharacteristic1->setValue("init"); 52 | pCharacteristicSensor->setValue("0"); 53 | pCharacteristicMotorDirection->setValue("A"); 54 | pCharacteristicMotorSpeed->setValue("0"); 55 | 56 | // attivazione del servizio e del'advertising 57 | pService->start(); 58 | BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); 59 | pAdvertising->addServiceUUID(SERVICE_UUID); 60 | pAdvertising->setScanResponse(true); 61 | pAdvertising->setMinPreferred(0x12); 62 | BLEDevice::startAdvertising(); 63 | } 64 | 65 | void loop() 66 | { 67 | // acquisizione del valore della prima caratteristica 68 | std::string value = pCharacteristic1->getValue(); 69 | 70 | //lettura valori sensore e salvataggio 71 | int num = analogRead(ADCPIN); 72 | char s[5]; 73 | sprintf(s, "%04d", num); 74 | pCharacteristicSensor -> setValue(s); 75 | 76 | //controllo del motore 77 | std::string velo = pCharacteristicMotorSpeed->getValue(); 78 | std::string dir = pCharacteristicMotorDirection->getValue(); 79 | const char* direzione = dir.c_str(); 80 | const char* vel = velo.c_str(); 81 | int velocita = atoi(vel); 82 | if (strcmp("A", direzione) == 0) 83 | { 84 | digitalWrite(INDIETRO_PIN, LOW); 85 | digitalWrite(AVANTI_PIN, HIGH); 86 | analogWrite(VELOCITA_PIN, velocita); 87 | } 88 | if (strcmp("I", direzione) == 0) 89 | { 90 | digitalWrite(INDIETRO_PIN, HIGH); 91 | digitalWrite(AVANTI_PIN, LOW); 92 | analogWrite(VELOCITA_PIN, velocita); 93 | } 94 | 95 | // stampa 96 | Serial.print("Caratteristica 1: "); 97 | Serial.print(value.c_str()); 98 | Serial.print(" - Caratteristica sensore: "); 99 | Serial.print(s); 100 | Serial.println(); 101 | Serial.print("Caratteristica motore direzione: "); 102 | Serial.print(direzione); 103 | Serial.print(" - Caratteristica motore velocità: "); 104 | Serial.print(velocita); 105 | Serial.println(); 106 | 107 | // ripresa dell'advertising 108 | BLEDevice::startAdvertising(); 109 | 110 | delay(2000); 111 | } 112 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.it.md: -------------------------------------------------------------------------------- 1 | # Controllo di Motori e Sensori su Arduino, Raspberry Pi e ESP 2 | 3 | ![GitHub contributors](https://img.shields.io/github/contributors/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP) 4 | ![GitHub all releases](https://img.shields.io/github/downloads/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/total) 5 | ![GitHub](https://img.shields.io/github/license/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP) 6 | ![GitHub deployments](https://img.shields.io/github/deployments/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/github-pages) 7 | ![GitHub repo size](https://img.shields.io/github/repo-size/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP) 8 | ![GitHub Repo stars](https://img.shields.io/github/stars/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP) 9 | 10 | ![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54) 11 | ![C++](https://img.shields.io/badge/c++-%2300599C.svg?style=for-the-badge&logo=c%2B%2B&logoColor=white) 12 | ![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white) 13 | ![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white) 14 | ![Arduino](https://img.shields.io/badge/-Arduino-00979D?style=for-the-badge&logo=Arduino&logoColor=white) 15 | ![Raspberry Pi](https://img.shields.io/badge/-RaspberryPi-C51A4A?style=for-the-badge&logo=Raspberry-Pi) 16 | ![Matplotlib](https://img.shields.io/badge/Matplotlib-%23ffffff.svg?style=for-the-badge&logo=Matplotlib&logoColor=black) 17 | ![Flask](https://img.shields.io/badge/flask-%23000.svg?style=for-the-badge&logo=flask&logoColor=white) 18 | ![Mosquitto](https://img.shields.io/badge/mosquitto-%233C5280.svg?style=for-the-badge&logo=eclipsemosquitto&logoColor=white) 19 | ![Zigbee](https://img.shields.io/badge/zigbee-%23EB0443.svg?style=for-the-badge&logo=zigbee&logoColor=white) 20 | ![Amazon Alexa](https://img.shields.io/badge/amazon%20alexa-52b5f7?style=for-the-badge&logo=amazon%20alexa&logoColor=white) 21 | 22 | README.us 🇺🇸 23 | 24 | --- 25 | ## tps_GiorgioCitterio_UmbertoColombo_2022_2023 26 | ### Indice 27 | - Attività 1: Trasmissione seriale su Arduino 28 | - Attività 2: Comunicazione seriale con Python e Arduino 29 | - Attività 3: Comunicazione con pacchetto modello ISO/OSI 30 | - Attività 4: Controllo sensore/attuatore tramite interfaccia grafica GUI (Python) 31 | - Attività 5: Memorizzazione dati sensore su un file JSON 32 | - Attività 7: Rendere disponibili sul Web i dati del sensore 33 | - Attività 8: Controllo del motore tramite browser 34 | - Attività 9: Installazione e importazione programmi su Raspberry 35 | - Attività 10: Inviare pacchetti tramite modulo radio RF24 36 | - Attività 11: Controllo motore e sensore da Raspberry 37 | - Attività 12: Utilizzare MQTT tra dispositivi IoT 38 | - Attività 13: Utilizzare MQTT con l'ESP8266 39 | - Attività 14: Come controllare sensore e attuatore tramite Alexa 40 | - Attività 15: Utilizzare BLE per il controllo dell'ambiente 41 | 42 | Installazione delle librerie su sistemi [Linux](lib.md). 43 | 44 | --- 45 | 46 | # Attività 1 47 | 48 | **Relazione attività 1**: [Trasmissione seriale su arduino](01_TrasmissioneSerialeArduino/01_TrasmissioneSerialeArduino_Relazione.pdf). 49 | 50 | Controllare come avviene comunicazione sulla seriale da parte di arduino. 51 | 52 | --- 53 | 54 | # Attività 2 55 | 56 | **Relazione attività 2**: [Comunicazione seriale con python e arduino](02_Python-2-Seriale/02_Python_2_Seriale_Relazione.pdf). 57 | 58 | Comunicare tramite un' applicazione python che gira su Windows un sensore (potenziometro) ed un attuatore (motore con 59 | L293D), entrambi realizzati su breadboard e gestiti da un programma su arduino. 60 | 61 | Per comunicare sulla porta seriale tramite python si utilizza la libreria *serial* che può essere installata (su Windows) con il seguente comando: 62 | ``` 63 | py -m pip install pyserial 64 | ``` 65 | 66 | Documentazione ufficiale libreria [serial](https://pyserial.readthedocs.io/en/latest/pyserial.html). 67 | 68 | --- 69 | 70 | # Attività 3 71 | 72 | **Relazione attività 3**: [Comunicazione con pacchetto modello ISO/OSI](03_Python-3-Pacchetto_livello_3_7_del%20modello_ISO-OSI_su_seriale/03_Python_3_Pacchetto_livello_3_7_modello_ISOOSI_su_seriale_Relazione.pdf). 73 | 74 | Come riorganizzare il formato dei messaggi scambiati fra i sensori/attuatori e l’applicazione python, preparando le cose in modo tale che possano funzionare utilizzando un RF24, che ha un payload di 32 byte. 75 | 76 | Per realizzare questi pacchetti si utilizza la libreria *struct* già presente in python. 77 | 78 | Documentazione ufficiale libreria [struct](https://docs.python.org/3/library/struct.html). 79 | 80 | --- 81 | 82 | # Attività 4 83 | 84 | **Relazione attività 4**: [Controllo sensore/attuatore tramite interfaccia grafica GUI (Python)](04_Python-4-GUI/04_Python_4_GUI_Relazione.pdf). 85 | 86 | Come gestire il sensore e l'attuatore tramite interfaccia grafica GUI su python, 3 programmi diversi per l'attuatore e 3 per il sensore. 87 | 88 | Per realizzare la GUI (Graphical User Interface) si utilizza la libreria *tkinter* installabile per la maggior parte degli utenti con il seguente comando: 89 | ``` 90 | py -m pip install tkinter 91 | ``` 92 | 93 | Documentazione ufficiale libreria [tkinter](https://docs.python.org/3/library/tk.html). 94 | 95 | Nell'ultima versione del programma per il sensore, per la realizzazione del grafico si utilizza la libreria *matplotlib* installabile (su Windows) con il comando seguente: 96 | ``` 97 | py -m pip install matplotlib 98 | ``` 99 | 100 | Documentazione ufficiale libreria [matplotlib](https://matplotlib.org/). 101 | 102 | --- 103 | 104 | # Attività 5 105 | 106 | **Relazione attività 5**: [Memorizzazione dati sensore su un file JSON](05_Python-5-JSON/05_Python_5_JSON_Relazione.pdf). 107 | 108 | Come memorizzare i dati ricevuti dal sensore su un file JSON in modo da poterli rendere disponibili successivamente per lo scambio di dati client/server. 109 | 110 | Per scrivere su un file JSON da python si utilizza la libreria *json* già presente in python: 111 | 112 | Documentazione ufficiale libreria [json](https://docs.python.org/3/library/json.html). 113 | 114 | --- 115 | 116 | # Attività 7 117 | 118 | **Relazione attività 7**: [Rendere disponibili sul Web i dati del sensore](07_Python-7-Flask/07_Python_7_Flask_Relazione.pdf). 119 | 120 | Come rendere disponibili sul Web i dati del sensore memorizzati nel file JSON grazie all'utilizzo di Flask e del tunneling. 121 | 122 | Per creare il Web server utilizzeremo la libreria *Flask* installabile (su Windows) con il comando seguente: 123 | ``` 124 | py -m pip install Flask 125 | ``` 126 | 127 | Documentazione ufficiale libreria [Flask](https://flask.palletsprojects.com/en/2.2.x/). 128 | 129 | --- 130 | 131 | # Attività 8 132 | 133 | **Relazione attività 8**: [Controllo del motore tramite browser](08_Python-8-Form/08_Python_8_Form_Relazione.pdf). 134 | 135 | Come inviare dati da Web all’applicazione Flask, in modo da poter controllare il motore. 136 | 137 | --- 138 | 139 | # Attività 9 140 | 141 | Installazione e importazione programmi su **Raspberry**. 142 | 143 | --- 144 | 145 | # Attività 10 146 | 147 | **Relazione attività 10**: [Inviare pacchetti tramite modulo radio RF24](10_Pacchetto-RF24-Arduino/10_Pacchetto_RF24_Arduino_Relazione.pdf). 148 | 149 | Come inviare i pacchetti realizzati nella fase “Pacchetto Livello 3 – seriale”, in modo che facciano uso del modulo radio **nRF24L01+**. 150 | 151 | Per utilizzare il modulo radio **nRF24L01+** serve importare la libreria *RF24* su arduino. 152 | 153 | Documentazione ufficiale libreria [RF24](https://nrf24.github.io/RF24/classRF24.html). 154 | [RF24 GitHub](https://github.com/bjarne-hansen/py-nrf24). 155 | 156 | --- 157 | 158 | # Attività 11 159 | 160 | **Relazione attività 11**: [Controllo motore e sensore da Raspberry](11_Pacchetto-RF24-Raspberry/11_Pacchetto-RF24-Raspberry_Relazione.pdf). 161 | 162 | Come visualizzare i dati sensore e controllare il motore tramite un server Flask che gira su **Raspberry**, che comunica con i due arduino con l'hardware tramite il modulo radio **nRF24L01+**. 163 | 164 | Per il controllo dei piedini **GPIO** su **Raspberry** abbiamo dovuto installare la libreria *pigpiod* con il comando seguente: 165 | ``` 166 | sudo apt-get install pigpiod 167 | ``` 168 | 169 | Per interfacciarsi con il modulo radio **RF24** da python bisogna importare la libreria *nrf24* con il comando seguente: 170 | ``` 171 | python3 –m pip install nrf24 172 | ``` 173 | 174 | --- 175 | 176 | # Attività 12 177 | 178 | **Relazione attività 12**: [Utilizzare MQTT tra dispositivi IoT](12_Cloud-MQTT/12_Cloud_MQTT_Relazione.pdf). 179 | 180 | Come utilizzare il protocollo MQTT per comunicare tra dispositivi IoT, anche tramite app. 181 | 182 | Per utilizzare mqtt da python bisogna importare la libreria *paho-mqtt* con il comando seguente: 183 | ``` 184 | python3 -m pip install paho-mqtt 185 | ``` 186 | 187 | --- 188 | 189 | # Attività 13 190 | 191 | **Relazione attività 13**: [Utilizzare MQTT con l'ESP8266](13_Cloud-MQTT-ESP8266/13_Cloud_MQTT_ESP8266_Relazione.pdf). 192 | 193 | Come utilizzare MQTT per lo scambio di messaggi fra dispositivi IoT connessi direttamente all'ESP8266 con funzionalità per la connessione WiFi. 194 | 195 | Bisognerà aggiungere il gestore schede nell'IDE di Arduino per poter gestire l'ESP8266. 196 | 197 | [Tutorial per l'installazione](https://www.vincenzov.net/tutorial/ESP/ESP8266/Arduino-IDE.htm). 198 | 199 | --- 200 | 201 | # Attività 14 202 | 203 | TODO: Come controllare sensore e attuatore tramite alexa. 204 | 205 | --- 206 | 207 | # Attività 15 208 | 209 | **Relazione attività 15**: [Utilizzare BLE per il controllo dell'ambiente](15_Cloud_BLE/15_Cloud_BLE_Relazione.pdf). 210 | 211 | Come utilizzare ESP32 per realizzare dispositivi che utilizzano il protocollo Bluetooth Low Energy (BLE) per la comunicazione. 212 | 213 | Per il controllo dell'ESP32 dall'IDE di Arduino bisognerà aggiungere il gestore schede come fatto precedentemente per l'ESP8266. 214 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Motor and Sensor Control on Arduino Raspberry Pi and ESP 2 | 3 | ![GitHub contributors](https://img.shields.io/github/contributors/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP) 4 | ![GitHub all releases](https://img.shields.io/github/downloads/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/total) 5 | ![GitHub](https://img.shields.io/github/license/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP) 6 | ![GitHub deployments](https://img.shields.io/github/deployments/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/github-pages) 7 | ![GitHub repo size](https://img.shields.io/github/repo-size/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP) 8 | ![GitHub Repo stars](https://img.shields.io/github/stars/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP) 9 | 10 | ![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54) 11 | ![C++](https://img.shields.io/badge/c++-%2300599C.svg?style=for-the-badge&logo=c%2B%2B&logoColor=white) 12 | ![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white) 13 | ![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white) 14 | ![Arduino](https://img.shields.io/badge/-Arduino-00979D?style=for-the-badge&logo=Arduino&logoColor=white) 15 | ![Raspberry Pi](https://img.shields.io/badge/-RaspberryPi-C51A4A?style=for-the-badge&logo=Raspberry-Pi) 16 | ![Matplotlib](https://img.shields.io/badge/Matplotlib-%23ffffff.svg?style=for-the-badge&logo=Matplotlib&logoColor=black) 17 | ![Flask](https://img.shields.io/badge/flask-%23000.svg?style=for-the-badge&logo=flask&logoColor=white) 18 | ![Mosquitto](https://img.shields.io/badge/mosquitto-%233C5280.svg?style=for-the-badge&logo=eclipsemosquitto&logoColor=white) 19 | ![Zigbee](https://img.shields.io/badge/zigbee-%23EB0443.svg?style=for-the-badge&logo=zigbee&logoColor=white) 20 | ![Amazon Alexa](https://img.shields.io/badge/amazon%20alexa-52b5f7?style=for-the-badge&logo=amazon%20alexa&logoColor=white) 21 | 22 | README.it 🇮🇹 23 | 24 | --- 25 | ## tps_GiorgioCitterio_UmbertoColombo_2022_2023 26 | ### Table of Contents 27 | - Activity 1: Serial Communication on Arduino 28 | - Activity 2: Serial Communication with Python and Arduino 29 | - Activity 3: Communication with ISO/OSI Model Packet 30 | - Activity 4: Sensor/Actuator Control via GUI (Python) 31 | - Activity 5: Storing Sensor Data in a JSON File 32 | - Activity 7: Making Sensor Data Available on the Web 33 | - Activity 8: Motor Control via Web Browser 34 | - Activity 9: Installation and Importing Programs on Raspberry Pi 35 | - Activity 10: Sending Packets via RF24 Radio Module 36 | - Activity 11: Controlling Motor and Sensor from Raspberry Pi 37 | - Activity 12: Using MQTT for IoT Device Communication 38 | - Activity 13: Using MQTT with ESP8266 39 | - Activity 14: Controlling Sensor and Actuator with Alexa 40 | - Activity 15: Using BLE for Environment Control 41 | 42 | For library installation on [Linux systems](lib.md). 43 | 44 | --- 45 | 46 | # Activity 1: 47 | 48 | **Activity Report 1**: [Serial Communication on Arduino](01_TrasmissioneSerialeArduino/01_TrasmissioneSerialeArduino_Relazione.pdf). 49 | 50 | Exploration of serial communication on Arduino. 51 | 52 | --- 53 | 54 | # Activity 2: 55 | 56 | **Activity Report 2**: [Serial Communication with Python and Arduino](02_Python-2-Seriale/02_Python_2_Seriale_Relazione.pdf). 57 | 58 | Communication between a Python application running on Windows and a sensor (potentiometer) and an actuator (L293D motor) connected to an Arduino. 59 | 60 | To communicate with the serial port using Python, the *serial* library is used, which can be installed on Windows with the following command: 61 | ``` 62 | py -m pip install pyserial 63 | ``` 64 | 65 | Official documentation for the [serial library](https://pyserial.readthedocs.io/en/latest/pyserial.html). 66 | 67 | --- 68 | 69 | # Activity 3: 70 | 71 | **Activity Report 3**: [Communication with ISO/OSI Model Packet](03_Python-3-Pacchetto_livello_3_7_del%20modello_ISO-OSI_su_seriale/03_Python_3_Pacchetto_livello_3_7_modello_ISOOSI_su_seriale_Relazione.pdf). 72 | 73 | Reorganizing the message format exchanged between sensors/actuators and the Python application to work with an RF24 module, which has a payload of 32 bytes. 74 | 75 | The *struct* library in Python is used to create these packets. 76 | 77 | Official documentation for the [struct library 78 | 79 | ](https://docs.python.org/3/library/struct.html). 80 | 81 | --- 82 | 83 | # Activity 4: 84 | 85 | **Activity Report 4**: [Sensor/Actuator Control via GUI (Python)](04_Python-4-GUI/04_Python_4_GUI_Relazione.pdf). 86 | 87 | Controlling a sensor and actuator through a GUI using Python. Three different programs for the actuator and three for the sensor. 88 | 89 | The GUI (Graphical User Interface) is created using the *tkinter* library, which can be installed for most users with the following command: 90 | ``` 91 | py -m pip install tkinter 92 | ``` 93 | 94 | Official documentation for the [tkinter library](https://docs.python.org/3/library/tk.html). 95 | 96 | In the latest version of the sensor program, the *matplotlib* library is used to create a graph. It can be installed (on Windows) with the following command: 97 | ``` 98 | py -m pip install matplotlib 99 | ``` 100 | 101 | Official documentation for the [matplotlib library](https://matplotlib.org/). 102 | 103 | --- 104 | 105 | # Activity 5: 106 | 107 | **Activity Report 5**: [Storing Sensor Data in a JSON File](05_Python-5-JSON/05_Python_5_JSON_Relazione.pdf). 108 | 109 | Storing sensor data received in a JSON file for later use in client/server data exchange. 110 | 111 | To write to a JSON file from Python, the *json* library, which is already available in Python, is used. 112 | 113 | Official documentation for the [json library](https://docs.python.org/3/library/json.html). 114 | 115 | --- 116 | 117 | # Activity 7: 118 | 119 | **Activity Report 7**: [Making Sensor Data Available on the Web](07_Python-7-Flask/07_Python_7_Flask_Relazione.pdf). 120 | 121 | Making sensor data stored in a JSON file available on the web using Flask and tunneling. 122 | 123 | To create the web server, the *Flask* library is used, which can be installed (on Windows) with the following command: 124 | ``` 125 | py -m pip install Flask 126 | ``` 127 | 128 | Official documentation for the [Flask library](https://flask.palletsprojects.com/en/2.2.x/). 129 | 130 | --- 131 | 132 | # Activity 8: 133 | 134 | **Activity Report 8**: [Motor Control via Web Browser](08_Python-8-Form/08_Python_8_Form_Relazione.pdf). 135 | 136 | Sending data from a web browser to a Flask application to control the motor. 137 | 138 | --- 139 | # Activity 9 140 | 141 | Installation and program importation on **Raspberry Pi**. 142 | 143 | --- 144 | 145 | # Activity 10 146 | 147 | **Activity Report 10**: [Sending Packets via RF24 Radio Module](10_Pacchetto-RF24-Arduino/10_Pacchetto_RF24_Arduino_Relazione.pdf). 148 | 149 | How to send packets created in the "Layer 3 Packet - Serial" phase using the **nRF24L01+** radio module. 150 | 151 | To use the **nRF24L01+** radio module, you need to import the *RF24* library on Arduino. 152 | 153 | Official documentation for the [RF24 library](https://nrf24.github.io/RF24/classRF24.html). 154 | [RF24 GitHub](https://github.com/bjarne-hansen/py-nrf24). 155 | 156 | --- 157 | 158 | # Activity 11 159 | 160 | **Activity Report 11**: [Motor and Sensor Control from Raspberry Pi](11_Pacchetto-RF24-Raspberry/11_Pacchetto-RF24-Raspberry_Relazione.pdf). 161 | 162 | How to display sensor data and control the motor through a Flask server running on **Raspberry Pi**, which communicates with the two Arduinos using the **nRF24L01+** radio module. 163 | 164 | To control the **GPIO** pins on **Raspberry Pi**, you need to install the *pigpiod* library using the following command: 165 | ``` 166 | sudo apt-get install pigpiod 167 | ``` 168 | 169 | To interface with the **RF24** radio module from Python, you need to import the *nrf24* library using the following command: 170 | ``` 171 | python3 -m pip install nrf24 172 | ``` 173 | 174 | --- 175 | 176 | # Activity 12 177 | 178 | **Activity Report 12**: [Using MQTT for IoT Device Communication](12_Cloud-MQTT/12_Cloud_MQTT_Relazione.pdf). 179 | 180 | How to use the MQTT protocol to communicate between IoT devices, including through apps. 181 | 182 | To use MQTT with Python, you need to import the *paho-mqtt* library using the following command: 183 | ``` 184 | python3 -m pip install paho-mqtt 185 | ``` 186 | 187 | --- 188 | 189 | # Activity 13 190 | 191 | **Activity Report 13**: [Using MQTT with ESP8266](13_Cloud-MQTT-ESP8266/13_Cloud_MQTT_ESP8266_Relazione.pdf). 192 | 193 | How to use MQTT for message exchange between IoT devices directly connected to ESP8266 with WiFi connectivity. 194 | 195 | You will need to add the board manager to the Arduino IDE to manage the ESP8266. 196 | 197 | [Tutorial for installation](https://www.vincenzov.net/tutorial/ESP/ESP8266/Arduino-IDE.htm). 198 | 199 | --- 200 | 201 | # Activity 14 202 | 203 | TODO: How to control the sensor and actuator using Alexa. 204 | 205 | --- 206 | 207 | # Activity 15 208 | 209 | **Activity Report 15**: [Using BLE for Environment Control](15_Cloud_BLE/15_Cloud_BLE_Relazione.pdf). 210 | 211 | How to use ESP32 to create devices that utilize the Bluetooth Low Energy (BLE) protocol for communication. 212 | 213 | To control the ESP32 from the Arduino IDE, you will need to add the board manager as previously done for the ESP8266. 214 | 215 | -------------------------------------------------------------------------------- /lib.md: -------------------------------------------------------------------------------- 1 | # General Guide to Installing Python Libraries on Major Linux Distributions Using *pip* 2 | 3 | For installing *pip* on **Arch**, use the following command: 4 | ``` 5 | sudo pacman -S python-pip 6 | ``` 7 | For installing *pip* on **Debian** and **Ubuntu**, use the following command: 8 | ``` 9 | sudo apt install python3-pip 10 | ``` 11 | --- 12 | **Arch Linux - Debian - Ubuntu** 13 | 14 | After installing *pip* for any of these distributions or their derivatives, you can install any library using the following command: 15 | ``` 16 | pip install libraryName 17 | ``` 18 | If this command doesn't work, you may need to specify the pip version to use, for example: 19 | ``` 20 | pip3 install libraryName 21 | ``` 22 | To uninstall a library, use the command: 23 | ``` 24 | pip uninstall libraryName 25 | ``` 26 | 27 | In case of any issues, you can search the internet for your specific problem and distribution to find a resolution. 28 | 29 | --- 30 | # Guida generale all'installazione delle librerie python nelle principali distro linux utilizzando *pip* 31 | 32 | Per l'installazione di *pip* su **Arch** il comando sarà il seguente: 33 | ``` 34 | sudo pacman -S python-pip 35 | ``` 36 | Per l'installazione di *pip* su **Debian** e **Ubuntu** il comando sarà il seguente: 37 | ``` 38 | sudo apt install python3-pip 39 | ``` 40 | --- 41 | **Arch linux - Debian - Ubuntu** 42 | 43 | Dopo aver installato *pip* per tutte queste distro o basate su di esse, per installare una qualsiasi libreria basterà utilizzare il seguente comando: 44 | ``` 45 | pip install nomeLibreria 46 | ``` 47 | Nel caso in cui questo comando non funzioni potrebbe essere necessario specificare la versione di pip da utilizzare ad esempio: 48 | ``` 49 | pip3 install nomeLibreria 50 | ``` 51 | Per disinstallare una libreria basterà utilizzare il comando: 52 | ``` 53 | pip uninstall nomeLibreria 54 | ``` 55 | 56 | In caso di problemi basterà cercare su Internet il proprio problema e distro e si troverà la risoluzione ad esso. 57 | -------------------------------------------------------------------------------- /pdfs/Cloud - Alexa.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - Alexa.pdf -------------------------------------------------------------------------------- /pdfs/Cloud - BLE.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - BLE.pdf -------------------------------------------------------------------------------- /pdfs/Cloud - IFTTT.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - IFTTT.pdf -------------------------------------------------------------------------------- /pdfs/Cloud - Infrared.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - Infrared.pdf -------------------------------------------------------------------------------- /pdfs/Cloud - Lego EV3 Robot.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - Lego EV3 Robot.pdf -------------------------------------------------------------------------------- /pdfs/Cloud - MQTT - ESP8266.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - MQTT - ESP8266.pdf -------------------------------------------------------------------------------- /pdfs/Cloud - RF433MHz.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - RF433MHz.pdf -------------------------------------------------------------------------------- /pdfs/Cloud - Telegram.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - Telegram.pdf -------------------------------------------------------------------------------- /pdfs/Cloud - Tuya.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - Tuya.pdf -------------------------------------------------------------------------------- /pdfs/Cloud - Zigbee Conbee 2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - Zigbee Conbee 2.pdf -------------------------------------------------------------------------------- /pdfs/Cloud - Zigbee2MQTT 1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - Zigbee2MQTT 1.pdf -------------------------------------------------------------------------------- /pdfs/Cloud - rete mesh su NRF24.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiorgioCitterio/Motor-and-Sensor-Control-on-Arduino-Raspberry-Pi-and-ESP/e7e6d03ea4918ca6551954b7c2266ac6315d86b3/pdfs/Cloud - rete mesh su NRF24.pdf --------------------------------------------------------------------------------