CuriousScientist

OLED - Pressure dial -old

Sep 7th, 2021 (edited)
631
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Arduino.h>
  2. #include <U8g2lib.h>
  3. #include <Wire.h> //Arduino Nano; SDA = A4, SCL = A5
  4.  
  5. //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //1.3 inch display (SH1106)
  6. U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ A5, /* data=*/ A4, /* reset=*/ U8X8_PIN_NONE);   //0.96 inch display (SSD1306)
  7.  
  8.  
  9. float Current = 0; //4-20 mA (mapped)
  10. float rawADCValue = 0; //0-1023
  11. float ADCVoltage = 0; //0-5 V
  12. float pressure = 0; //0-250 bar (mapped)
  13. int ADC_Pin = A1;
  14.  
  15. void setup()
  16. {
  17.   Serial.begin(115200);
  18.  
  19.   u8g2.begin();    
  20.   u8g2.setFont(u8g2_font_inb24_mr);  
  21. }
  22.  
  23. void loop()
  24. {
  25.   readADC();
  26.   printLCD();
  27. }
  28.  
  29. void readADC()
  30. {
  31.   rawADCValue = 0; //Reset the value before summation
  32.  
  33.   for (int i = 0; i < 100; i++) //Do 100 readings
  34.   {
  35.     rawADCValue += analogRead(ADC_Pin);
  36.     delay(5); //"settling time" for the ADC
  37.     //Sum the results 100 times
  38.   }
  39.  
  40.   ADCVoltage = (float)(rawADCValue / 100.0) * (4630 / 1023.0); //The average is converted into voltage (5000 mV = 5 V)
  41.   //measure the real 5 V of your board and substitute the result (mine was 4630 mV)
  42.   Serial.print("RAW: ");
  43.   Serial.println((rawADCValue / 100.0));
  44.   Serial.print("Voltage: ");
  45.   Serial.println(ADCVoltage);
  46.  
  47.   //For 220 Ohm: 4 mA * 220 Ohm = 880 mV, 20 mA * 220 Ohm = 4400 mV
  48.   //For 250 Ohm: 4 mA * 250 Ohm = 1000 mV, 20 mA * 250 Ohm = 5000 mV
  49.   //Note: measure the 220 (or 250) resistor, and calculate the actual voltages
  50.   Current = mapfloat(ADCVoltage, 880, 4400, 4, 20);
  51.   // Voltage between 880-4400 mV is distributed as current 4-20 mA
  52.   //2640 mV should be 12 mA equivalent
  53.   Serial.print("Current: ");
  54.   Serial.println(Current);
  55.  
  56.   pressure = mapfloat(Current, 4, 20, 0, 250);
  57.   Serial.print("Pressure: ");
  58.   Serial.println(pressure);
  59.   //Current between 4-20 mA is distributed as pressure between 0-250 bar.
  60.   //12 mA should be 125 bar equivalent
  61. }
  62.  
  63. void printLCD()
  64. {
  65.   u8g2.firstPage();
  66.  
  67.   do {
  68.  
  69.    u8g2.setCursor(0, 30);
  70.    u8g2.print(ADCVoltage);
  71.    
  72.    u8g2.setCursor(0, 60);
  73.    u8g2.print(Current);
  74.    
  75.    } while ( u8g2.nextPage() );
  76.    
  77. }
  78.  
  79. float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
  80. {
  81.   return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
  82. }
Add Comment
Please, Sign In to add comment