Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

uploading varius code

some of my code and some is not my code, waht is not mine should have
info in comment
  • Loading branch information...
commit 5fc066bd46907b850a5de822a8dbb99e6a795f19 1 parent 20b5089
lestofante authored
Showing with 38,042 additions and 13 deletions.
  1. +51 −0 AsincWritePPMChannel/AsincWritePPMChannel.pde
  2. +220 −0 BMP085/BMP085.pde
  3. +232 −0 ClassPPM/ClassPPM.pde
  4. +81 −0 ClassPPM/InputPin.cpp
  5. +22 −0 ClassPPM/InputPin.cpp~
  6. +15 −0 ClassPPM/InputPin.h
  7. +16 −0 ClassPPM/InputPin.h~
  8. +53 −0 ControlloMotoriSeriale/ControlloMotoriSeriale.pde
  9. +74 −0 ControlloMotoriSeriale/ReadSerial.cpp
  10. +22 −0 ControlloMotoriSeriale/ReadSerial.h
  11. +37 −0 DCMtest1/DCMtest1.pde
  12. +102 −0 DCMtest1/IMU.cpp
  13. +37 −0 DCMtest1/IMU.h
  14. +38 −0 DS18B20/DS18B20.ino
  15. +738 −0 DS18B20/DallasTemperature.cpp
  16. +242 −0 DS18B20/DallasTemperature.h
  17. +527 −0 DS18B20/OneWire.cpp
  18. +192 −0 DS18B20/OneWire.h
  19. +47 −0 DistanzaSeriale/DistanzaSeriale.pde
  20. +127 −0 FreqCounter/FreqCounter.cpp
  21. +127 −0 FreqCounter/FreqCounter.cpp~
  22. +36 −0 FreqCounter/FreqCounter.h
  23. +45 −0 FreqCounter/FreqCounter.pde
  24. +166 −0 GPS_test/GPS_test.ino
  25. +251 −0 HMC5883L/HMC5883L.ino
  26. +73 −0 HeartSensor/HeartSensor.pde
  27. +22 −0 HeartSensor2/HeartSensor2.pde
  28. +14 −0 IMU9DOFtest/IMU9DOFtest.ino
  29. +8 −0 IMU9DOFtest/ITG3200.cpp
  30. +16 −0 IMU9DOFtest/ITG3200.h
  31. +82 −0 ITG3200/ITG3200.ino
  32. +132 −0 ITG3200test/ITG3200.cpp
  33. +90 −0 ITG3200test/ITG3200.h
  34. +11 −0 ITG3200test/ITG3200test.pde
  35. +112 −0 ITG3200test/twi.c
  36. +14 −0 ITG3200test/twi.h
  37. +12 −0 LedDistanzaAnalogica/LedDistanzaAnalogica.pde
  38. +84 −0 LedRadar/LedRadar.pde
  39. +34 −0 Lettore/Lettore.pde
  40. +148 −0 MotionPlusTest1/MotionPlusTest1.pde
  41. +27 −0 NumeroLettureAlSecondoDigitali/NumeroLettureAlSecondoDigitali.pde
  42. +312 −0 NunAndMotionTest1/NunAndMotionTest1.pde
  43. +217 −0 NunAndMotionTest2/NunAndMotionTest2.pde
  44. +309 −0 NunAndMotionTest3/NunAndMotionTest3.pde
  45. +35 −0 NunAndMotionTest4/NunAndMotionTest4.pde
  46. +408 −0 NunAndMotionTest4/WMPandNun.cpp
  47. +25 −0 NunAndMotionTest4/WMPandNun.h
  48. +173 −0 QuadricotteroCompleto/LogicaMotori/EngineMindPID.cpp
  49. +173 −0 QuadricotteroCompleto/LogicaMotori/EngineMindPID.cpp~
  50. +29 −0 QuadricotteroCompleto/LogicaMotori/EngineMindPID.h
  51. +26 −0 QuadricotteroCompleto/LogicaMotori/EngineMindPID.h~
  52. +60 −0 QuadricotteroCompleto/LogicaMotori/PID/PID.cpp
  53. +60 −0 QuadricotteroCompleto/LogicaMotori/PID/PID.cpp~
  54. +19 −0 QuadricotteroCompleto/LogicaMotori/PID/PID.h
  55. +397 −0 QuadricotteroCompleto/QuadricotteroCompleto.pde
  56. +101 −0 QuadricotteroCompleto/RX/InputPin.cpp
  57. +101 −0 QuadricotteroCompleto/RX/InputPin.cpp~
  58. +17 −0 QuadricotteroCompleto/RX/InputPin.h
  59. +11 −0 QuadricotteroCompleto/Utils/Utils.cpp
  60. +11 −0 QuadricotteroCompleto/Utils/Utils.cpp~
  61. +15 −0 QuadricotteroCompleto/Utils/Utils.h
  62. +15 −0 QuadricotteroCompleto/Utils/Utils.h~
  63. +103 −0 QuadricotteroCompleto/stabilization/IMU/IMULast.cpp
  64. +103 −0 QuadricotteroCompleto/stabilization/IMU/IMULast.cpp~
  65. +15 −0 QuadricotteroCompleto/stabilization/IMU/IMULast.h
  66. +15 −0 QuadricotteroCompleto/stabilization/IMU/IMULast.h~
  67. +138 −0 QuadricotteroCompleto/stabilization/IMU/sensor/Fastwire.cpp
  68. +41 −0 QuadricotteroCompleto/stabilization/IMU/sensor/Fastwire.h
  69. +293 −0 QuadricotteroCompleto/stabilization/IMU/sensor/WMP.cpp
  70. +293 −0 QuadricotteroCompleto/stabilization/IMU/sensor/WMP.cpp~
  71. +26 −0 QuadricotteroCompleto/stabilization/IMU/sensor/WMP.h
  72. +26 −0 QuadricotteroCompleto/stabilization/IMU/sensor/WMP.h~
  73. +416 −0 QuadricotteroCompleto/stabilization/Stabilizzazione.cpp
  74. +416 −0 QuadricotteroCompleto/stabilization/Stabilizzazione.cpp~
  75. +52 −0 QuadricotteroCompleto/stabilization/Stabilizzazione.h
  76. +51 −0 QuadricotteroCompleto/stabilization/Stabilizzazione.h~
  77. +141 −0 RFIDread/RFIDread.pde
  78. +45 −0 RFIDtest2/RFIDtest2.pde
  79. +23 −0 RTCleo72/RTCleo72.pde
  80. +217 −0 RTCleo72/swRTC.cpp
  81. +37 −0 RTCleo72/swRTC.h
  82. +35 −0 ReadPPMChannel/ReadPPMChannel.pde
  83. +136 −0 SQRTtest/SQRTtest.pde
  84. +319 −0 TestERER/ERER.cpp
  85. +15 −0 TestERER/ERER.h
  86. +59 −0 TestERER/TestERER.pde
  87. +35 −0 TestGiro3/Giroscopio.cpp
  88. +35 −0 TestGiro3/Giroscopio.cpp~
  89. +16 −0 TestGiro3/Giroscopio.h
  90. +60 −0 TestGiro3/TestGiro3.pde
  91. +87 −0 TestGyro4/TestGyro4.pde
  92. +90 −0 TestInterrupt/TestInterrupt.pde
  93. +19 −0 TestMioProtocolloComunicazione/LestoCommReader.cpp
  94. +18 −0 TestMioProtocolloComunicazione/LestoCommReader.h
  95. +48 −0 TestMioProtocolloComunicazione/LestoCommWriter.cpp
  96. +14 −0 TestMioProtocolloComunicazione/LestoCommWriter.h
  97. +32 −0 TestMioProtocolloComunicazione/TestMioProtocolloComunicazione.pde
  98. +44 −0 TestNumeroALettera/TestNumeroALettera.pde
  99. +51 −0 TestOverflowMicros/TestOverflowMicros.pde
  100. +44 −0 TestPotenzaMotori/TestPotenzaMotori.pde
  101. +301 −0 TestReattivitaMotore/NunchukFarlocco.cpp
  102. +22 −0 TestReattivitaMotore/NunchukFarlocco.h
  103. +131 −0 TestReattivitaMotore/TestReattivitaMotore.pde
  104. +26 −0 TestSerioNunchukGyro/Giroscopio.cpp
  105. +16 −0 TestSerioNunchukGyro/Giroscopio.h
  106. +207 −0 TestSerioNunchukGyro/IMU.cpp
  107. +37 −0 TestSerioNunchukGyro/IMU.h
  108. +80 −0 TestSerioNunchukGyro/InputPin.cpp
  109. +15 −0 TestSerioNunchukGyro/InputPin.h
  110. +13 −0 TestSerioNunchukGyro/Motore.cpp
  111. +14 −0 TestSerioNunchukGyro/Motore.h
  112. +219 −0 TestSerioNunchukGyro/NunchukFarlocco.cpp
  113. +20 −0 TestSerioNunchukGyro/NunchukFarlocco.h
  114. +17 −0 TestSerioNunchukGyro/PID.cpp
  115. +14 −0 TestSerioNunchukGyro/PID.h
  116. +329 −0 TestSerioNunchukGyro/TestSerioNunchukGyro.pde
  117. +138 −0 TestWMP/Fastwire.cpp
  118. +41 −0 TestWMP/Fastwire.h
  119. +236 −0 TestWMP/Stabilizzazione.cpp
  120. +53 −0 TestWMP/Stabilizzazione.h
  121. +98 −0 TestWMP/TestWMP.pde
  122. +295 −0 TestWMP/WMP.cpp
  123. +26 −0 TestWMP/WMP.h
  124. +84 −0 TsteAnalogico/TsteAnalogico.pde
  125. +48 −0 WritePPMChannel/WritePPMChannel.pde
  126. +1,102 −0 XXcontrol/XXcontrol.pde
  127. +53 −0 XXcontrol/io_cfg.h
  128. +62 −0 XXcontrol/typedefs.h
  129. +44 −0 XbeeTest/XbeeTest.pde
  130. +1 −1  asincI2C/asincI2C.ino
  131. +23 −4 asincI2Ctest2/asincI2Ctest2.ino
  132. +8 −8 asincI2Ctest2_asinc/asincI2Ctest2_asinc.ino
  133. +225 −0 bigNumberTest/BigNumber.cpp
  134. +110 −0 bigNumberTest/BigNumber.h
  135. +225 −0 bigNumberTest/BigNumber/BigNumber.cpp
  136. +110 −0 bigNumberTest/BigNumber/BigNumber.h
  137. +24 −0 bigNumberTest/BigNumber/bcconfig.h
  138. BIN  bigNumberTest/BigNumber/examples/.DS_Store
  139. +40 −0 bigNumberTest/BigNumber/examples/Calculate_E/Calculate_E.pde
  140. +31 −0 bigNumberTest/BigNumber/examples/Factorials/Factorials.pde
  141. +28 −0 bigNumberTest/BigNumber/examples/Multiplication/Multiplication.pde
  142. +57 −0 bigNumberTest/BigNumber/examples/Natural_Log/Natural_Log.pde
  143. +51 −0 bigNumberTest/BigNumber/examples/Power_of_E/Power_of_E.pde
  144. +47 −0 bigNumberTest/BigNumber/examples/Powers/Powers.pde
  145. +51 −0 bigNumberTest/BigNumber/examples/Sine/Sine.pde
  146. +339 −0 bigNumberTest/BigNumber/gpl.txt
  147. +11 −0 bigNumberTest/BigNumber/keywords.txt
  148. +1,597 −0 bigNumberTest/BigNumber/number.c
  149. +161 −0 bigNumberTest/BigNumber/number.h
  150. +24 −0 bigNumberTest/bcconfig.h
  151. +459 −0 bigNumberTest/bigNumberTest.ino
  152. +1,626 −0 bigNumberTest/number.c
  153. +160 −0 bigNumberTest/number.h
  154. +23 −0 cellLoad/cellLoad.pde
  155. +25 −0 dialogoLed/dialogoLed.pde
  156. +362 −0 fixedPointMath/fixedPointMath.pde
  157. +362 −0 fixedPointMath/fixedptc.h
  158. +72 −0 i2cscanner/i2cScanner.pde
  159. +75 −0 i2cscanner/i2cscanner.ino
  160. +218 −0 interruptOK/interruptOK.pde
  161. +48 −0 invioSeriale/invioSeriale.pde
  162. +48 −0 ledFastDistanza/ledFastDistanza.pde
  163. +112 −0 max6675test/MAX6675.cpp
  164. +25 −0 max6675test/MAX6675.h
  165. +71 −0 max6675test/max6675test.ino
  166. +138 −0 newQuad/Fastwire.cpp
  167. +44 −0 newQuad/Fastwire.h
  168. +7 −0 newQuad/newQuad.pde
  169. +108 −0 oldADXL345/oldADXL345.pde
  170. +1 −0  oldITG3200/ITG3200.pde
  171. +138 −0 oldTestImu/Fastwire.cpp
  172. +41 −0 oldTestImu/Fastwire.h
  173. +31 −0 oldTestImu/Giroscopio.cpp
  174. +19 −0 oldTestImu/Giroscopio.h
  175. +62 −0 oldTestImu/IMU.cpp
  176. +13 −0 oldTestImu/IMU.h
  177. +92 −0 oldTestImu/IMULast.cpp
  178. +15 −0 oldTestImu/IMULast.h
  179. +292 −0 oldTestImu/NunchukFarlocco.cpp
  180. +22 −0 oldTestImu/NunchukFarlocco.h
  181. +1 −0  oldTestImu/SensorInput.cpp
  182. +11 −0 oldTestImu/SensorInput.h
  183. +278 −0 oldTestImu/Stabilizzazione.cpp
  184. +217 −0 oldTestImu/Stabilizzazione.cpp~
  185. +71 −0 oldTestImu/Stabilizzazione.h
  186. +134 −0 oldTestImu/TestImu.pde
  187. +187 −0 oldTestImu/WMP.cpp
  188. +205 −0 oldTestImu/WMP.cpp~
  189. +22 −0 oldTestImu/WMP.h
  190. +25 −0 optiLoader/optiLoader.h
  191. +861 −0 optiLoader/optiLoader.pde
  192. +861 −0 optiLoader_pde/optiLoader_pde.pde
  193. +121 −0 oveflowTestSerio/oveflowTestSerio.ino
  194. +16 −0 seconds/seconds.ino
  195. +169 −0 swRTClesto/core_build_options.h
  196. +349 −0 swRTClesto/swRTC.cpp
  197. +54 −0 swRTClesto/swRTC.h
  198. +34 −0 swRTClesto/swRTClesto.pde
  199. +125 −0 test/AF_SDLog.cpp
  200. +36 −0 test/AF_SDLog.h
  201. +1,608 −0 test/fat16.cpp
  202. +175 −0 test/fat16.h
  203. +84 −0 test/fat16_config.h
  204. +163 −0 test/partition.cpp
  205. +201 −0 test/partition.h
  206. +35 −0 test/partition_config.h
  207. +890 −0 test/sd_raw.cpp
  208. +139 −0 test/sd_raw.h
  209. +121 −0 test/sd_raw_config.h
  210. +44 −0 test/sd_reader_config.h
  211. +390 −0 test/test.pde
  212. +18 −0 test/util.cpp
  213. +8 −0 test/util.h
  214. +44 −0 test2Gyro/test2Gyro.pde
  215. +178 −0 testADXL/ADXL345.cpp
  216. +84 −0 testADXL/ADXL345.h
  217. +40 −0 testADXL/testADXL.ino
  218. +15 −0 testAccelerometroAnalogico/testAccelerometroAnalogico.pde
  219. +1,581 −0 testDouble/avr_f64.c
  220. +243 −0 testDouble/avr_f64.h
  221. +126 −0 testDouble/testDouble.ino
  222. +62 −0 testFastSqrt/testFastSqrt.pde
  223. +60 −0 testGiro/Gyro.cpp
  224. +12 −0 testGiro/Gyro.h
  225. +21 −0 testGiro/Sensor.h
  226. +5 −0 testGiro/Struct.h
  227. +19 −0 testGiro/testGiro.ino
  228. +223 −0 testI2Cspeed/I2cMaster.cpp
  229. +129 −0 testI2Cspeed/I2cMaster.h
  230. +64 −0 testI2Cspeed/I2cMaster/examples/i2cScanAddress/i2cScanAddress.pde
  231. +38 −0 testI2Cspeed/I2cMaster/examples/i2cScopeTest/i2cScopeTest.pde
  232. +344 −0 testI2Cspeed/I2cMaster/examples/softDS1307/softDS1307.pde
  233. +60 −0 testI2Cspeed/TwiMap.h
  234. +33 −0 testI2Cspeed/keywords.txt
  235. +711 −0 testI2Cspeed/old/I2C.cpp
  236. +135 −0 testI2Cspeed/old/I2C.h
  237. +138 −0 testI2Cspeed/testI2Cspeed.ino
  238. +119 −0 testIMU/ADXL345.cpp
  239. +24 −0 testIMU/ADXL345.h
  240. +201 −0 testIMU/DCM.cpp
  241. +38 −0 testIMU/DCM.h
  242. +187 −0 testIMU/HMC5883L.cpp
  243. +23 −0 testIMU/HMC5883L.h
  244. +102 −0 testIMU/ITG3200.cpp
  245. +24 −0 testIMU/ITG3200.h
  246. +314 −0 testIMU/MahonyAHRS.cpp
  247. +45 −0 testIMU/MahonyAHRS.h
  248. +47 −0 testIMU/MemoryFree.cpp
  249. +20 −0 testIMU/MemoryFree.h
  250. +17 −0 testIMU/Sensor.h
  251. +16 −0 testIMU/SensorDataStruct.h
  252. +274 −0 testIMU/testIMU.ino
  253. +35 −0 testIR/testIR.pde
  254. +68 −0 testIR2/testIR2.pde
  255. +129 −0 testITG/ITG3200.cpp
  256. +129 −0 testITG/ITG3200.h
  257. +60 −0 testITG/main.h
  258. +1 −0  testITG/testITG.ino
  259. +112 −0 testITG/twi.c
  260. +14 −0 testITG/twi.h
  261. +260 −0 testNunchuck4/NunchukFarlocco.cpp
  262. +22 −0 testNunchuck4/NunchukFarlocco.h
  263. +62 −0 testNunchuck4/testNunchuck4.pde
  264. +260 −0 testNunchuckSlaveI2C/NunchukFarlocco.cpp
  265. +22 −0 testNunchuckSlaveI2C/NunchukFarlocco.h
  266. +98 −0 testNunchuckSlaveI2C/testNunchuckSlaveI2C.pde
  267. +241 −0 testNunchuk2/testNunchuk2.pde
  268. +357 −0 testNunchuk3/testNunchuk3.pde
  269. +32 −0 testOverflow/testOverflow.ino
  270. +9 −0 testPotenziometro/testPotenziometro.pde
  271. +60 −0 testTimerInterrupt/testTimerInterrupt.pde
  272. +213 −0 testnunchuk/WiiChuck.h
  273. +1 −0  testnunchuk/WiiChuck.h~
  274. +47 −0 testnunchuk/testnunchuk.pde
  275. +178 −0 vecchi file/FatswireDebig.cpp
  276. +35 −0 vecchi file/Giroscopio.cpp
  277. +16 −0 vecchi file/Giroscopio.h
