Skip to content

Instantly share code, notes, and snippets.

@ashwani-rathee
Created January 14, 2023 06:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashwani-rathee/20ddda143f5544fd7c685dd20195ab5f to your computer and use it in GitHub Desktop.
Save ashwani-rathee/20ddda143f5544fd7c685dd20195ab5f to your computer and use it in GitHub Desktop.
Arduino UNO with Julia project
using LibSerialPort
using Distributed
using ArgParse
portname = "/dev/ttyUSB0"
baudrate = 9600
struct CustomType
val::Int
end
function ArgParse.parse_item(::Type{CustomType}, x::AbstractString)
return CustomType(parse(Int, x))
end
s = ArgParseSettings()
@add_arg_table! s begin
"--tlow"
help = "temp high"
arg_type = Int
default = 10
"--thigh"
help = "temp low"
arg_type = Int
default = 50
"--hlow"
help = "humidity low"
arg_type = Int
default = 10
"--hhigh"
help = "humidity high"
arg_type = Int
default = 80
"--plow"
help = "pressure low"
arg_type = Int
default = 5000
"--phigh"
help = "pressure range"
arg_type = Int
default = 90000
"--alow"
help = "altitude low"
arg_type = Int
default = 200
"--ahigh"
help = "altitude high"
arg_type = Int
default = 1000
end
pargs = parse_args(ARGS, s)
tempr = [pargs["tlow"],pargs["thigh"]]
humr = [pargs["hlow"], pargs["hhigh"]]
presr = [pargs["plow"], pargs["phigh"]]
altr = [pargs["alow"], pargs["ahigh"]]
@info pargs
LibSerialPort.open(portname, baudrate) do sp
@info "Port Opened successfully!!"
function producer(c::Channel)
@info "Buffer Collector Started!!"
while(true)
if bytesavailable(sp) > 0
d = String(read(sp))
push!(c, d)
end
sleep(0.1)
end
end
chnl = Channel(producer);
@info "Channel Created!!"
function bufferreducer(sp)
@info "Buffer Reducer Started!!"
buffercollect = ""
while(true)
buffercollect = buffercollect * take!(chnl)
# println("Buffer Reducer:", length(buffercollect))
if(length(buffercollect) > 100)
reg = r"FRAMESTART:PACKETNUM:(?<packetnum>\d+),TEMPERATURE:(?<temperature>(.*))C,HUMIDITY:(?<humidity>(.*))%,PRESSURE:(?<pressure>\d+)Pa,ALTITUDE:(?<altitude>(.*))m,FRAMEEND\n"
a = match(reg, buffercollect)
if(a === nothing)
println("No match found")
continue
end
@info "Packet Found:" a[:packetnum] a.match
temp = parse(Float32, a[:temperature])
hum = parse(Float32, a[:humidity])
pres = parse(Int32, a[:pressure])
alt = parse(Float32, a[:altitude])
resp = """RESPONSESTART:RESPONSENO:$(a[:packetnum]),DATA:$(Int(temp < tempr[1] || temp > tempr[2]))$(Int(hum< humr[1] || hum> humr[2]))$(Int(pres < presr[1] || pres> presr[2]))$(Int(alt< altr[1] || alt > altr[2])),RESPONSEEND\n"""
@info "Response:" a[:packetnum] resp
write(sp, resp)
println("Response Sent for packet no." ,a[:packetnum])
buffercollect = buffercollect[a.offsets[end]+16:end]
end
sleep(0.1)
end
end
bufferreducer(sp)
end
// Imports
#include <Regexp.h>
#include <Wire.h>
#include <Adafruit_BMP085.h>
#include <DHTStable.h>
// DHT and BMP Object creation
DHTStable DHT;
Adafruit_BMP085 bmp;
// What's connected where
#define SWITCH 7
#define DHT_PIN 2
int counter = 0; // counter to keep track of packet number
const byte numChars = 64; // length of buffer
char receivedChars[numChars]; // an buffer to store the received data
boolean newData = false;
// Setup
void setup(void) {
Serial.begin(9600); // opens serial port at 9600 baud rate
pinMode(SWITCH, INPUT_PULLUP); // tell where push button is connected
pinMode(9, OUTPUT); // configuring 9,10,11,12 as output pins for LEDs
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
//Trying to find BMP sensor
if (!bmp.begin()) {
Serial.println("Could not find a valid BMP085 sensor, check wiring!");
while (1) {}
}
}
// Loop code which runs after every 100 ms
void loop() {
// Works on computer to microcontroller data
// Checks if computer has sent any data packets?
if(Serial.available()){
// adds that data to buffer
recvWithEndMarker();
showNewData(); // shows that data
// using regex to indentify reponse and its components
MatchState ms;
ms.Target(receivedChars);
// We want to match our response to this structure
// Ex: "RESPONSESTART:RESPONSENO:1,DATA:1111,RESPONSEEND"
// where each of the 4 points in data correpond to expected state
// LEDs
char result = ms.Match("RESPONSESTART:RESPONSENO:(%d+),DATA:(.)(.)(.)(.),RESPONSEEND");
// if we find a result
if (result > 0)
{
// we read data in (.) and change the LED on/off with digitalWrite
for (int j = 0; j < ms.level; j++)
{
int val = atoi(ms.GetCapture (receivedChars, j));
if(j >= 1 && j <= 4)
{
digitalWrite(j+8, val); // j+8 gets pin number, val is HIGH/LOW based on input
}
} // end of for each capture
}
else{
Serial.println ("No match.");
}
}
// Works on microcontroller to computer data
// Checks if button has been pressed or not
if (digitalRead(SWITCH) == LOW) {
//The button is pressed!
// reads
int readData = DHT.read11(DHT_PIN);
// Data Packet formation
// FRAMESTART..............FRAMEEND is one packet
// Above FRAMESTART, FRAMEEND can be considered magic bytes
// to uniquely identify the packet
Serial.print("FRAMESTART:");
Serial.print("PACKETNUM:");
Serial.print(counter%127);
Serial.print(",");
Serial.print("TEMPERATURE:");
Serial.print(DHT.getTemperature());
Serial.print("C,");
Serial.print("HUMIDITY:");
Serial.print(DHT.getHumidity());
Serial.print("%,");
Serial.print("PRESSURE:");
Serial.print(bmp.readPressure());
Serial.print("Pa,");
Serial.print("ALTITUDE:");
Serial.print(bmp.readAltitude());
Serial.print("m,");
Serial.print("FRAMEEND\n");
counter = counter + 1;
}
// delay of 100 ms before loop is run again
delay(100);
}
// recieves input till \0
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '\n';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
// prints the recieved data
void showNewData() {
if (newData == true) {
Serial.print("This just in ... ");
Serial.println(receivedChars);
newData = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment