Last active
March 6, 2019 03:01
-
-
Save TonsOfFun/80e195c6092302290af700e0349c4e69 to your computer and use it in GitHub Desktop.
Using this for Arduino sensor readings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Wire.h> | |
#include <Adafruit_AM2315.h> | |
/*************************************************** | |
This is an example for the AM2315 Humidity + Temp sensor | |
Designed specifically to work with the Adafruit BMP085 Breakout | |
----> https://www.adafruit.com/products/1293 | |
These displays use I2C to communicate, 2 pins are required to | |
interface | |
Adafruit invests time and resources providing this open source code, | |
please support Adafruit and open-source hardware by purchasing | |
products from Adafruit! | |
Written by Limor Fried/Ladyada for Adafruit Industries. | |
BSD license, all text above must be included in any redistribution | |
****************************************************/ | |
// Connect RED of the AM2315 sensor to 5.0V | |
// Connect BLACK to Ground | |
// Connect WHITE to i2c clock - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 5 | |
// Connect YELLOW to i2c data - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 4 | |
Adafruit_AM2315 am2315; | |
void setup() { | |
Serial.begin(9600); | |
Serial.println("AM2315 Test!"); | |
if (! am2315.begin()) { | |
Serial.println("Sensor not found, check wiring & pullups!"); | |
while (1); | |
} | |
} | |
void loop() { | |
Serial.print("Air Humidity: "); Serial.println(am2315.readHumidity()); | |
Serial.print("Air Temperature: "); Serial.println(am2315.readTemperature()); | |
delay(1000); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//**THIS CODE WILL WORK ON ANY ARDUINO** | |
//This code was written to be easy to understand. | |
//Modify this code as you see fit. | |
//This code will output data to the Arduino serial monitor. | |
//Type commands into the Arduino serial monitor to control the pH circuit. | |
//An Arduino UNO was used to test this code. | |
//This code was written in the Arduino 1.8.5 IDE | |
//This code was last tested 1/2018 | |
#include <Wire.h> //enable I2C. | |
#define address 99 //default I2C ID number for EZO pH Circuit. | |
char computerdata[20]; //we make a 20 byte character array to hold incoming data from a pc/mac/other. | |
byte received_from_computer = 0; //we need to know how many characters have been received. | |
byte code = 0; //used to hold the I2C response code. | |
char ph_data[20]; //we make a 20-byte character array to hold incoming data from the pH circuit. | |
byte in_char = 0; //used as a 1 byte buffer to store inbound bytes from the pH Circuit. | |
byte i = 0; //counter used for ph_data array. | |
int time_ = 900; //used to change the delay needed depending on the command sent to the EZO Class pH Circuit. | |
float ph_float; //float var used to hold the float value of the pH. | |
void setup() //hardware initialization. | |
{ | |
Serial.begin(9600); //enable serial port. | |
Wire.begin(); //enable I2C port. | |
} | |
void loop() { //the main loop. | |
if (Serial.available() > 0) { //if data is holding in the serial buffer | |
received_from_computer = Serial.readBytesUntil(13, computerdata, 20); //we read the data sent from the serial monitor(pc/mac/other) until we see a <CR>. We also count how many characters have been received. | |
computerdata[received_from_computer] = 0; //stop the buffer from transmitting leftovers or garbage. | |
computerdata[0] = tolower(computerdata[0]); //we make sure the first char in the string is lower case. | |
if (computerdata[0] == 'c' || computerdata[0] == 'r')time_ = 900; //if a command has been sent to calibrate or take a reading we wait 1800ms so that the circuit has time to take the reading. | |
else time_ = 300; //if any other command has been sent we wait only 300ms. | |
Wire.beginTransmission(address); //call the circuit by its ID number. | |
Wire.write(computerdata); //transmit the command that was sent through the serial port. | |
Wire.endTransmission(); //end the I2C data transmission. | |
if (strcmp(computerdata, "sleep") != 0) { //if the command that has been sent is NOT the sleep command, wait the correct amount of time and request data. | |
//if it is the sleep command, we do nothing. Issuing a sleep command and then requesting data will wake the pH circuit. | |
delay(time_); //wait the correct amount of time for the circuit to complete its instruction. | |
Wire.requestFrom(address, 20, 1); //call the circuit and request 20 bytes (this may be more than we need) | |
code = Wire.read(); //the first byte is the response code, we read this separately. | |
switch (code) { //switch case based on what the response code is. | |
case 1: //decimal 1. | |
Serial.println("Success"); //means the command was successful. | |
break; //exits the switch case. | |
case 2: //decimal 2. | |
Serial.println("Failed"); //means the command has failed. | |
break; //exits the switch case. | |
case 254: //decimal 254. | |
Serial.println("Pending"); //means the command has not yet been finished calculating. | |
break; //exits the switch case. | |
case 255: //decimal 255. | |
Serial.println("No Data"); //means there is no further data to send. | |
break; //exits the switch case. | |
} | |
while (Wire.available()) { //are there bytes to receive. | |
in_char = Wire.read(); //receive a byte. | |
ph_data[i] = in_char; //load this byte into our array. | |
i += 1; //incur the counter for the array element. | |
if (in_char == 0) { //if we see that we have been sent a null command. | |
i = 0; //reset the counter i to 0. | |
Wire.endTransmission(); //end the I2C data transmission. | |
break; //exit the while loop. | |
} | |
} | |
Serial.println(ph_data); //print the data. | |
} | |
} | |
//Uncomment this section if you want to take the pH value and convert it into floating point number. | |
//ph_float=atof(ph_data); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* HC-SR04 example sketch | |
* | |
* https://create.arduino.cc/projecthub/Isaac100/getting-started-with-the-hc-sr04-ultrasonic-sensor-036380 | |
* | |
* by Isaac100 | |
*/ | |
const int trigPin = 9; | |
const int echoPin = 10; | |
float duration, distance; | |
void setup() { | |
pinMode(trigPin, OUTPUT); | |
pinMode(echoPin, INPUT); | |
Serial.begin(9600); | |
} | |
void loop() { | |
digitalWrite(trigPin, LOW); | |
delayMicroseconds(2); | |
digitalWrite(trigPin, HIGH); | |
delayMicroseconds(10); | |
digitalWrite(trigPin, LOW); | |
duration = pulseIn(echoPin, HIGH); | |
distance = (duration*.0343)/2; | |
Serial.print("Distance: "); | |
Serial.println(distance); | |
delay(100); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//**THIS CODE WILL WORK ON ANY ARDUINO** | |
//This code was written to be easy to understand. | |
//Modify this code as you see fit. | |
//This code will output data to the Arduino serial monitor. | |
//Type commands into the Arduino serial monitor to control the pH circuit. | |
//An Arduino UNO was used to test this code. | |
//This code was written in the Arduino 1.8.5 IDE | |
//This code was last tested 1/2018 | |
#include <Wire.h> //enable I2C. | |
#define address 99 //default I2C ID number for EZO pH Circuit. | |
char computerdata[20]; //we make a 20 byte character array to hold incoming data from a pc/mac/other. | |
byte received_from_computer = 0; //we need to know how many characters have been received. | |
byte code = 0; //used to hold the I2C response code. | |
char ph_data[20]; //we make a 20-byte character array to hold incoming data from the pH circuit. | |
byte in_char = 0; //used as a 1 byte buffer to store inbound bytes from the pH Circuit. | |
byte i = 0; //counter used for ph_data array. | |
int time_ = 900; //used to change the delay needed depending on the command sent to the EZO Class pH Circuit. | |
float ph_float; //float var used to hold the float value of the pH. | |
void setup() //hardware initialization. | |
{ | |
Serial.begin(9600); //enable serial port. | |
Wire.begin(); //enable I2C port. | |
} | |
void loop() { //the main loop. | |
if (Serial.available() > 0) { //if data is holding in the serial buffer | |
received_from_computer = Serial.readBytesUntil(13, computerdata, 20); //we read the data sent from the serial monitor(pc/mac/other) until we see a <CR>. We also count how many characters have been received. | |
computerdata[received_from_computer] = 0; //stop the buffer from transmitting leftovers or garbage. | |
computerdata[0] = tolower(computerdata[0]); //we make sure the first char in the string is lower case. | |
if (computerdata[0] == 'c' || computerdata[0] == 'r')time_ = 900; //if a command has been sent to calibrate or take a reading we wait 1800ms so that the circuit has time to take the reading. | |
else time_ = 300; //if any other command has been sent we wait only 300ms. | |
Wire.beginTransmission(address); //call the circuit by its ID number. | |
Wire.write(computerdata); //transmit the command that was sent through the serial port. | |
Wire.endTransmission(); //end the I2C data transmission. | |
if (strcmp(computerdata, "sleep") != 0) { //if the command that has been sent is NOT the sleep command, wait the correct amount of time and request data. | |
//if it is the sleep command, we do nothing. Issuing a sleep command and then requesting data will wake the pH circuit. | |
delay(time_); //wait the correct amount of time for the circuit to complete its instruction. | |
Wire.requestFrom(address, 20, 1); //call the circuit and request 20 bytes (this may be more than we need) | |
code = Wire.read(); //the first byte is the response code, we read this separately. | |
switch (code) { //switch case based on what the response code is. | |
case 1: //decimal 1. | |
Serial.println("Success"); //means the command was successful. | |
break; //exits the switch case. | |
case 2: //decimal 2. | |
Serial.println("Failed"); //means the command has failed. | |
break; //exits the switch case. | |
case 254: //decimal 254. | |
Serial.println("Pending"); //means the command has not yet been finished calculating. | |
break; //exits the switch case. | |
case 255: //decimal 255. | |
Serial.println("No Data"); //means there is no further data to send. | |
break; //exits the switch case. | |
} | |
while (Wire.available()) { //are there bytes to receive. | |
in_char = Wire.read(); //receive a byte. | |
ph_data[i] = in_char; //load this byte into our array. | |
i += 1; //incur the counter for the array element. | |
if (in_char == 0) { //if we see that we have been sent a null command. | |
i = 0; //reset the counter i to 0. | |
Wire.endTransmission(); //end the I2C data transmission. | |
break; //exit the while loop. | |
} | |
} | |
Serial.println(ph_data); //print the data. | |
} | |
} | |
//Uncomment this section if you want to take the pH value and convert it into floating point number. | |
//ph_float=atof(ph_data); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import serial | |
from serial.tools import list_ports | |
ser = serial.Serial(list_ports.comports()[1].device, 9600) | |
while True: | |
print(ser.readline()) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import io # used to create file streams | |
import fcntl # used to access I2C parameters like addresses | |
import time # used for sleep delay and timestamps | |
import string # helps parse strings | |
class atlas_i2c: | |
long_timeout = 1.5 # the timeout needed to query readings and calibrations | |
short_timeout = .5 # timeout for regular commands | |
default_bus = 1 # the default bus for I2C on the newer Raspberry Pis, certain older boards use bus 0 | |
default_address = 99 # the default address for the pH sensor | |
def __init__(self, address = default_address, bus = default_bus): | |
# open two file streams, one for reading and one for writing | |
# the specific I2C channel is selected with bus | |
# it is usually 1, except for older revisions where its 0 | |
# wb and rb indicate binary read and write | |
self.file_read = io.open("/dev/i2c-"+str(bus), "rb", buffering = 0) | |
self.file_write = io.open("/dev/i2c-"+str(bus), "wb", buffering = 0) | |
# initializes I2C to either a user specified or default address | |
self.set_i2c_address(address) | |
def set_i2c_address(self, addr): | |
# set the I2C communications to the slave specified by the address | |
# The commands for I2C dev using the ioctl functions are specified in | |
# the i2c-dev.h file from i2c-tools | |
I2C_SLAVE = 0x703 | |
fcntl.ioctl(self.file_read, I2C_SLAVE, addr) | |
fcntl.ioctl(self.file_write, I2C_SLAVE, addr) | |
def write(self, string): | |
# appends the null character and sends the string over I2C | |
string += "\00" | |
self.file_write.write(string) | |
def read(self, num_of_bytes = 31): | |
# reads a specified number of bytes from I2C, then parses and displays the result | |
res = self.file_read.read(num_of_bytes) # read from the board | |
response = filter(lambda x: x != '\x00', res) # remove the null characters to get the response | |
if(ord(response[0]) == 1): # if the response isnt an error | |
char_list = map(lambda x: chr(ord(x) & ~0x80), list(response[1:])) # change MSB to 0 for all received characters except the first and get a list of characters | |
# NOTE: having to change the MSB to 0 is a glitch in the raspberry pi, and you shouldn't have to do this! | |
return "Command succeeded " + ''.join(char_list) # convert the char list to a string and returns it | |
else: | |
return "Error " + str(ord(response[0])) | |
def query(self, string): | |
# write a command to the board, wait the correct timeout, and read the response | |
self.write(string) | |
# the read and calibration commands require a longer timeout | |
if((string.upper().startswith("R")) or | |
(string.upper().startswith("CAL"))): | |
time.sleep(self.long_timeout) | |
elif((string.upper().startswith("SLEEP"))): | |
return "sleep mode" | |
else: | |
time.sleep(self.short_timeout) | |
return self.read() | |
def close(self): | |
self.file_read.close() | |
self.file_write.close() | |
def main(): | |
device = atlas_i2c() # creates the I2C port object, specify the address or bus if necessary | |
print(">> Atlas Scientific sample code") | |
print(">> Any commands entered are passed to the board via I2C except:") | |
print(">> Address,xx changes the I2C address the Raspberry Pi communicates with.") | |
print(">> Poll,xx.x command continuously polls the board every xx.x seconds") | |
print(" where xx.x is longer than the %0.2f second timeout." % atlas_i2c.long_timeout) | |
print(" Pressing ctrl-c will stop the polling") | |
# main loop | |
while True: | |
input = raw_input("Enter command: ") | |
# address command lets you change which address the Raspberry Pi will poll | |
if(input.upper().startswith("ADDRESS")): | |
addr = int(string.split(input, ',')[1]) | |
device.set_i2c_address(addr) | |
print("I2C address set to " + str(addr)) | |
# contiuous polling command automatically polls the board | |
elif(input.upper().startswith("POLL")): | |
delaytime = float(string.split(input, ',')[1]) | |
# check for polling time being too short, change it to the minimum timeout if too short | |
if(delaytime < atlas_i2c.long_timeout): | |
print("Polling time is shorter than timeout, setting polling time to %0.2f" % atlas_i2c.long_timeout) | |
delaytime = atlas_i2c.long_timeout | |
# get the information of the board you're polling | |
info = string.split(device.query("I"), ",")[1] | |
print("Polling %s sensor every %0.2f seconds, press ctrl-c to stop polling" % (info, delaytime)) | |
try: | |
while True: | |
print(device.query("R")) | |
time.sleep(delaytime - atlas_i2c.long_timeout) | |
except KeyboardInterrupt: # catches the ctrl-c command, which breaks the loop above | |
print("Continuous polling stopped") | |
# if not a special keyword, pass commands straight to board | |
else: | |
try: | |
print(device.query(input)) | |
except IOError: | |
print("Query failed") | |
if __name__ == '__main__': | |
main() | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*************************************************** | |
This is a sketch to test the soil sensor based | |
on the SHT10 temperature & humidity sensor | |
Written by Marco Schwartz for Open Home Automation | |
****************************************************/ | |
// Include Sensirion library | |
#include <Sensirion.h> | |
// Sensor pins | |
const uint8_t dataPin = 6; | |
const uint8_t clockPin = 7; | |
// Variables for the temperature & humidity sensor | |
float temperature; | |
float humidity; | |
float dewpoint; | |
// Create sensor instance | |
Sensirion soilSensor = Sensirion(dataPin, clockPin); | |
void setup() | |
{ | |
Serial.begin(9600); | |
} | |
void loop() | |
{ | |
// Make a measurement | |
soilSensor.measure(&temperature, &humidity, &dewpoint); | |
// Print results | |
Serial.print("Soil Temperature: "); | |
Serial.println(temperature); | |
Serial.print("Soil Humidity: "); | |
Serial.println(humidity); | |
// Wait 1000 ms before next measurement | |
delay(1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment