Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Arduino.h>
- #include <U8g2lib.h>
- #include <Wire.h> //Arduino Nano; SDA = A4, SCL = A5
- //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //1.3 inch display (SH1106)
- U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ A5, /* data=*/ A4, /* reset=*/ U8X8_PIN_NONE); //0.96 inch display (SSD1306)
- float Current = 0; //4-20 mA (mapped)
- float rawADCValue = 0; //0-1023
- float ADCVoltage = 0; //0-5 V
- float pressure = 0; //0-250 bar (mapped)
- int ADC_Pin = A1;
- void setup()
- {
- Serial.begin(115200);
- u8g2.begin();
- u8g2.setFont(u8g2_font_inb24_mr);
- }
- void loop()
- {
- readADC();
- printLCD();
- }
- void readADC()
- {
- rawADCValue = 0; //Reset the value before summation
- for (int i = 0; i < 100; i++) //Do 100 readings
- {
- rawADCValue += analogRead(ADC_Pin);
- delay(5); //"settling time" for the ADC
- //Sum the results 100 times
- }
- ADCVoltage = (float)(rawADCValue / 100.0) * (4630 / 1023.0); //The average is converted into voltage (5000 mV = 5 V)
- //measure the real 5 V of your board and substitute the result (mine was 4630 mV)
- Serial.print("RAW: ");
- Serial.println((rawADCValue / 100.0));
- Serial.print("Voltage: ");
- Serial.println(ADCVoltage);
- //For 220 Ohm: 4 mA * 220 Ohm = 880 mV, 20 mA * 220 Ohm = 4400 mV
- //For 250 Ohm: 4 mA * 250 Ohm = 1000 mV, 20 mA * 250 Ohm = 5000 mV
- //Note: measure the 220 (or 250) resistor, and calculate the actual voltages
- Current = mapfloat(ADCVoltage, 880, 4400, 4, 20);
- // Voltage between 880-4400 mV is distributed as current 4-20 mA
- //2640 mV should be 12 mA equivalent
- Serial.print("Current: ");
- Serial.println(Current);
- pressure = mapfloat(Current, 4, 20, 0, 250);
- Serial.print("Pressure: ");
- Serial.println(pressure);
- //Current between 4-20 mA is distributed as pressure between 0-250 bar.
- //12 mA should be 125 bar equivalent
- }
- void printLCD()
- {
- u8g2.firstPage();
- do {
- u8g2.setCursor(0, 30);
- u8g2.print(ADCVoltage);
- u8g2.setCursor(0, 60);
- u8g2.print(Current);
- } while ( u8g2.nextPage() );
- }
- float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
- {
- return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
- }
Add Comment
Please, Sign In to add comment