-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuv_sensor_basic.py
More file actions
137 lines (114 loc) · 4.22 KB
/
Copy pathuv_sensor_basic.py
File metadata and controls
137 lines (114 loc) · 4.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#!/usr/bin/env python3
"""
Basic UV Sensor Script
Simple script to read UV data from VEML6075 sensor
"""
import time
import json
from datetime import datetime
from smbus2 import SMBus
# I2C Configuration
I2C_BUS = 3 # Changed from 1 to 3 - UV sensor is on bus 3
VEML6075_ADDR = 0x10
# VEML6075 UV sensor registers
REG_CONF = 0x00
REG_UVB = 0x09
VEML6075_CONF_100MS = 0x00
class UVSensor:
def __init__(self, bus, address, sensor_name):
self.bus = bus
self.address = address
self.sensor_name = sensor_name
self.working = False
self.initialize()
def initialize(self):
"""Initialize VEML6075 sensor"""
try:
# Set configuration for 100ms integration time
self.bus.write_word_data(self.address, REG_CONF, VEML6075_CONF_100MS)
time.sleep(0.2)
# Verify configuration
conf = self.bus.read_word_data(self.address, REG_CONF)
if conf == VEML6075_CONF_100MS:
self.working = True
print(f"✅ {self.sensor_name} UV sensor initialized successfully")
else:
print(f"❌ {self.sensor_name} UV sensor configuration failed")
except Exception as e:
print(f"❌ Failed to initialize {self.sensor_name} UV sensor: {e}")
def read_uvb(self):
"""Read UVB level"""
if not self.working:
return None
try:
# Read UVB data (16-bit)
val = self.bus.read_word_data(self.address, REG_UVB)
# Swap bytes (little endian to big endian)
uvb = ((val & 0xFF) << 8) | (val >> 8)
return uvb
except Exception as e:
print(f"Error reading {self.sensor_name} UVB: {e}")
return None
def get_uv_index(self, uvb_value):
"""Convert UVB counts to UV Index (approximate)"""
if uvb_value is None:
return None
# This is an approximate conversion - actual conversion depends on sensor calibration
# VEML6075 typically needs calibration for accurate UV Index
uv_index = uvb_value / 100.0 # Rough approximation
return round(uv_index, 2)
def main():
print("🌞 Starting Basic UV Sensor...")
# Initialize I2C bus
try:
bus = SMBus(I2C_BUS)
print(f"✅ I2C bus {I2C_BUS} initialized")
except Exception as e:
print(f"❌ Failed to initialize I2C bus: {e}")
return
# Initialize UV sensor
try:
uv_sensor = UVSensor(bus, VEML6075_ADDR, "VEML6075")
if not uv_sensor.working:
print("❌ UV sensor not working. Exiting.")
return
except Exception as e:
print(f"❌ Failed to initialize UV sensor: {e}")
return
print("📡 Starting UV data collection...")
print("Press Ctrl+C to stop")
print("-" * 50)
try:
while True:
timestamp = datetime.now().isoformat()
# Read UV sensor
uvb_value = uv_sensor.read_uvb()
uv_index = uv_sensor.get_uv_index(uvb_value)
if uvb_value is not None:
print(f"📊 UVB Counts: {uvb_value}")
print(f"🌡️ UV Index: {uv_index}")
print(f"⏰ Timestamp: {timestamp}")
# Create data dictionary
data = {
"sensor": "VEML6075",
"uvb_counts": uvb_value,
"uv_index": uv_index,
"timestamp": timestamp
}
# Save to JSON file (optional)
with open("uv_data.json", "w") as f:
json.dump(data, f, indent=2)
print("-" * 50)
else:
print("⚠️ Failed to read UV sensor data")
# Wait before next reading
time.sleep(2) # Read every 2 seconds
except KeyboardInterrupt:
print("\n🛑 Stopping UV sensor...")
except Exception as e:
print(f"❌ Error in main loop: {e}")
finally:
bus.close()
print("👋 UV sensor stopped")
if __name__ == "__main__":
main()