123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- #include "stm32f1xx_hal.h"
- #include<stdio.h>
- #define DS18B20_PIN GPIO_PIN_14
- #define DS18B20_PORT GPIOC
- void us_delay(uint16_t delay)
- {
- TIM1->CNT = 0;
- while (TIM1->CNT < delay);
- }
- /**
- * Control registers for F1xx GPIOs are 2 x 2 bits
- * For Port C, CRH, pin 14 bits 27-24
- * CNF: Input mode: 01=Float input Output mode: 01=Open-drain (Reset stage is 01)
- * MODE: 00=Input 10=Out 2 MHz
- *
- * So bits should be for | XXXX |
- * Input: 0100 AND-Mask: 0xF4FFFFFF 11110100111111111111111111111111
- * Output: 0110 OR-Mask: 0x06000000 00000110000000000000000000000000
- *
- * For init use OR 0x04000000 and then AND 0xF4FFFFFF = Input
- *
- */
- void init_gpio_pin(void)
- {
- DS18B20_PORT->CRH |= 0x04000000;
- DS18B20_PORT->CRH &= 0xF4FFFFFF;
- }
- void gpio_set_input(void)
- {
- DS18B20_PORT->CRH &= 0xF4FFFFFF;
- DS18B20_PORT->BSRR = (1 << 14);
- }
- void gpio_set_output(void)
- {
- DS18B20_PORT->BSRR = (1 << 14);
- DS18B20_PORT->CRH |= 0x06000000;
- }
- int readInput()
- {
- if (((DS18B20_PORT->IDR) & (1 << 14)) == 0)
- return 0;
- else
- return 1;
- }
- void writeBitHigh() { DS18B20_PORT->BSRR = (1 << 14); }
- void writeBitLow() { DS18B20_PORT->BSRR = (1 << 30); }
- void writeSlot(uint8_t data) {
- gpio_set_output(); // set as output
- if( data == 1 ) {
- // write 1
- writeBitLow();
- us_delay(1);
- writeBitHigh();
- us_delay(64);
- }
- else {
- // write 0
- writeBitLow();
- us_delay(65);
- writeBitHigh();
- }
- gpio_set_input();
- us_delay(5);
- }
- uint8_t readSlot(void) {
- uint8_t retVal = 0;
- gpio_set_output(); // set as output
- writeBitLow();
- us_delay(1);
- writeBitHigh();
- gpio_set_input(); // 2.5mS has passed
- us_delay(10); // 12.5mS has passed
- if (readInput() == 1) // if the pin is HIGH
- {
- retVal = 1;
- }
- us_delay(55);
- return retVal;
- }
- void writeByte(uint8_t data)
- {
- for (int i = 0; i < 8; i++)
- {
- writeSlot( ((data & (1 << i)) == 0) ? 0:1 );
- }
- }
- uint8_t readByte(void)
- {
- uint8_t value = 0;
- for (int i = 0; i < 8; i++)
- {
- if (readSlot() == 1) value |= 1 << i;
- }
- return value;
- }
- uint8_t oneWire_init(void)
- {
- volatile int i;
- uint8_t retVal = 0;
- gpio_set_output();
- writeBitLow();
- us_delay(500);
- writeBitHigh();
- gpio_set_input();
- us_delay(20);
- for(i=0;i<48;i++) { // We must wait minimum 480uS in total. Every loop is 10uS
- if( readInput() == 0 ) retVal = 1; // Ok, sensor was found
- us_delay(10);
- }
- return retVal;
- }
|