diff --git a/docs/tutorials/i2c-environmental-sensor-module.mdx b/docs/tutorials/i2c-environmental-sensor-module.mdx new file mode 100644 index 0000000..88b5569 --- /dev/null +++ b/docs/tutorials/i2c-environmental-sensor-module.mdx @@ -0,0 +1,845 @@ +--- +title: Building an I2C Environmental Sensor Module +description: >- + This tutorial will walk you through building an I2C environmental sensor module + featuring temperature, humidity, and pressure sensing using the BME280 sensor, + perfect for weather stations, home automation, and environmental monitoring. +--- + +## Overview + +This tutorial will walk you through building an I2C environmental sensor module using the popular BME280 sensor. The BME280 is a combined digital sensor that measures temperature, barometric pressure, and humidity with high accuracy. This module is ideal for weather stations, home automation systems, HVAC monitoring, and environmental data logging. + +import CircuitPreview from "@site/src/components/CircuitPreview" +import TscircuitIframe from "@site/src/components/TscircuitIframe" + + ( + + {/* BME280 Environmental Sensor */} + + + {/* I2C Pull-up Resistors */} + + + {/* OLED Display for readings */} + + + {/* Status LED */} + + + + {/* Power Capacitor */} + + + {/* I2C header for external connection */} + + + {/* Connect I2C bus */} + + + + + + {/* Connect power */} + + + + + + {/* Connect header */} + + + + + + {/* Connect LED */} + + + + + {/* Connect decoupling capacitor */} + + + +) +`} /> + +## What is an Environmental Sensor Module? + +Environmental sensor modules measure physical conditions in the surrounding environment: + +- **Temperature**: Ambient air temperature in Celsius or Fahrenheit +- **Humidity**: Relative humidity percentage (0-100% RH) +- **Barometric Pressure**: Atmospheric pressure in hPa/mbar + +### Why Build Your Own? + +Building a custom environmental sensor module offers advantages: + +- **Custom form factor**: Design for your specific enclosure or application +- **Integration**: Combine sensor with display, wireless, or data logging +- **Learning**: Understand I2C communication and sensor integration +- **Cost optimization**: Only include components you need + +## Understanding the BME280 Sensor + +The BME280 from Bosch is a popular environmental sensor because: + +- **High accuracy**: Temperature (±0.5°C), humidity (±3% RH), pressure (±1 hPa) +- **Low power**: 3.6µA typical current consumption +- **I2C/SPI interface**: Flexible communication options +- **Small package**: 2.5mm x 2.5mm LGA-8 package +- **Digital filter**: Built-in noise reduction + +### BME280 Specifications + +| Parameter | Value | +|-----------|-------| +| Temperature Range | -40°C to +85°C | +| Pressure Range | 300 to 1100 hPa | +| Humidity Range | 0 to 100% RH | +| I2C Address | 0x76 (SDO=0) or 0x77 (SDO=1) | +| Supply Voltage | 1.71V to 3.6V | +| Interface | I2C (up to 3.4MHz) or SPI (up to 10MHz) | + +### I2C Communication + +The BME280 uses standard I2C communication: + +``` +Device Address: 0x76 or 0x77 (set by SDO pin) +Registers: + - 0xD0: Chip ID (should read 0x60) + - 0xF7: pressure_msb (start of readout) + - 0xF2: ctrl_hum (humidity oversampling) + - 0xF4: ctrl_meas (temperature/pressure settings) + - 0xF5: config (standby, filter) +``` + +## Circuit Requirements + +Our environmental sensor module needs: + +1. **BME280 sensor** for temperature, humidity, and pressure +2. **I2C pull-up resistors** (typically 4.7kΩ) +3. **Power decoupling capacitor** (100nF) +4. **Status LED** to indicate power +5. **Pin header** for external connections +6. **Optional OLED display** for local readings + +## Building the Circuit Step by Step + +### Step 1: Create the Board and Add the BME280 Sensor + +Start with a board and place the BME280 sensor at the center. + +```tsx +import { BME280 } from "@tsci/seveibar.bme280" + +export default () => ( + + + +) +``` + + ( + + + +) +`} /> + +### Step 2: Add the I2C Pull-up Resistors + +I2C requires pull-up resistors on SDA and SCL lines. The BME280 and most microcontrollers have open-drain outputs, so pull-ups are essential. + + ( + + + + +) +`} /> + +### Step 3: Add the Power Decoupling Capacitor + +Place a 100nF capacitor close to the BME280's VCC pin to filter high-frequency noise. + + ( + + + + + +) +`} /> + +### Step 4: Add the Pin Header for External Connection + +A 4-pin header allows connection to microcontrollers or other I2C devices. + + ( + + + + + + +) +`} /> + +### Step 5: Connect All Components + +Now let's wire everything together with proper traces. + + ( + + + + + + + {/* Connect I2C bus to sensor and pull-ups */} + + + + {/* Connect header */} + + + + + + {/* Connect power to sensor */} + + + + {/* Connect decoupling capacitor */} + + + +) +`} /> + +### Step 6: Add the Optional OLED Display + +Adding an OLED display creates a standalone weather station that can display readings without needing a computer. + + ( + + + + + + + + + + + + + + + + + + + + + + +) +`} /> + +### Step 7: Add Status LED + +A status LED provides visual confirmation that the module is powered. + + ( + + + + + + + + + + + + + + + + + + + + + + + + + + + +) +`} /> + +## Complete 3D View + +Here's the complete module with all components in 3D: + + ( + + + + + + + + + + + + + + + + + + + + + + + + + + + +) +`} /> + +## Complete Circuit Schematic + +Here's the full schematic showing all component connections: + + ( + + + + + + + + + + + + + + + + + + + + + + + + + + + +) +`} /> + +## Bill of Materials + +| Reference | Component | Value | Footprint | Notes | +|-----------|-----------|-------|-----------|-------| +| U1 | BME280 Sensor | - | LGA-8 | Temperature, humidity, pressure | +| OLED1 | SSD1306 OLED | 0.96" 128x64 | - | I2C OLED display | +| R1 | Resistor | 330Ω | 0603 | LED current limit | +| R2, R3 | Resistor | 4.7kΩ | 0603 | I2C pull-ups | +| C1 | Capacitor | 100nF | 0603 | Power decoupling | +| J1 | Pin Header | 1x4 male | THT | External connection | +| LED1 | LED | Blue | 0805 | Power indicator | + +## PCB Layout Recommendations + +### Sensor Placement + +The BME280 should be placed with consideration for: + +1. **Keep-out zone**: Avoid placing tall components nearby that might block airflow +2. **Ventilation**: The sensor needs to "breathe" - consider adding small holes in the enclosure +3. **Distance from heat sources**: Keep away from components that generate heat (regulators, displays) +4. **Board orientation**: If using as a vertical module, place sensor on the edge + +### I2C Bus Layout + +For the I2C bus: + +1. **Pull-up resistor placement**: Place near the master device or split between ends +2. **Bus capacitance**: Keep total bus capacitance under 400pF for reliable 400kHz operation +3. **Trace length**: I2C is not sensitive to trace length for typical hobby projects +4. **Shielding**: Not necessary for most applications, but keep away from noisy signals + +### Decoupling Capacitor Placement + +The 100nF capacitor should be: + +1. **As close as possible** to the BME280 VCC pin +2. **On the same side** of the board as the sensor if possible +3. **Connected with short traces** to both VCC and GND + +## Using the Module with Microcontrollers + +### Arduino Connection + +```cpp +#include +#include +#include +#include + +#define SEALEVELPRESSURE_HPA (1013.25) + +Adafruit_BME280 bme; +Adafruit_SSD1306 display(128, 64, &Wire); + +void setup() { + Serial.begin(9600); + + // Initialize BME280 + if (!bme.begin(0x76)) { + Serial.println("Could not find a valid BME280 sensor!"); + while (1); + } + + // Initialize OLED + display.begin(SSD1306_SWITCHCAPVCC, 0x3C); + display.display(); + delay(1000); +} + +void loop() { + // Read sensor values + float temp = bme.readTemperature(); + float humidity = bme.readHumidity(); + float pressure = bme.readPressure() / 100.0F; + + // Print to Serial + Serial.print("Temperature: "); + Serial.print(temp); + Serial.println(" °C"); + + Serial.print("Humidity: "); + Serial.print(humidity); + Serial.println(" %"); + + Serial.print("Pressure: "); + Serial.print(pressure); + Serial.println(" hPa"); + + // Display on OLED + display.clearDisplay(); + display.setTextSize(1); + display.setTextColor(SSD1306_WHITE); + display.setCursor(0, 0); + display.println("Weather Station"); + display.setTextSize(2); + display.print(temp, 1); + display.println(" C"); + display.print(humidity, 0); + display.println(" %"); + display.print(pressure, 0); + display.println(" hPa"); + display.display(); + + delay(2000); +} +``` + +### Raspberry Pi Python Example + +```python +import smbus2 +import bme280 +import time + +# Initialize I2C bus +bus = smbus2.SMBus(1) +address = 0x76 + +# Load calibration parameters +calibration_params = bme280.load_calibration_params(bus, address) + +while True: + # Read sensor data + data = bme280.read(bus, address, calibration_params) + + print(f"Temperature: {data.temperature:.2f} C") + print(f"Humidity: {data.humidity:.2f} %") + print(f"Pressure: {data.pressure:.2f} hPa") + + # Calculate altitude (optional) + altitude = 44330 * (1 - (data.pressure / 1013.25) ** 0.1903) + print(f"Altitude: {altitude:.2f} m") + + time.sleep(2) +``` + +### ESP32 Example + +```cpp +#include +#include +#include + +#define I2C_SDA 21 +#define I2C_SCL 22 + +Adafruit_BME280 bme; + +void setup() { + Serial.begin(115200); + + // Initialize I2C with custom pins + Wire.begin(I2C_SDA, I2C_SCL); + + if (!bme.begin(0x76, &Wire)) { + Serial.println("Could not find BME280!"); + while (1); + } + + // Connect to WiFi + WiFi.begin("SSID", "PASSWORD"); +} + +void loop() { + Serial.printf("Temperature: %.2f C\n", bme.readTemperature()); + Serial.printf("Humidity: %.2f %%\n", bme.readHumidity()); + Serial.printf("Pressure: %.2f hPa\n", bme.readPressure() / 100); + + delay(1000); +} +``` + +## Advanced: Altitude Compensation + +Barometric pressure varies with altitude. To calculate altitude from pressure readings: + +``` +Altitude = 44330 × (1 - (P/P0)^0.1903) +``` + +Where: +- P = measured pressure +- P0 = sea level pressure (typically 1013.25 hPa) + +You can also use local weather station data for more accurate P0 values. + +## Adding More Sensors + +The I2C bus can support multiple sensors. Common additions: + +### Gas Sensor (MQ-135) + +```tsx +// Add to existing circuit +import { MQ135 } from "@tsci/common.mq135" + + +``` + +### UV Sensor (VEML6075) + +```tsx +import { VEML6075 } from "@tsci/common.veml6075" + + +``` + +## Enclosure Design + +When designing an enclosure for your sensor module: + +1. **Ventilation holes**: Add small holes for air circulation +2. **Sensor window**: If using an OLED, plan for a viewing window +3. **Cable routing**: Consider strain relief for the header wires +4. **Mounting**: Add holes for standoffs or magnets +5. **Material**: Avoid airtight enclosures - the sensor needs airflow +6. **Sunlight**: If used outdoors, protect from direct sunlight + +## Troubleshooting + +### Sensor Not Detected + +1. Check I2C address (try 0x76 and 0x77) +2. Verify pull-up resistors are installed +3. Check SDA/SCL connections +4. Verify voltage (BME280 needs 3.3V) + +### Readings Seem Off + +1. Allow 20 minutes for sensor to stabilize +2. Check for heat sources near sensor +3. Verify calibration parameters +4. Compare with known-good reference + +### I2C Communication Errors + +1. Check bus capacitance (<400pF) +2. Reduce I2C speed to 100kHz +3. Add stronger pull-ups (2.2kΩ) +4. Check for short circuits + +## Conclusion + +You now have a complete environmental sensor module that can: + +- Measure temperature, humidity, and barometric pressure +- Display readings on an integrated OLED +- Interface with any microcontroller via I2C +- Be extended with additional sensors + +This project demonstrates important skills in sensor integration, I2C communication, and PCB design that apply to many embedded systems projects. + +## Next Steps + +- Add wireless connectivity (ESP8266, nRF24L01, LoRa) +- Implement data logging with SD card +- Create a web dashboard for remote monitoring +- Design a 3D-printed enclosure +- Build a multi-sensor array for distributed monitoring +- Add solar power for outdoor deployment + +## Resources + +- [BME280 Datasheet](https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bme280-ds002.pdf) +- [Adafruit BME280 Guide](https://learn.adafruit.com/adafruit-bme280-humidity-barometric-pressure-temperature-sensor-breakout) +- [I2C Protocol Overview](https://www.i2c-bus.org/specification/) +- [tscircuit Documentation](/docs/intro/overview) diff --git a/docs/tutorials/usb-pd-trigger-hat.mdx b/docs/tutorials/usb-pd-trigger-hat.mdx new file mode 100644 index 0000000..837d906 --- /dev/null +++ b/docs/tutorials/usb-pd-trigger-hat.mdx @@ -0,0 +1,606 @@ +--- +title: Building a USB Power Delivery Trigger HAT +description: >- + This tutorial will walk you through building a USB Power Delivery (PD) trigger + board that can negotiate different voltage levels (5V, 9V, 12V, 15V, 20V) from + USB-C power supplies, useful for powering projects that need higher voltages. +--- + +## Overview + +This tutorial will walk you through building a USB Power Delivery (PD) trigger HAT for Raspberry Pi. USB PD allows devices to request specific voltage levels from compatible power supplies, enabling projects that require more than the standard 5V. This is perfect for powering motors, LED strips, or other peripherals that need 9V-20V. + +import CircuitPreview from "@site/src/components/CircuitPreview" +import TscircuitIframe from "@site/src/components/TscircuitIframe" + + ( + + {/* USB-C PD Controller/Trigger Chip */} + + + {/* Output Terminal Block for 12V/3A */} + + + {/* Status LED - Power Indicator */} + + + {/* Current Limiting Resistor for LED */} + + + {/* Capacitor for input filtering */} + + + {/* Capacitor for output filtering */} + + + {/* Connect USB-C CC lines to PD controller */} + + + {/* Connect output terminals to VBUS */} + + + {/* Connect ground to terminal and HAT GND */} + + + + {/* Connect status LED with resistor */} + + + + + {/* Connect capacitors for filtering */} + + + + + +) +`} /> + +## What is USB Power Delivery? + +USB Power Delivery (PD) is a fast charging protocol that allows USB-C devices to negotiate power levels beyond the standard 5V/500mA. With USB PD, devices can request: + +| Voltage | Maximum Current | Maximum Power | +|---------|-----------------|---------------| +| 5V | 3A | 15W | +| 9V | 3A | 27W | +| 12V | 2.5A | 30W | +| 15V | 2A | 30W | +| 20V | 3A | 60W | + +### Why Build a PD Trigger Board? + +USB PD trigger boards are useful for: + +- **Projects requiring higher voltages**: Motors, solenoids, and some LED strips need 9V-20V +- **Efficient power delivery**: USB PD is more efficient than boost converters +- **Universal power source**: Use any USB-C PD power supply (phone chargers, laptop chargers, power banks) +- **Safe voltage selection**: Programmable boards can limit maximum voltage + +## Circuit Requirements + +Our USB PD Trigger HAT needs to: + +1. **Detect USB-C connection** via CC pins +2. **Communicate with PD controller** to negotiate voltage/current +3. **Output regulated power** to terminal block +4. **Include filtering capacitors** for clean power +5. **Add status indicators** (LED for power-on) + +## Understanding the Components + +### USB-C Connector with PD Controller + +The PD controller (such as FP28XX, CH224K, or PD2001) handles all USB PD negotiation: +- Monitors CC1/CC2 pins for source connection +- Sends PDO (Power Data Object) requests +- Enables internal MOSFET when voltage is negotiated +- Provides overcurrent protection + +### Filtering Capacitors + +Input and output capacitors are critical: +- **Input capacitor (10uF)**: Filters high-frequency noise from USB source +- **Output capacitor (22uF)**: Provides stable output for load transients +- Both should be rated for the maximum voltage (25V minimum) + +### Status LED + +A green LED indicates when output power is active: +- Current limiting resistor (330Ω) sets LED current to ~10mA +- Connected to output VBUS so it shows when power is available + +### Terminal Block + +A 2-pin terminal block provides easy connection: +- Output voltage (VBUS) on pin 1 +- Ground on pin 2 +- Rated for the expected current (3A-5A recommended) + +## Building the Circuit Step by Step + +### Step 1: Import the RaspberryPiHatBoard and PD Trigger + +First, we import the base HAT board and the PD trigger component. + +```tsx +import { RaspberryPiHatBoard } from "@tscircuit/common" +import { PD2001_Trigger } from "@tscircuit/common" + +export default () => ( + + {/* PD Trigger will go here */} + +) +``` + + ( + + + +) +`} /> + +### Step 2: Add the Terminal Block + +The terminal block provides screw terminals for connecting your load. + + ( + + + + +) +`} /> + +### Step 3: Add the Status LED and Resistor + +Add visual feedback for when power is active. + + ( + + + + + + +) +`} /> + +### Step 4: Add the Filtering Capacitors + +Capacitors smooth out voltage fluctuations and provide transient response. + + ( + + + + + + + + +) +`} /> + +### Step 5: Connect Everything with Traces + +Now we wire all the components together to complete the circuit. + + ( + + + + + + + + + {/* Connect terminal block to VBUS and GND */} + + + + + {/* Connect status LED through resistor to VBUS */} + + + + + {/* Connect filtering capacitors */} + + + + + +) +`} /> + +## Complete Circuit Schematic + +Here's the full schematic view showing all components and their connections: + + ( + + + + + + + + + + + + + + + + + + + +) +`} /> + +## Bill of Materials + +| Reference | Component | Value | Footprint | Notes | +|-----------|-----------|-------|-----------|-------| +| U1 | PD Trigger IC | FP28XX/CH224K/PD2001 | SOP-8 | USB PD controller | +| TB1 | Terminal Block | 2-pin 5mm | THT | Output connection | +| LED1 | Power LED | Green | 0805 | Power indicator | +| R1 | Resistor | 330Ω | 0603 | LED current limit | +| C1 | Capacitor | 10µF | 0603 | Input filter, 25V | +| C2 | Capacitor | 22µF | 0805 | Output filter, 25V | +| - | USB-C Connector | - | - | Right-angle THT or SMD | + +## PCB Layout Recommendations + +When laying out this board: + +1. **USB-C connector placement**: Position near the edge of the HAT for easy cable access +2. **Terminal block placement**: Keep opposite side for load connections +3. **Capacitor placement**: Place C1 close to IC VBUS pin, C2 near terminal block +4. **LED placement**: Position for visibility when HAT is installed +5. **Ground plane**: Use a solid ground plane under all components +6. **Trace widths**: Use 20mil traces for signal, 40-60mil for power paths +7. **Keep-out zones**: Follow USB-C connector manufacturer's keep-out recommendations + +## Programming Voltage Selection + +Some PD trigger ICs allow voltage selection via resistors or jumpers: + +### Voltage Selection Resistor Values + +| Target Voltage | Resistor Value | +|----------------|----------------| +| 5V | 10kΩ | +| 9V | 15kΩ | +| 12V | 20kΩ | +| 15kΩ | 27kΩ | +| 20V | 36kΩ | + +Check your specific IC's datasheet for exact resistor values and connection method. + +## Alternative: Programmable PD Controller + +For more flexibility, consider using a microcontroller-based PD solution: + +- **FUSB302**: I2C-based USB PD controller +- **CYPD3177**: Full-featured PD controller with USB-C authentication +- **ESP32-C3**: Combine PD control with wireless connectivity + +This allows dynamic voltage negotiation based on load requirements. + +## Testing Your PD Trigger HAT + +### Required Equipment + +- USB-C PD power supply (65W recommended) +- Digital multimeter +- Electronic load (optional, for load testing) + +### Testing Procedure + +1. **Visual inspection**: Check for cold solder joints, bridged pins +2. **Continuity test**: Verify no shorts between VBUS and GND +3. **No-load test**: Connect power supply, verify LED illuminates +4. **Voltage verification**: Measure output voltage with multimeter +5. **Load test**: Connect load, verify stable operation at rated current + +### Expected Results + +| Test | Expected Result | +|------|------------------| +| LED indicator | Illuminates when PD negotiation succeeds | +| Output voltage | Matches programmed/selected voltage (±5%) | +| Ripple/noise | <100mVpp at rated load | +| Thermal | Component temperature rise <30°C at rated load | + +## Extending the Design + +### Adding Voltage Display + +Add an OLED display to show current voltage and current: + +```tsx +// Add to circuit +import { SSD1306_OLED } from "@tscircuit/common" + + +``` + +### Adding Current Monitoring + +Include an INA219 sensor for power monitoring: + +```tsx +import { INA219_Sensor } from "@tscircuit/common" + + +``` + +### Adding Multiple Outputs + +Create a board with selectable voltage outputs using analog switches or relays. + +## Safety Considerations + +1. **Overcurrent protection**: Ensure your PD controller or downstream protection limits current +2. **Overvoltage protection**: Some controllers have built-in OVP; verify before use +3. **Thermal management**: High-current applications may require heatsinking +4. **Reverse polarity**: Add a reverse-polarity protection diode on output +5. **ESD protection**: Consider adding TVS diodes on USB-C connector pins + +## Conclusion + +You've now built a complete USB Power Delivery Trigger HAT that can: + +- Negotiate voltages from 5V to 20V with USB PD power supplies +- Provide clean, filtered power output +- Display status via LED indicator +- Interface with Raspberry Pi GPIO pins + +This project demonstrates key concepts in power supply design, USB protocols, and HAT development that apply to many other projects. + +## Next Steps + +- Add an ESP32 or other microcontroller for dynamic voltage control +- Implement voltage/current monitoring with a small display +- Design a more compact version using all SMD components +- Create an enclosure for the completed HAT +- Experiment with different PD power supplies and verify compatibility + +## Resources + +- [USB Power Delivery Specification](https://usb.org/document-library/usb-power-delivery) +- [USB Type-C Specification](https://usb.org/document-library/usb-type-cr-cable-and-connector-specification) +- [Raspberry Pi HAT Specification](https://github.com/raspberrypi/hats) +- [tscircuit Documentation](/docs/intro/overview)