Sorry, we could not display the entire diff because it was too big.
51 AsincWritePPMChannel/AsincWritePPMChannel.pde
View
@@ -0,0 +1,51 @@
+//data HIGH goes from 900 to 1700
+//data LOW go to 19000
+
+#define MINSERVO 50 //value to test
+#define MAXSERVO 1024 //value to test
+#define SERVOLOWSIGNALDURATION 2000
+
+unsigned long duration1=MINSERVO;
+unsigned long duration2=19000;
+
+struct PPMPIN{
+ byte pin;
+ boolean pinstate = false;
+ unsigned long lastChange;
+ byte
+}
+
+struct PPMPIN test;
+
+void setup()
+{
+ Serial.begin(9600);
+ pinMode(PINOUTPUT, OUTPUT);
+ test.pin=2;
+ test.lastChange=micros();
+}
+
+void loop()
+{
+ updatePPM();
+ digitalWrite(PINOUTPUT, HIGH);
+ delayMicroseconds(duration1);
+ digitalWrite(PINOUTPUT, LOW);
+ delayMicroseconds(1000);
+
+ duration1+=10;
+ if (duration1>MAXSERVO){
+ duration1=MINSERVO;
+ }
+ Serial.print("Moving to: ");
+ Serial.println(duration1);
+}
+
+void updatePPM(){
+ if (micros()-test.lastChange < SERVOLOWSIGNALDURATION){
+ test.lastChange=micros();
+
+ }
+
+}
+
220 BMP085/BMP085.pde
View
@@ -0,0 +1,220 @@
+/* BMP085 Extended Example Code
+ by: Jim Lindblom
+ SparkFun Electronics
+ date: 1/18/11
+ license: CC BY-SA v3.0 - http://creativecommons.org/licenses/by-sa/3.0/
+
+ Get pressure and temperature from the BMP085 and calculate altitude.
+ Serial.print it out at 9600 baud to serial monitor.
+
+ Update (7/19/11): I've heard folks may be encountering issues
+ with this code, who're running an Arduino at 8MHz. If you're
+ using an Arduino Pro 3.3V/8MHz, or the like, you may need to
+ increase some of the delays in the bmp085ReadUP and
+ bmp085ReadUT functions.
+*/
+
+#include <Wire.h>
+
+#define BMP085_ADDRESS 0x77 // I2C address of BMP085
+
+const unsigned char OSS = 0; // Oversampling Setting
+
+// Calibration values
+int ac1;
+int ac2;
+int ac3;
+unsigned int ac4;
+unsigned int ac5;
+unsigned int ac6;
+int b1;
+int b2;
+int mb;
+int mc;
+int md;
+
+// b5 is calculated in bmp085GetTemperature(...), this variable is also used in bmp085GetPressure(...)
+// so ...Temperature(...) must be called before ...Pressure(...).
+long b5;
+
+short temperature;
+long pressure;
+
+void setup()
+{
+ Serial.begin(9600);
+ delay(2000);
+ Wire.begin();
+ bmp085Calibration();
+}
+
+void loop()
+{
+ temperature = bmp085GetTemperature(bmp085ReadUT());
+ pressure = bmp085GetPressure(bmp085ReadUP());
+ Serial.print("Temperature: ");
+ Serial.print(temperature, DEC);
+ Serial.println(" *0.1 deg C");
+ Serial.print("Pressure: ");
+ Serial.print(pressure, DEC);
+ Serial.println(" Pa");
+ Serial.println();
+ delay(1000);
+}
+
+// Stores all of the bmp085's calibration values into global variables
+// Calibration values are required to calculate temp and pressure
+// This function should be called at the beginning of the program
+void bmp085Calibration()
+{
+ ac1 = bmp085ReadInt(0xAA);
+ ac2 = bmp085ReadInt(0xAC);
+ ac3 = bmp085ReadInt(0xAE);
+ ac4 = bmp085ReadInt(0xB0);
+ ac5 = bmp085ReadInt(0xB2);
+ ac6 = bmp085ReadInt(0xB4);
+ b1 = bmp085ReadInt(0xB6);
+ b2 = bmp085ReadInt(0xB8);
+ mb = bmp085ReadInt(0xBA);
+ mc = bmp085ReadInt(0xBC);
+ md = bmp085ReadInt(0xBE);
+}
+
+// Calculate temperature given ut.
+// Value returned will be in units of 0.1 deg C
+short bmp085GetTemperature(unsigned int ut)
+{
+ long x1, x2;
+
+ x1 = (((long)ut - (long)ac6)*(long)ac5) >> 15;
+ x2 = ((long)mc << 11)/(x1 + md);
+ b5 = x1 + x2;
+
+ return ((b5 + 8)>>4);
+}
+
+// Calculate pressure given up
+// calibration values must be known
+// b5 is also required so bmp085GetTemperature(...) must be called first.
+// Value returned will be pressure in units of Pa.
+long bmp085GetPressure(unsigned long up)
+{
+ long x1, x2, x3, b3, b6, p;
+ unsigned long b4, b7;
+
+ b6 = b5 - 4000;
+ // Calculate B3
+ x1 = (b2 * (b6 * b6)>>12)>>11;
+ x2 = (ac2 * b6)>>11;
+ x3 = x1 + x2;
+ b3 = (((((long)ac1)*4 + x3)<<OSS) + 2)>>2;
+
+ // Calculate B4
+ x1 = (ac3 * b6)>>13;
+ x2 = (b1 * ((b6 * b6)>>12))>>16;
+ x3 = ((x1 + x2) + 2)>>2;
+ b4 = (ac4 * (unsigned long)(x3 + 32768))>>15;
+
+ b7 = ((unsigned long)(up - b3) * (50000>>OSS));
+ if (b7 < 0x80000000)
+ p = (b7<<1)/b4;
+ else
+ p = (b7/b4)<<1;
+
+ x1 = (p>>8) * (p>>8);
+ x1 = (x1 * 3038)>>16;
+ x2 = (-7357 * p)>>16;
+ p += (x1 + x2 + 3791)>>4;
+
+ return p;
+}
+
+// Read 1 byte from the BMP085 at 'address'
+char bmp085Read(unsigned char address)
+{
+ unsigned char data;
+
+ Wire.beginTransmission(BMP085_ADDRESS);
+ Wire.send(address);
+ Wire.endTransmission();
+
+ Wire.requestFrom(BMP085_ADDRESS, 1);
+ while(!Wire.available())
+ ;
+
+ return Wire.receive();
+}
+
+// Read 2 bytes from the BMP085
+// First byte will be from 'address'
+// Second byte will be from 'address'+1
+int bmp085ReadInt(unsigned char address)
+{
+ unsigned char msb, lsb;
+
+ Wire.beginTransmission(BMP085_ADDRESS);
+ Wire.send(address);
+ Wire.endTransmission();
+
+ Wire.requestFrom(BMP085_ADDRESS, 2);
+ while(Wire.available()<2)
+ ;
+ msb = Wire.receive();
+ lsb = Wire.receive();
+
+ return (int) msb<<8 | lsb;
+}
+
+// Read the uncompensated temperature value
+unsigned int bmp085ReadUT()
+{
+ unsigned int ut;
+
+ // Write 0x2E into Register 0xF4
+ // This requests a temperature reading
+ Wire.beginTransmission(BMP085_ADDRESS);
+ Wire.send(0xF4);
+ Wire.send(0x2E);
+ Wire.endTransmission();
+
+ // Wait at least 4.5ms
+ delay(5);
+
+ // Read two bytes from registers 0xF6 and 0xF7
+ ut = bmp085ReadInt(0xF6);
+ return ut;
+}
+
+// Read the uncompensated pressure value
+unsigned long bmp085ReadUP()
+{
+ unsigned char msb, lsb, xlsb;
+ unsigned long up = 0;
+
+ // Write 0x34+(OSS<<6) into register 0xF4
+ // Request a pressure reading w/ oversampling setting
+ Wire.beginTransmission(BMP085_ADDRESS);
+ Wire.send(0xF4);
+ Wire.send(0x34 + (OSS<<6));
+ Wire.endTransmission();
+
+ // Wait for conversion, delay time dependent on OSS
+ delay(2 + (3<<OSS));
+
+ // Read register 0xF6 (MSB), 0xF7 (LSB), and 0xF8 (XLSB)
+ Wire.beginTransmission(BMP085_ADDRESS);
+ Wire.send(0xF6);
+ Wire.endTransmission();
+ Wire.requestFrom(BMP085_ADDRESS, 3);
+
+ // Wait for data to become available
+ while(Wire.available() < 3)
+ ;
+ msb = Wire.receive();
+ lsb = Wire.receive();
+ xlsb = Wire.receive();
+
+ up = (((unsigned long) msb << 16) | ((unsigned long) lsb << 8) | (unsigned long) xlsb) >> (8-OSS);
+
+ return up;
+}
232 ClassPPM/ClassPPM.pde
View
@@ -0,0 +1,232 @@
+#include "InputPin.h"
+
+#define MIN_RADIO_VALUE 900
+#define MAX_RADIO_VALUE 1900
+
+
+/*
+pin3 = motor0
+pin9 = motor1
+pin10 = motor2
+pin11 = motor3
+
+^up
+ motor0
+motor1 + motor2
+ motor3
+
+
+*/
+
+//void setMid();
+
+unsigned long time;
+unsigned long midChannel[4];
+long motorPower[4];
+
+InputPin inputs;
+
+unsigned long lastInputChannelValue[4];
+
+void setup(){
+ Serial.begin(57600);
+ time = micros();
+
+ for (int i=0; i < 4; i++){
+ lastInputChannelValue[i]=0;
+ }
+ setMid();
+}
+
+void setMid(){
+ //calculate the mid of the RX
+ pinMode(13, OUTPUT);
+ digitalWrite(13, HIGH);
+ for (int a=0; a < 100;a++){
+ while ( !inputs.getAndSetFalseHasChanged() ) {
+ //wait until new data is readed
+ }
+ if (a==0){
+ midChannel[0]=inputs.getDuration(0);
+ midChannel[1]=inputs.getDuration(1);
+ midChannel[2]=inputs.getDuration(2);
+ midChannel[3]=inputs.getDuration(3);
+ }else{
+ midChannel[0]=( midChannel[0]+inputs.getDuration(0) )/2;
+ midChannel[1]=( midChannel[1]+inputs.getDuration(1) )/2;
+ midChannel[2]=( midChannel[2]+inputs.getDuration(2) )/2;
+ midChannel[3]=( midChannel[3]+inputs.getDuration(3) )/2;
+ }
+ }
+
+ digitalWrite(13, LOW);
+}
+
+
+void loop(){
+
+ computeInputs();
+
+ calculateLoopDuraton();
+
+}
+
+unsigned long desiredMotorPower=MIN_RADIO_VALUE;
+
+int volte=0;
+unsigned long midTime=0;
+boolean led = false;
+void calculateLoopDuraton(){
+
+ if (midTime!=0)
+ midTime = (midTime+micros() - time)/2;
+ else
+ midTime = (micros() - time);
+
+ time = micros();
+ volte++;
+ if (volte>=15000){
+ digitalWrite(13, led);
+ led = !led;
+ Serial.print("time 1 loop in micros:");
+ Serial.println(midTime);
+// Serial.println(F_CPU);
+ volte = 0;
+
+ Serial.println("input:");
+ for (int i =0; i < 4; i++){
+ Serial.print(i);
+ Serial.print(":");
+ Serial.println( inputs.getDuration(i) );
+ }
+ Serial.print("Mid0:");
+ Serial.println(midChannel[0] );
+ Serial.print("Mid1:");
+ Serial.println( midChannel[1] );
+ Serial.print("Mid2:");
+ Serial.println( midChannel[2] );
+ Serial.print("Mid3:");
+ Serial.println( midChannel[3] );
+
+ Serial.print("DesiredPower:");
+ Serial.println( desiredMotorPower );
+
+ Serial.print("Mot0:");
+ Serial.println( motorPower[0] );
+
+ Serial.print("Mot1:");
+ Serial.println( motorPower[1] );
+
+ Serial.print("Mot2:");
+ Serial.println( motorPower[2] );
+
+ Serial.print("Mot3:");
+ Serial.println( motorPower[3] );
+
+ }
+
+}
+
+
+int ROLL_PITCH_YAW_WEIGHT = 4;
+int volteErrSignalNotInRange=0;
+int volteErrSignalLost=0;
+int MAXDIFF=20;
+int diff;
+byte cont;
+
+void computeInputs(){
+ /*
+ desiredMotorPower = inputs.getDuration(0);
+ diff=false;
+ for (int cont=0; cont < 4; cont++){
+ motorPower[cont] = map(desiredMotorPower, 0, MAX_RADIO_VALUE, 0, 220);
+ }
+ analogWrite( 3, motorPower[0] );
+ analogWrite( 9, motorPower[1] );
+ analogWrite( 10, motorPower[2] );
+ analogWrite( 11, motorPower[3] );
+ */
+ desiredMotorPower = inputs.getDuration(0);
+ diff=0;
+
+ if ( inputs.getAndSetFalseHasChanged() ){
+ for (cont = 0; cont < 4; cont++){
+ diff+=inputs.getDuration(cont)-lastInputChannelValue[cont];
+ }
+ if (abs(diff)>MAXDIFF){ //if there is enought difference
+ volteErrSignalLost=0;
+ if ( (desiredMotorPower >= MIN_RADIO_VALUE) && (desiredMotorPower <= MAX_RADIO_VALUE) ){ //if engine input is valid
+ volteErrSignalNotInRange=0;
+ long a = ( (long)inputs.getDuration(1) -(long)midChannel[1] )/ROLL_PITCH_YAW_WEIGHT; //PITCH
+//Serial.print("a:");
+//Serial.println(a);
+
+ long b = ( (long)inputs.getDuration(2) -(long)midChannel[2] )/ROLL_PITCH_YAW_WEIGHT; //ROLL
+//Serial.print("b:");
+//Serial.println(b);
+
+ long c = ( (long)inputs.getDuration(3) -(long)midChannel[3] )/ROLL_PITCH_YAW_WEIGHT; //YAW
+//Serial.print("c:");
+//Serial.println(c);
+
+ motorPower[0] = constrain( map(desiredMotorPower+a+c, 0, MAX_RADIO_VALUE, 0, 220), 0, 250);
+ analogWrite( 3, motorPower[0] );
+
+ motorPower[1] = constrain( map(desiredMotorPower-b-c, 0, MAX_RADIO_VALUE, 0, 220), 0, 250);
+ analogWrite( 9, motorPower[1] );
+
+ motorPower[2] = constrain( map(desiredMotorPower+b-c, 0, MAX_RADIO_VALUE, 0, 220), 0, 250);
+ analogWrite( 10, motorPower[2] );
+
+ motorPower[3] = constrain( map(desiredMotorPower-a+c, 0, MAX_RADIO_VALUE, 0, 220), 0, 250);
+ analogWrite( 11, motorPower[3] );
+
+ for (cont = 0; cont < 4; cont++){
+ lastInputChannelValue[cont]=inputs.getDuration(cont);
+ }
+ }else{
+ if (volteErrSignalNotInRange>1){
+ digitalWrite(13, HIGH);
+ Serial.println("Error, radio signal not in range!");
+ //slowly turn down engine
+ if (motorPower[0]>0)
+ motorPower[0]--;
+ if (motorPower[1]>0)
+ motorPower[1]--;
+ if (motorPower[2]>0)
+ motorPower[2]--;
+ if (motorPower[3]>0)
+ motorPower[3]--;
+ analogWrite( 3, motorPower[0] );
+ analogWrite( 9, motorPower[1] );
+ analogWrite( 10, motorPower[2] );
+ analogWrite( 11, motorPower[3] );
+ }else{
+ volteErrSignalNotInRange++;
+ }
+ }
+ }
+ }else{
+ if (volteErrSignalLost>36000){
+ digitalWrite(13, HIGH);
+ Serial.println("Error, radio signal lost!");
+ //slowly turn down engine
+ if (motorPower[0]>0)
+ motorPower[0]--;
+ if (motorPower[1]>0)
+ motorPower[1]--;
+ if (motorPower[2]>0)
+ motorPower[2]--;
+ if (motorPower[3]>0)
+ motorPower[3]--;
+ analogWrite( 3, motorPower[0] );
+ analogWrite( 9, motorPower[1] );
+ analogWrite( 10, motorPower[2] );
+ analogWrite( 11, motorPower[3] );
+ }else{
+ volteErrSignalLost++;
+ }
+ }
+
+}
81 ClassPPM/InputPin.cpp
View
@@ -0,0 +1,81 @@
+#include "InputPin.h"
+
+/*
+Let You read digital pin 2,4,5,6,7
+based on BIRONPILOTV59, tnx to ciskje
+*/
+
+#define MAXUNSIGNEDLONGCVALUE 4294967295
+#define MASKPCINT0 (1<<2)
+#define MASKPCINT1 (1<<4)
+#define MASKPCINT2 (1<<5)
+#define MASKPCINT3 (1<<6)
+
+volatile byte _oldbit, _newbit, _changed;
+
+InputPin::InputPin(){
+ pinMode(2, INPUT); // 3 is used for esc
+ pinMode(4, INPUT);
+ pinMode(5, INPUT);
+ pinMode(6, INPUT);
+ // interrupt on pin change PCINT2
+ PCICR |= (1 << PCIE2);
+
+ PCMSK2 = (1 << PCINT18) | // pin2
+ (1 << PCINT20) | // pin4
+ (1 << PCINT21) | // pin5
+ (1 << PCINT22); // pin6
+
+ _oldbit=PIND;
+}
+
+//putted here because interrupt dosn't want it in .h
+unsigned long _startIn[4];
+volatile unsigned long _rawIn[4];
+unsigned long _time;
+
+
+ISR(PCINT2_vect) {
+ _time=micros();
+
+ _newbit=PIND;
+ _changed=_newbit^_oldbit;
+
+ if (_changed&MASKPCINT0){
+
+ if (_newbit&MASKPCINT0) {
+ _startIn[0]=_time;
+ }else{
+ _rawIn[0]=_time-_startIn[0];
+ }
+ }
+
+ if (_changed&MASKPCINT1)
+ if (_newbit&MASKPCINT1)
+ _startIn[1]=_time;
+ else
+ _rawIn[1]=_time-_startIn[1];
+
+ if (_changed&MASKPCINT2)
+ if (_newbit&MASKPCINT2)
+ _startIn[2]=_time;
+ else
+ _rawIn[2]=_time-_startIn[2];
+
+ if (_changed&MASKPCINT3)
+ if (_newbit&MASKPCINT3)
+ _startIn[3]=_time;
+ else
+ _rawIn[3]=_time-_startIn[3];
+ _oldbit=_newbit;
+// blockedRX=0;
+}
+
+int InputPin::getDuration(int i){
+ // Serial.print("ok:");
+// Serial.print(rawIn[i]);
+ // Serial.println(rawIn[0]);
+ // Serial.print("okIND2:");
+ //Serial.println(rawIn, BIN);
+ return _rawIn[i];
+}
22 ClassPPM/InputPin.cpp~
View
@@ -0,0 +1,22 @@
+#include "InputPin.h"
+
+InputPin(int pinNumber){
+ InputPin(pinNumber, false);
+}
+
+InputPin(int pinNumber, boolean startingSignal){
+ pin = pinNumber;
+ signal = startingSignal;
+ signalLenght=0;
+ signalStart = micros();
+}
+
+~InputPin(){
+}
+
+void update(){
+ if ( digitalRead(pin)!=signal ){
+ signal=!signal;
+ }
+
+}
15 ClassPPM/InputPin.h
View
@@ -0,0 +1,15 @@
+#ifndef InputPin_h
+#define InputPin_h
+
+
+#include "WProgram.h"
+
+class InputPin{
+
+ public:
+ InputPin();
+ int getDuration(int i);
+ int x, y, z;
+ private:
+};
+#endif
16 ClassPPM/InputPin.h~
View
@@ -0,0 +1,16 @@
+#ifndef InputPin_h
+#define InputPin_h
+
+
+#include "WProgram.h"
+
+class InputPin{
+
+ public:
+ InputPin();
+ getAndSetFalseHasChanged(); // send the initilization handshake
+ nunchuck_get_data();
+ int x, y, z;
+ private:
+};
+#endif
53 ControlloMotoriSeriale/ControlloMotoriSeriale.pde
View
@@ -0,0 +1,53 @@
+#include <Servo.h>
+#include "ReadSerial.h"
+
+#define motore1PWMPin 3
+#define motore2PWMPin 9
+#define motore3PWMPin 10
+#define motore4PWMPin 11
+
+Servo motori[4]={Servo(), Servo(), Servo(), Servo()};
+
+ReadSerial comm;
+
+void setup(){
+ Serial.begin(19200);
+
+ motori[0].attach( motore1PWMPin, 1000, 2400 );
+ motori[1].attach( motore2PWMPin, 1000, 2400 );
+ motori[2].attach( motore3PWMPin, 1000, 2400 );
+ motori[3].attach( motore4PWMPin, 1000, 2400 );
+ int i;
+ for(i=0; i<4; i++){
+ motori[i].write(0);
+ }
+ delay(2000);
+}
+
+void loop(){
+ if ( comm.readSerial() ){
+ char c;
+ float v;
+ comm.get(&c, &v);
+ executeCommand(c, v);
+
+ int i;
+ for(i=0; i<4; i++){
+ Serial.print(i);
+ Serial.print(":");
+ Serial.println( motori[i].read() );
+ }
+ }
+}
+
+
+void executeCommand(char c, float v){
+
+ Serial.print("setting command and value ");
+ Serial.print(c);
+ Serial.print(" ");
+ Serial.println(v);
+
+ int i = c-'0';
+ motori[i].write( constrain(v, 0, 180) );
+}
74 ControlloMotoriSeriale/ReadSerial.cpp
View
@@ -0,0 +1,74 @@
+#include "ReadSerial.h"
+
+
+ReadSerial::ReadSerial(){
+ indexInput2=0;
+ inputValue=false;
+ validInput=false;
+}
+
+bool ReadSerial::readSerial(){
+ /*
+ input data: *name:value\n
+ */
+ while (Serial.available() > 0){
+ char c = Serial.read();
+ if (c =='*'){
+ indexInput2=0;
+ inputValue=false;
+ validInput=true;
+ Serial.println("starting input");
+ }else{
+
+ if (validInput){
+ if (c =='\n'){
+ input2[indexInput2]='\0';
+ Serial.print("value ok");
+ Serial.println(input2);
+ int point=1, i=0;
+ float ris=0;
+ while(input2[i]!='\0'){
+ if (input2[i]=='.'){
+ point=indexInput2-i;
+ }else{
+ ris=(ris*10)+input2[i]-'0';
+ }
+ i++;
+ }
+ Serial.print("ris and point ");
+ Serial.print(ris);
+ Serial.print(" ");
+ Serial.println(point);
+ ris/=point;
+ finalC=input1;
+ finalF=ris;
+ validInput=false;
+ indexInput2=0;
+ inputValue=false;
+ return true;
+ }else{
+ if (inputValue){
+ input2[indexInput2]=c;
+ indexInput2++;
+ }else{
+ if (c ==':'){
+ Serial.println("command ok, waiting value");
+ inputValue=true;
+ }else{
+ Serial.print("command ");
+ Serial.println(c);
+ input1=c;
+ }
+ }
+ }
+ }
+
+ }
+ }
+ return false;
+}
+
+void ReadSerial::get(char *risC, float *risF){
+ (*risC)=finalC;
+ (*risF)=finalF;
+}
22 ControlloMotoriSeriale/ReadSerial.h
View
@@ -0,0 +1,22 @@
+#ifndef Giroscopio_h
+#define Giroscopio_h
+
+#include "WProgram.h"
+
+#define midPrecision 500
+
+class ReadSerial{
+ public:
+ ReadSerial();
+ bool readSerial();
+ void get(char *, float *);
+ private:
+ char input1;
+ char input2[10];
+ int indexInput2;
+ boolean inputValue;
+ boolean validInput;
+ char finalC;
+ float finalF;
+};
+#endif
37 DCMtest1/DCMtest1.pde
View
@@ -0,0 +1,37 @@
+#include "IMU.h"
+
+IMU orizzonte;
+
+unsigned long time;
+void setup(){
+ Serial.begin(19200);
+ time = micros();
+}
+unsigned long time2=0;
+unsigned long time3=0;
+int loopNumber=0;
+void loop(){
+ loopNumber++;
+ time3=micros();
+ if (time2==0)
+ time2=time3-time;
+ else
+ time2=(time2+ (time3-time) )/2;
+ time = time3;
+ if (loopNumber > 100){
+ Serial.println(time2);
+ loopNumber=0;
+ }
+
+ float gyroX;
+ float gyroY;
+ float gyroZ;
+
+ float accX;
+ float accY;
+ float accZ;
+
+ //normalizzazione valori
+
+ orizzonte.IMUupdate(gyroX, gyroY, gyroZ, accX, accY, accZ);
+}
102 DCMtest1/IMU.cpp
View
@@ -0,0 +1,102 @@
+//=====================================================================================================
+// IMU.c
+// S.O.H. Madgwick
+// 25th September 2010
+//
+// IMU.cpp
+// Modified as class for arduino by Lestofante
+// 27th December 2010
+//=====================================================================================================
+// Description:
+//
+// Quaternion implementation of the 'DCM filter' [Mayhony et al].
+//
+// User must define 'halfT' as the (sample period / 2), and the filter gains 'Kp' and 'Ki'.
+//
+// Global variables 'q0', 'q1', 'q2', 'q3' are the quaternion elements representing the estimated
+// orientation. See my report for an overview of the use of quaternions in this application.
+//
+// User must call 'IMUupdate()' every sample period and parse calibrated gyroscope ('gx', 'gy', 'gz')
+// and accelerometer ('ax', 'ay', 'ay') data. Gyroscope units are radians/second, accelerometer
+// units are irrelevant as the vector is normalised.
+//
+//=====================================================================================================
+
+//----------------------------------------------------------------------------------------------------
+// Header files
+
+#include "IMU.h"
+#include <math.h>
+
+//----------------------------------------------------------------------------------------------------
+// Definitions
+
+#define Kp 2.0f // proportional gain governs rate of convergence to accelerometer/magnetometer
+#define Ki 0.005f // integral gain governs rate of convergence of gyroscope biases
+#define halfT 0.5f // half the sample period
+
+//---------------------------------------------------------------------------------------------------
+// Variable definitions
+
+//float q0 = 1, q1 = 0, q2 = 0, q3 = 0; // quaternion elements representing the estimated orientation
+//float exInt = 0, eyInt = 0, ezInt = 0; // scaled integral error
+
+//====================================================================================================
+// Function
+//====================================================================================================
+
+IMU::IMU(){
+ exInt=0;
+ eyInt=0;
+ ezInt=0;
+}
+
+void IMU::IMUupdate(float gx, float gy, float gz, float ax, float ay, float az) {
+ float norm;
+ float vx, vy, vz;
+ float ex, ey, ez;
+
+ // normalise the measurements
+ norm = sqrt(ax*ax + ay*ay + az*az);
+ ax = ax / norm;
+ ay = ay / norm;
+ az = az / norm;
+
+ // estimated direction of gravity
+ vx = 2*(q1*q3 - q0*q2);
+ vy = 2*(q0*q1 + q2*q3);
+ vz = q0*q0 - q1*q1 - q2*q2 + q3*q3;
+
+ // error is sum of cross product between reference direction of field and direction measured by sensor
+ ex = (ay*vz - az*vy);
+ ey = (az*vx - ax*vz);
+ ez = (ax*vy - ay*vx);
+
+ // integral error scaled integral gain
+ exInt = exInt + ex*Ki;
+ eyInt = eyInt + ey*Ki;
+ ezInt = ezInt + ez*Ki;
+
+ // adjusted gyroscope measurements
+ gx = gx + Kp*ex + exInt;
+ gy = gy + Kp*ey + eyInt;
+ gz = gz + Kp*ez + ezInt;
+
+ // integrate quaternion rate and normalise
+ q0 = q0 + (-q1*gx - q2*gy - q3*gz)*halfT;
+ q1 = q1 + (q0*gx + q2*gz - q3*gy)*halfT;
+ q2 = q2 + (q0*gy - q1*gz + q3*gx)*halfT;
+ q3 = q3 + (q0*gz + q1*gy - q2*gx)*halfT;
+
+ // normalise quaternion
+ norm = sqrt(q0*q0 + q1*q1 + q2*q2 + q3*q3);
+ q0 = q0 / norm;
+ q1 = q1 / norm;
+ q2 = q2 / norm;
+ q3 = q3 / norm;
+}
+
+//====================================================================================================
+// END OF CODE
+//====================================================================================================
+
37 DCMtest1/IMU.h
View
@@ -0,0 +1,37 @@
+//=====================================================================================================
+// IMU.h
+// S.O.H. Madgwick
+// 25th September 2010
+//
+// Modified as class for arduino by Lestofante
+// 27th December 2010
+//
+//=====================================================================================================
+//
+// See IMU.c file for description.
+//
+//=====================================================================================================
+#ifndef IMU_h
+#define IMU_h
+
+#include <WProgram.h>
+//----------------------------------------------------------------------------------------------------
+// Variable declaration
+class IMU{
+
+ public:
+ float q0, q1, q2, q3; // quaternion elements representing the estimated orientation
+
+ //---------------------------------------------------------------------------------------------------
+ // Function declaration
+ IMU(); //constructor, set exInt, eyInt and ezInt to 0
+ void IMUupdate(float gx, float gy, float gz, float ax, float ay, float az);
+
+ private:
+ float exInt, eyInt, ezInt; // scaled integral error
+
+};
+#endif
+//=====================================================================================================
+// End of file
+//=====================================================================================================
38 DS18B20/DS18B20.ino
View
@@ -0,0 +1,38 @@
+#include "OneWire.h"
+#include "DallasTemperature.h"
+
+// Data wire is plugged into pin 2 on the Arduino
+//#define ONE_WIRE_BUS 2
+
+// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
+OneWire oneWire(2);
+
+// Pass our oneWire reference to Dallas Temperature.
+DallasTemperature sensors(&oneWire);
+
+void setup(void)
+{
+ // start serial port
+ Serial.begin(9600);
+ Serial.println("Dallas Temperature IC Control Library Demo");
+
+ // Start up the library
+ sensors.begin(); // IC Default 9 bit. If you have troubles consider upping it 12. Ups the delay giving the IC more time to process the temperature measurement
+ sensors.setResolution(12);
+}
+
+
+void loop(void)
+{
+ // call sensors.requestTemperatures() to issue a global temperature
+ // request to all devices on the bus
+ Serial.print("Requesting temperatures...");
+ sensors.requestTemperatures(); // Send the command to get temperatures
+ Serial.println("DONE");
+
+ Serial.print("Temperature for Device 1 is: ");
+ Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"? You can have more than one IC on the same bus. 0 refers to the first IC on the wire
+
+}
+
+
738 DS18B20/DallasTemperature.cpp
View
@@ -0,0 +1,738 @@
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+
+// Version 3.7.2 modified on Dec 6, 2011 to support Arduino 1.0
+// See Includes...
+// Modified by Jordan Hochenbaum
+
+#include "DallasTemperature.h"
+
+#if ARDUINO >= 100
+ #include "Arduino.h"
+#else
+extern "C" {
+ #include "WConstants.h"
+}
+#endif
+
+DallasTemperature::DallasTemperature(OneWire* _oneWire)
+ #if REQUIRESALARMS
+ : _AlarmHandler(&defaultAlarmHandler)
+ #endif
+{
+ _wire = _oneWire;
+ devices = 0;
+ parasite = false;
+ bitResolution = 9;
+ waitForConversion = true;
+ checkForConversion = true;
+}
+
+// initialise the bus
+void DallasTemperature::begin(void)
+{
+ DeviceAddress deviceAddress;
+
+ _wire->reset_search();
+ devices = 0; // Reset the number of devices when we enumerate wire devices
+
+ while (_wire->search(deviceAddress))
+ {
+ if (validAddress(deviceAddress))
+ {
+ if (!parasite && readPowerSupply(deviceAddress)) parasite = true;
+
+ ScratchPad scratchPad;
+
+ readScratchPad(deviceAddress, scratchPad);
+
+ bitResolution = max(bitResolution, getResolution(deviceAddress));
+
+ devices++;
+ }
+ }
+}
+
+// returns the number of devices found on the bus
+uint8_t DallasTemperature::getDeviceCount(void)
+{
+ return devices;
+}
+
+// returns true if address is valid
+bool DallasTemperature::validAddress(uint8_t* deviceAddress)
+{
+ return (_wire->crc8(deviceAddress, 7) == deviceAddress[7]);
+}
+
+// finds an address at a given index on the bus
+// returns true if the device was found
+bool DallasTemperature::getAddress(uint8_t* deviceAddress, uint8_t index)
+{
+ uint8_t depth = 0;
+
+ _wire->reset_search();
+
+ while (depth <= index && _wire->search(deviceAddress))
+ {
+ if (depth == index && validAddress(deviceAddress)) return true;
+ depth++;
+ }
+
+ return false;
+}
+
+// attempt to determine if the device at the given address is connected to the bus
+bool DallasTemperature::isConnected(uint8_t* deviceAddress)
+{
+ ScratchPad scratchPad;
+ return isConnected(deviceAddress, scratchPad);
+}
+
+// attempt to determine if the device at the given address is connected to the bus
+// also allows for updating the read scratchpad
+bool DallasTemperature::isConnected(uint8_t* deviceAddress, uint8_t* scratchPad)
+{
+ readScratchPad(deviceAddress, scratchPad);
+ return (_wire->crc8(scratchPad, 8) == scratchPad[SCRATCHPAD_CRC]);
+}
+
+// read device's scratch pad
+void DallasTemperature::readScratchPad(uint8_t* deviceAddress, uint8_t* scratchPad)
+{
+ // send the command
+ _wire->reset();
+ _wire->select(deviceAddress);
+ _wire->write(READSCRATCH);
+
+ // TODO => collect all comments & use simple loop
+ // byte 0: temperature LSB
+ // byte 1: temperature MSB
+ // byte 2: high alarm temp
+ // byte 3: low alarm temp
+ // byte 4: DS18S20: store for crc
+ // DS18B20 & DS1822: configuration register
+ // byte 5: internal use & crc
+ // byte 6: DS18S20: COUNT_REMAIN
+ // DS18B20 & DS1822: store for crc
+ // byte 7: DS18S20: COUNT_PER_C
+ // DS18B20 & DS1822: store for crc
+ // byte 8: SCRATCHPAD_CRC
+ //
+ // for(int i=0; i<9; i++)
+ // {
+ // scratchPad[i] = _wire->read();
+ // }
+
+
+ // read the response
+
+ // byte 0: temperature LSB
+ scratchPad[TEMP_LSB] = _wire->read();
+
+ // byte 1: temperature MSB
+ scratchPad[TEMP_MSB] = _wire->read();
+
+ // byte 2: high alarm temp
+ scratchPad[HIGH_ALARM_TEMP] = _wire->read();
+
+ // byte 3: low alarm temp
+ scratchPad[LOW_ALARM_TEMP] = _wire->read();
+
+ // byte 4:
+ // DS18S20: store for crc
+ // DS18B20 & DS1822: configuration register
+ scratchPad[CONFIGURATION] = _wire->read();
+
+ // byte 5:
+ // internal use & crc
+ scratchPad[INTERNAL_BYTE] = _wire->read();
+
+ // byte 6:
+ // DS18S20: COUNT_REMAIN
+ // DS18B20 & DS1822: store for crc
+ scratchPad[COUNT_REMAIN] = _wire->read();
+
+ // byte 7:
+ // DS18S20: COUNT_PER_C
+ // DS18B20 & DS1822: store for crc
+ scratchPad[COUNT_PER_C] = _wire->read();
+
+ // byte 8:
+ // SCTRACHPAD_CRC
+ scratchPad[SCRATCHPAD_CRC] = _wire->read();
+
+ _wire->reset();
+}
+
+// writes device's scratch pad
+void DallasTemperature::writeScratchPad(uint8_t* deviceAddress, const uint8_t* scratchPad)
+{
+ _wire->reset();
+ _wire->select(deviceAddress);
+ _wire->write(WRITESCRATCH);
+ _wire->write(scratchPad[HIGH_ALARM_TEMP]); // high alarm temp
+ _wire->write(scratchPad[LOW_ALARM_TEMP]); // low alarm temp
+ // DS18S20 does not use the configuration register
+ if (deviceAddress[0] != DS18S20MODEL) _wire->write(scratchPad[CONFIGURATION]); // configuration
+ _wire->reset();
+ // save the newly written values to eeprom
+ _wire->write(COPYSCRATCH, parasite);
+ if (parasite) delay(10); // 10ms delay
+ _wire->reset();
+}
+
+// reads the device's power requirements
+bool DallasTemperature::readPowerSupply(uint8_t* deviceAddress)
+{
+ bool ret = false;
+ _wire->reset();
+ _wire->select(deviceAddress);
+ _wire->write(READPOWERSUPPLY);
+ if (_wire->read_bit() == 0) ret = true;
+ _wire->reset();
+ return ret;
+}
+
+
+// set resolution of all devices to 9, 10, 11, or 12 bits
+// if new resolution is out of range, it is constrained.
+void DallasTemperature::setResolution(uint8_t newResolution)
+{
+ bitResolution = constrain(newResolution, 9, 12);
+ DeviceAddress deviceAddress;
+ for (int i=0; i<devices; i++)
+ {
+ getAddress(deviceAddress, i);
+ setResolution(deviceAddress, bitResolution);
+ }
+}
+
+// set resolution of a device to 9, 10, 11, or 12 bits
+// if new resolution is out of range, 9 bits is used.
+bool DallasTemperature::setResolution(uint8_t* deviceAddress, uint8_t newResolution)
+{
+ ScratchPad scratchPad;
+ if (isConnected(deviceAddress, scratchPad))
+ {
+ // DS18S20 has a fixed 9-bit resolution
+ if (deviceAddress[0] != DS18S20MODEL)
+ {
+ switch (newResolution)
+ {
+ case 12:
+ scratchPad[CONFIGURATION] = TEMP_12_BIT;
+ break;
+ case 11:
+ scratchPad[CONFIGURATION] = TEMP_11_BIT;
+ break;
+ case 10:
+ scratchPad[CONFIGURATION] = TEMP_10_BIT;
+ break;
+ case 9:
+ default:
+ scratchPad[CONFIGURATION] = TEMP_9_BIT;
+ break;
+ }
+ writeScratchPad(deviceAddress, scratchPad);
+ }
+ return true; // new value set
+ }
+ return false;
+}
+
+// returns the global resolution
+uint8_t DallasTemperature::getResolution()
+{
+ return bitResolution;
+}
+
+// returns the current resolution of the device, 9-12
+// returns 0 if device not found
+uint8_t DallasTemperature::getResolution(uint8_t* deviceAddress)
+{
+ if (deviceAddress[0] == DS18S20MODEL) return 9; // this model has a fixed resolution
+
+ ScratchPad scratchPad;
+ if (isConnected(deviceAddress, scratchPad))
+ {
+ switch (scratchPad[CONFIGURATION])
+ {
+ case TEMP_12_BIT:
+ return 12;
+
+ case TEMP_11_BIT:
+ return 11;
+
+ case TEMP_10_BIT:
+ return 10;
+
+ case TEMP_9_BIT:
+ return 9;
+
+ }
+ }
+ return 0;
+}
+
+
+// sets the value of the waitForConversion flag
+// TRUE : function requestTemperature() etc returns when conversion is ready
+// FALSE: function requestTemperature() etc returns immediately (USE WITH CARE!!)
+// (1) programmer has to check if the needed delay has passed
+// (2) but the application can do meaningful things in that time
+void DallasTemperature::setWaitForConversion(bool flag)
+{
+ waitForConversion = flag;
+}
+
+// gets the value of the waitForConversion flag
+bool DallasTemperature::getWaitForConversion()
+{
+ return waitForConversion;
+}
+
+
+// sets the value of the checkForConversion flag
+// TRUE : function requestTemperature() etc will 'listen' to an IC to determine whether a conversion is complete
+// FALSE: function requestTemperature() etc will wait a set time (worst case scenario) for a conversion to complete
+void DallasTemperature::setCheckForConversion(bool flag)
+{
+ checkForConversion = flag;
+}
+
+// gets the value of the waitForConversion flag
+bool DallasTemperature::getCheckForConversion()
+{
+ return checkForConversion;
+}
+
+bool DallasTemperature::isConversionAvailable(uint8_t* deviceAddress)
+{
+ // Check if the clock has been raised indicating the conversion is complete
+ ScratchPad scratchPad;
+ readScratchPad(deviceAddress, scratchPad);
+ return scratchPad[0];
+}
+
+
+// sends command for all devices on the bus to perform a temperature conversion
+void DallasTemperature::requestTemperatures()
+{
+ _wire->reset();
+ _wire->skip();
+ _wire->write(STARTCONVO, parasite);
+
+ // ASYNC mode?
+ if (!waitForConversion) return;
+ blockTillConversionComplete(&bitResolution, 0);
+
+ return;
+}
+
+// sends command for one device to perform a temperature by address
+// returns FALSE if device is disconnected
+// returns TRUE otherwise
+bool DallasTemperature::requestTemperaturesByAddress(uint8_t* deviceAddress)
+{
+
+ _wire->reset();
+ _wire->select(deviceAddress);
+ _wire->write(STARTCONVO, parasite);
+
+ // check device
+ ScratchPad scratchPad;
+ if (!isConnected(deviceAddress, scratchPad)) return false;
+
+
+ // ASYNC mode?
+ if (!waitForConversion) return true;
+ uint8_t bitResolution = getResolution(deviceAddress);
+ blockTillConversionComplete(&bitResolution, deviceAddress);
+
+ return true;
+}
+
+
+void DallasTemperature::blockTillConversionComplete(uint8_t* bitResolution, uint8_t* deviceAddress)
+{
+ if(deviceAddress != 0 && checkForConversion && !parasite)
+ {
+ // Continue to check if the IC has responded with a temperature
+ // NB: Could cause issues with multiple devices (one device may respond faster)
+ unsigned long start = millis();
+ while(!isConversionAvailable(0) && ((millis() - start) < 750));
+ }
+
+ // Wait a fix number of cycles till conversion is complete (based on IC datasheet)
+ switch (*bitResolution)
+ {
+ case 9:
+ delay(94);
+ break;
+ case 10:
+ delay(188);
+ break;
+ case 11:
+ delay(375);
+ break;
+ case 12:
+ default:
+ delay(750);
+ break;
+ }
+
+}
+
+// sends command for one device to perform a temp conversion by index
+bool DallasTemperature::requestTemperaturesByIndex(uint8_t deviceIndex)
+{
+ DeviceAddress deviceAddress;
+ getAddress(deviceAddress, deviceIndex);
+ return requestTemperaturesByAddress(deviceAddress);
+}
+
+// Fetch temperature for device index
+float DallasTemperature::getTempCByIndex(uint8_t deviceIndex)
+{
+ DeviceAddress deviceAddress;
+ getAddress(deviceAddress, deviceIndex);
+ return getTempC((uint8_t*)deviceAddress);
+}
+
+// Fetch temperature for device index
+float DallasTemperature::getTempFByIndex(uint8_t deviceIndex)
+{
+ return toFahrenheit(getTempCByIndex(deviceIndex));
+}
+
+// reads scratchpad and returns the temperature in degrees C
+float DallasTemperature::calculateTemperature(uint8_t* deviceAddress, uint8_t* scratchPad)
+{
+ int16_t rawTemperature = (((int16_t)scratchPad[TEMP_MSB]) << 8) | scratchPad[TEMP_LSB];
+
+ switch (deviceAddress[0])
+ {
+ case DS18B20MODEL:
+ case DS1822MODEL:
+ switch (scratchPad[CONFIGURATION])
+ {
+ case TEMP_12_BIT:
+ return (float)rawTemperature * 0.0625;
+ break;
+ case TEMP_11_BIT:
+ return (float)(rawTemperature >> 1) * 0.125;
+ break;
+ case TEMP_10_BIT:
+ return (float)(rawTemperature >> 2) * 0.25;
+ break;
+ case TEMP_9_BIT:
+ return (float)(rawTemperature >> 3) * 0.5;
+ break;
+ }
+ break;
+ case DS18S20MODEL:
+ /*
+
+ Resolutions greater than 9 bits can be calculated using the data from
+ the temperature, COUNT REMAIN and COUNT PER �C registers in the
+ scratchpad. Note that the COUNT PER �C register is hard-wired to 16
+ (10h). After reading the scratchpad, the TEMP_READ value is obtained
+ by truncating the 0.5�C bit (bit 0) from the temperature data. The
+ extended resolution temperature can then be calculated using the
+ following equation:
+
+ COUNT_PER_C - COUNT_REMAIN
+ TEMPERATURE = TEMP_READ - 0.25 + --------------------------
+ COUNT_PER_C
+ */
+
+ // Good spot. Thanks Nic Johns for your contribution
+ return (float)(rawTemperature >> 1) - 0.25 +((float)(scratchPad[COUNT_PER_C] - scratchPad[COUNT_REMAIN]) / (float)scratchPad[COUNT_PER_C] );
+ break;
+ }
+}
+
+// returns temperature in degrees C or DEVICE_DISCONNECTED if the
+// device's scratch pad cannot be read successfully.
+// the numeric value of DEVICE_DISCONNECTED is defined in
+// DallasTemperature.h. It is a large negative number outside the
+// operating range of the device
+float DallasTemperature::getTempC(uint8_t* deviceAddress)
+{
+ // TODO: Multiple devices (up to 64) on the same bus may take
+ // some time to negotiate a response
+ // What happens in case of collision?
+
+ ScratchPad scratchPad;
+ if (isConnected(deviceAddress, scratchPad)) return calculateTemperature(deviceAddress, scratchPad);
+ return DEVICE_DISCONNECTED;
+}
+
+// returns temperature in degrees F
+// TODO: - when getTempC returns DEVICE_DISCONNECTED
+// -127 gets converted to -196.6 F
+float DallasTemperature::getTempF(uint8_t* deviceAddress)
+{
+ return toFahrenheit(getTempC(deviceAddress));
+}
+
+// returns true if the bus requires parasite power
+bool DallasTemperature::isParasitePowerMode(void)
+{
+ return parasite;
+}
+
+#if REQUIRESALARMS
+
+/*
+
+ALARMS:
+
+TH and TL Register Format
+
+BIT 7 BIT 6 BIT 5 BIT 4 BIT 3 BIT 2 BIT 1 BIT 0
+ S 2^6 2^5 2^4 2^3 2^2 2^1 2^0
+
+Only bits 11 through 4 of the temperature register are used
+in the TH and TL comparison since TH and TL are 8-bit
+registers. If the measured temperature is lower than or equal
+to TL or higher than or equal to TH, an alarm condition exists
+and an alarm flag is set inside the DS18B20. This flag is
+updated after every temperature measurement; therefore, if the
+alarm condition goes away, the flag will be turned off after
+the next temperature conversion.
+
+*/
+
+// sets the high alarm temperature for a device in degrees celsius
+// accepts a float, but the alarm resolution will ignore anything
+// after a decimal point. valid range is -55C - 125C
+void DallasTemperature::setHighAlarmTemp(uint8_t* deviceAddress, char celsius)
+{
+ // make sure the alarm temperature is within the device's range
+ if (celsius > 125) celsius = 125;
+ else if (celsius < -55) celsius = -55;
+
+ ScratchPad scratchPad;
+ if (isConnected(deviceAddress, scratchPad))
+ {
+ scratchPad[HIGH_ALARM_TEMP] = (uint8_t)celsius;
+ writeScratchPad(deviceAddress, scratchPad);
+ }
+}
+
+// sets the low alarm temperature for a device in degreed celsius
+// accepts a float, but the alarm resolution will ignore anything
+// after a decimal point. valid range is -55C - 125C
+void DallasTemperature::setLowAlarmTemp(uint8_t* deviceAddress, char celsius)
+{
+ // make sure the alarm temperature is within the device's range
+ if (celsius > 125) celsius = 125;
+ else if (celsius < -55) celsius = -55;
+
+ ScratchPad scratchPad;
+ if (isConnected(deviceAddress, scratchPad))
+ {
+ scratchPad[LOW_ALARM_TEMP] = (uint8_t)celsius;
+ writeScratchPad(deviceAddress, scratchPad);
+ }
+}
+
+// returns a char with the current high alarm temperature or
+// DEVICE_DISCONNECTED for an address
+char DallasTemperature::getHighAlarmTemp(uint8_t* deviceAddress)
+{
+ ScratchPad scratchPad;
+ if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[HIGH_ALARM_TEMP];
+ return DEVICE_DISCONNECTED;
+}
+
+// returns a char with the current low alarm temperature or
+// DEVICE_DISCONNECTED for an address
+char DallasTemperature::getLowAlarmTemp(uint8_t* deviceAddress)
+{
+ ScratchPad scratchPad;
+ if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[LOW_ALARM_TEMP];
+ return DEVICE_DISCONNECTED;
+}
+
+// resets internal variables used for the alarm search
+void DallasTemperature::resetAlarmSearch()
+{
+ alarmSearchJunction = -1;
+ alarmSearchExhausted = 0;
+ for(uint8_t i = 0; i < 7; i++)
+ alarmSearchAddress[i] = 0;
+}
+
+// This is a modified version of the OneWire::search method.
+//
+// Also added the OneWire search fix documented here:
+// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295
+//
+// Perform an alarm search. If this function returns a '1' then it has
+// enumerated the next device and you may retrieve the ROM from the
+// OneWire::address variable. If there are no devices, no further
+// devices, or something horrible happens in the middle of the
+// enumeration then a 0 is returned. If a new device is found then
+// its address is copied to newAddr. Use
+// DallasTemperature::resetAlarmSearch() to start over.
+bool DallasTemperature::alarmSearch(uint8_t* newAddr)
+{
+ uint8_t i;
+ char lastJunction = -1;
+ uint8_t done = 1;
+
+ if (alarmSearchExhausted) return false;
+ if (!_wire->reset()) return false;
+
+ // send the alarm search command
+ _wire->write(0xEC, 0);
+
+ for(i = 0; i < 64; i++)
+ {
+ uint8_t a = _wire->read_bit( );
+ uint8_t nota = _wire->read_bit( );
+ uint8_t ibyte = i / 8;
+ uint8_t ibit = 1 << (i & 7);
+
+ // I don't think this should happen, this means nothing responded, but maybe if
+ // something vanishes during the search it will come up.
+ if (a && nota) return false;
+
+ if (!a && !nota)
+ {
+ if (i == alarmSearchJunction)
+ {
+ // this is our time to decide differently, we went zero last time, go one.
+ a = 1;
+ alarmSearchJunction = lastJunction;
+ }
+ else if (i < alarmSearchJunction)
+ {
+ // take whatever we took last time, look in address
+ if (alarmSearchAddress[ibyte] & ibit) a = 1;
+ else
+ {
+ // Only 0s count as pending junctions, we've already exhasuted the 0 side of 1s
+ a = 0;
+ done = 0;
+ lastJunction = i;
+ }
+ }
+ else
+ {
+ // we are blazing new tree, take the 0
+ a = 0;
+ alarmSearchJunction = i;
+ done = 0;
+ }
+ // OneWire search fix
+ // See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295
+ }
+
+ if (a) alarmSearchAddress[ibyte] |= ibit;
+ else alarmSearchAddress[ibyte] &= ~ibit;
+
+ _wire->write_bit(a);
+ }
+
+ if (done) alarmSearchExhausted = 1;
+ for (i = 0; i < 8; i++) newAddr[i] = alarmSearchAddress[i];
+ return true;
+}
+
+// returns true if device address has an alarm condition
+// TODO: can this be done with only TEMP_MSB REGISTER (faster)
+// if ((char) scratchPad[TEMP_MSB] <= (char) scratchPad[LOW_ALARM_TEMP]) return true;
+// if ((char) scratchPad[TEMP_MSB] >= (char) scratchPad[HIGH_ALARM_TEMP]) return true;
+bool DallasTemperature::hasAlarm(uint8_t* deviceAddress)
+{
+ ScratchPad scratchPad;
+ if (isConnected(deviceAddress, scratchPad))
+ {
+ float temp = calculateTemperature(deviceAddress, scratchPad);
+
+ // check low alarm
+ if ((char)temp <= (char)scratchPad[LOW_ALARM_TEMP]) return true;
+
+ // check high alarm
+ if ((char)temp >= (char)scratchPad[HIGH_ALARM_TEMP]) return true;
+ }
+
+ // no alarm
+ return false;
+}
+
+// returns true if any device is reporting an alarm condition on the bus
+bool DallasTemperature::hasAlarm(void)
+{
+ DeviceAddress deviceAddress;
+ resetAlarmSearch();
+ return alarmSearch(deviceAddress);
+}
+
+// runs the alarm handler for all devices returned by alarmSearch()
+void DallasTemperature::processAlarms(void)
+{
+ resetAlarmSearch();
+ DeviceAddress alarmAddr;
+
+ while (alarmSearch(alarmAddr))
+ {
+ if (validAddress(alarmAddr))
+ _AlarmHandler(alarmAddr);
+ }
+}
+
+// sets the alarm handler
+void DallasTemperature::setAlarmHandler(AlarmHandler *handler)
+{
+ _AlarmHandler = handler;
+}
+
+// The default alarm handler
+void DallasTemperature::defaultAlarmHandler(uint8_t* deviceAddress)
+{
+}
+
+#endif
+
+// Convert float celsius to fahrenheit
+float DallasTemperature::toFahrenheit(float celsius)
+{
+ return (celsius * 1.8) + 32;
+}
+
+// Convert float fahrenheit to celsius
+float DallasTemperature::toCelsius(float fahrenheit)
+{
+ return (fahrenheit - 32) / 1.8;
+}
+
+#if REQUIRESNEW
+
+// MnetCS - Allocates memory for DallasTemperature. Allows us to instance a new object
+void* DallasTemperature::operator new(unsigned int size) // Implicit NSS obj size
+{
+ void * p; // void pointer
+ p = malloc(size); // Allocate memory
+ memset((DallasTemperature*)p,0,size); // Initalise memory
+
+ //!!! CANT EXPLICITLY CALL CONSTRUCTOR - workaround by using an init() methodR - workaround by using an init() method
+ return (DallasTemperature*) p; // Cast blank region to NSS pointer
+}
+
+// MnetCS 2009 - Unallocates the memory used by this instance
+void DallasTemperature::operator delete(void* p)
+{
+ DallasTemperature* pNss = (DallasTemperature*) p; // Cast to NSS pointer
+ pNss->~DallasTemperature(); // Destruct the object
+
+ free(p); // Free the memory
+}
+
+#endif
242 DS18B20/DallasTemperature.h
View
@@ -0,0 +1,242 @@
+#ifndef DallasTemperature_h
+#define DallasTemperature_h
+
+#define DALLASTEMPLIBVERSION "3.7.2"
+
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+
+// set to true to include code for new and delete operators
+#ifndef REQUIRESNEW
+#define REQUIRESNEW false
+#endif
+
+// set to true to include code implementing alarm search functions
+#ifndef REQUIRESALARMS
+#define REQUIRESALARMS true
+#endif
+
+#include <inttypes.h>
+#include "OneWire.h"
+
+// Model IDs
+#define DS18S20MODEL 0x10
+#define DS18B20MODEL 0x28
+#define DS1822MODEL 0x22
+
+// OneWire commands
+#define STARTCONVO 0x44 // Tells device to take a temperature reading and put it on the scratchpad
+#define COPYSCRATCH 0x48 // Copy EEPROM
+#define READSCRATCH 0xBE // Read EEPROM
+#define WRITESCRATCH 0x4E // Write to EEPROM
+#define RECALLSCRATCH 0xB8 // Reload from last known
+#define READPOWERSUPPLY 0xB4 // Determine if device needs parasite power
+#define ALARMSEARCH 0xEC // Query bus for devices with an alarm condition
+
+// Scratchpad locations
+#define TEMP_LSB 0
+#define TEMP_MSB 1
+#define HIGH_ALARM_TEMP 2
+#define LOW_ALARM_TEMP 3
+#define CONFIGURATION 4
+#define INTERNAL_BYTE 5
+#define COUNT_REMAIN 6
+#define COUNT_PER_C 7
+#define SCRATCHPAD_CRC 8
+
+// Device resolution
+#define TEMP_9_BIT 0x1F // 9 bit
+#define TEMP_10_BIT 0x3F // 10 bit
+#define TEMP_11_BIT 0x5F // 11 bit
+#define TEMP_12_BIT 0x7F // 12 bit
+
+// Error Codes
+#define DEVICE_DISCONNECTED -127
+
+typedef uint8_t DeviceAddress[8];
+
+class DallasTemperature
+{
+ public:
+
+ DallasTemperature(OneWire*);
+
+ // initalise bus
+ void begin(void);
+
+ // returns the number of devices found on the bus
+ uint8_t getDeviceCount(void);
+
+ // Is a conversion complete on the wire?
+ bool isConversionComplete(void);
+
+ // returns true if address is valid
+ bool validAddress(uint8_t*);
+
+ // finds an address at a given index on the bus
+ bool getAddress(uint8_t*, const uint8_t);
+
+ // attempt to determine if the device at the given address is connected to the bus
+ bool isConnected(uint8_t*);
+
+ // attempt to determine if the device at the given address is connected to the bus
+ // also allows for updating the read scratchpad
+ bool isConnected(uint8_t*, uint8_t*);
+
+ // read device's scratchpad
+ void readScratchPad(uint8_t*, uint8_t*);
+
+ // write device's scratchpad
+ void writeScratchPad(uint8_t*, const uint8_t*);
+
+ // read device's power requirements
+ bool readPowerSupply(uint8_t*);
+
+ // get global resolution
+ uint8_t getResolution();
+
+ // set global resolution to 9, 10, 11, or 12 bits
+ void setResolution(uint8_t);
+
+ // returns the device resolution, 9-12
+ uint8_t getResolution(uint8_t*);
+
+ // set resolution of a device to 9, 10, 11, or 12 bits
+ bool setResolution(uint8_t*, uint8_t);
+
+ // sets/gets the waitForConversion flag
+ void setWaitForConversion(bool);
+ bool getWaitForConversion(void);
+
+ // sets/gets the checkForConversion flag
+ void setCheckForConversion(bool);
+ bool getCheckForConversion(void);
+
+ // sends command for all devices on the bus to perform a temperature conversion
+ void requestTemperatures(void);
+
+ // sends command for one device to perform a temperature conversion by address
+ bool requestTemperaturesByAddress(uint8_t*);
+
+ // sends command for one device to perform a temperature conversion by index
+ bool requestTemperaturesByIndex(uint8_t);
+
+ // returns temperature in degrees C
+ float getTempC(uint8_t*);
+
+ // returns temperature in degrees F
+ float getTempF(uint8_t*);
+
+ // Get temperature for device index (slow)
+ float getTempCByIndex(uint8_t);
+
+ // Get temperature for device index (slow)
+ float getTempFByIndex(uint8_t);
+
+ // returns true if the bus requires parasite power
+ bool isParasitePowerMode(void);
+
+ bool isConversionAvailable(uint8_t*);
+
+ #if REQUIRESALARMS
+
+ typedef void AlarmHandler(uint8_t*);
+
+ // sets the high alarm temperature for a device
+ // accepts a char. valid range is -55C - 125C
+ void setHighAlarmTemp(uint8_t*, const char);
+
+ // sets the low alarm temperature for a device
+ // accepts a char. valid range is -55C - 125C
+ void setLowAlarmTemp(uint8_t*, const char);
+
+ // returns a signed char with the current high alarm temperature for a device
+ // in the range -55C - 125C
+ char getHighAlarmTemp(uint8_t*);
+
+ // returns a signed char with the current low alarm temperature for a device
+ // in the range -55C - 125C
+ char getLowAlarmTemp(uint8_t*);
+
+ // resets internal variables used for the alarm search
+ void resetAlarmSearch(void);
+
+ // search the wire for devices with active alarms
+ bool alarmSearch(uint8_t*);
+
+ // returns true if ia specific device has an alarm
+ bool hasAlarm(uint8_t*);
+
+ // returns true if any device is reporting an alarm on the bus
+ bool hasAlarm(void);
+
+ // runs the alarm handler for all devices returned by alarmSearch()
+ void processAlarms(void);
+
+ // sets the alarm handler
+ void setAlarmHandler(AlarmHandler *);
+
+ // The default alarm handler
+ static void defaultAlarmHandler(uint8_t*);
+
+ #endif
+
+ // convert from celcius to farenheit
+ static float toFahrenheit(const float);
+
+ // convert from farenheit to celsius
+ static float toCelsius(const float);
+
+ #if REQUIRESNEW
+
+ // initalize memory area
+ void* operator new (unsigned int);
+
+ // delete memory reference
+ void operator delete(void*);
+
+ #endif
+
+ private:
+ typedef uint8_t ScratchPad[9];
+
+ // parasite power on or off
+ bool parasite;
+
+ // used to determine the delay amount needed to allow for the
+ // temperature conversion to take place
+ uint8_t bitResolution;
+
+ // used to requestTemperature with or without delay
+ bool waitForConversion;
+
+ // used to requestTemperature to dynamically check if a conversion is complete
+ bool checkForConversion;
+
+ // count of devices on the bus
+ uint8_t devices;
+
+ // Take a pointer to one wire instance
+ OneWire* _wire;
+
+ // reads scratchpad and returns the temperature in degrees C
+ float calculateTemperature(uint8_t*, uint8_t*);
+
+ void blockTillConversionComplete(uint8_t*,uint8_t*);
+
+ #if REQUIRESALARMS
+
+ // required for alarmSearch
+ uint8_t alarmSearchAddress[8];
+ char alarmSearchJunction;
+ uint8_t alarmSearchExhausted;
+
+ // the alarm handler function pointer
+ AlarmHandler *_AlarmHandler;
+
+ #endif
+
+};
+#endif
527 DS18B20/OneWire.cpp
View
@@ -0,0 +1,527 @@
+/*
+Copyright (c) 2007, Jim Studt (original old version - many contributors since)
+
+The latest version of this library may be found at:
+ http://www.pjrc.com/teensy/td_libs_OneWire.html
+
+Version 2.1:
+ Arduino 1.0 compatibility, Paul Stoffregen
+ Improve temperature example, Paul Stoffregen
+ DS250x_PROM example, Guillermo Lovato
+ PIC32 (chipKit) compatibility, Jason Dangel, dangel.jason AT gmail.com
+ Improvements from Glenn Trewitt:
+ - crc16() now works
+ - check_crc16() does all of calculation/checking work.
+ - Added read_bytes() and write_bytes(), to reduce tedious loops.
+ - Added ds2408 example.
+ Delete very old, out-of-date readme file (info is here)
+
+Version 2.0: Modifications by Paul Stoffregen, January 2010:
+http://www.pjrc.com/teensy/td_libs_OneWire.html
+ Search fix from Robin James
+ http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27
+ Use direct optimized I/O in all cases
+ Disable interrupts during timing critical sections
+ (this solves many random communication errors)
+ Disable interrupts during read-modify-write I/O
+ Reduce RAM consumption by eliminating unnecessary
+ variables and trimming many to 8 bits
+ Optimize both crc8 - table version moved to flash
+
+Modified to work with larger numbers of devices - avoids loop.
+Tested in Arduino 11 alpha with 12 sensors.
+26 Sept 2008 -- Robin James
+http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27
+
+Updated to work with arduino-0008 and to include skip() as of
+2007/07/06. --RJL20
+
+Modified to calculate the 8-bit CRC directly, avoiding the need for
+the 256-byte lookup table to be loaded in RAM. Tested in arduino-0010
+-- Tom Pollard, Jan 23, 2008
+
+Jim Studt's original library was modified by Josh Larios.
+
+Tom Pollard, pollard@alum.mit.edu, contributed around May 20, 2008
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Much of the code was inspired by Derek Yerger's code, though I don't
+think much of that remains. In any event that was..
+ (copyleft) 2006 by Derek Yerger - Free to distribute freely.
+
+The CRC code was excerpted and inspired by the Dallas Semiconductor
+sample code bearing this copyright.
+//---------------------------------------------------------------------------
+// Copyright (C) 2000 Dallas Semiconductor Corporation, All Rights Reserved.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the "Software"),
+// to deal in the Software without restriction, including without limitation
+// the rights to use, copy, modify, merge, publish, distribute, sublicense,
+// and/or sell copies of the Software, and to permit persons to whom the
+// Software is furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+// IN NO EVENT SHALL DALLAS SEMICONDUCTOR BE LIABLE FOR ANY CLAIM, DAMAGES
+// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+// OTHER DEALINGS IN THE SOFTWARE.
+//
+// Except as contained in this notice, the name of Dallas Semiconductor
+// shall not be used except as stated in the Dallas Semiconductor
+// Branding Policy.
+//--------------------------------------------------------------------------
+*/
+
+#include "OneWire.h"
+
+
+OneWire::OneWire(uint8_t pin)
+{
+ pinMode(pin, INPUT);
+ bitmask = PIN_TO_BITMASK(pin);
+ baseReg = PIN_TO_BASEREG(pin);
+#if ONEWIRE_SEARCH
+ reset_search();
+#endif
+}
+
+
+// Perform the onewire reset function. We will wait up to 250uS for
+// the bus to come high, if it doesn't then it is broken or shorted
+// and we return a 0;
+//
+// Returns 1 if a device asserted a presence pulse, 0 otherwise.
+//
+uint8_t OneWire::reset(void)
+{
+ IO_REG_TYPE mask = bitmask;
+ volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg;
+ uint8_t r;
+ uint8_t retries = 125;
+
+ noInterrupts();
+ DIRECT_MODE_INPUT(reg, mask);
+ interrupts();
+ // wait until the wire is high... just in case
+ do {
+ if (--retries == 0) return 0;
+ delayMicroseconds(2);
+ } while ( !DIRECT_READ(reg, mask));
+
+ noInterrupts();
+ DIRECT_WRITE_LOW(reg, mask);
+ DIRECT_MODE_OUTPUT(reg, mask); // drive output low
+ interrupts();
+ delayMicroseconds(500);
+ noInterrupts();
+ DIRECT_MODE_INPUT(reg, mask); // allow it to float
+ delayMicroseconds(80);
+ r = !DIRECT_READ(reg, mask);
+ interrupts();
+ delayMicroseconds(420);
+ return r;
+}
+
+//
+// Write a bit. Port and bit is used to cut lookup time and provide
+// more certain timing.
+//
+void OneWire::write_bit(uint8_t v)
+{
+ IO_REG_TYPE mask=bitmask;
+ volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg;
+
+ if (v & 1) {
+ noInterrupts();
+ DIRECT_WRITE_LOW(reg, mask);
+ DIRECT_MODE_OUTPUT(reg, mask); // drive output low
+ delayMicroseconds(10);
+ DIRECT_WRITE_HIGH(r