Skip to content
  • MySensors
  • OpenHardware.io
  • Categories
  • Recent
  • Tags
  • Popular
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Brand Logo
Cliff KarlssonC

Cliff Karlsson

@Cliff Karlsson
About
Posts
399
Topics
103
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • People counter using VL53L1X help "decoding" existing code to arduino
    Cliff KarlssonC Cliff Karlsson

    I stumbled upon this video that I think is really cool. I then found a forum thread on the ST website where an ST employee responded that he could send the code by email. After getting the code I realized that the code was made for some other system (STM32?). Could anyone look at the code and see if it is possible to port so it would be usable using an Arduino/ESP32/ESP8266 ?

    Code

    https://www.youtube.com/watch?v=c91Ve-g0J2U

    I think I found the code

    /**
      ******************************************************************************
      * File Name          : main.c
      * Description        : Main program body
      ******************************************************************************
      *
      * COPYRIGHT(c) 2017 STMicroelectronics
      *
      * Redistribution and use in source and binary forms, with or without modification,
      * are permitted provided that the following conditions are met:
      *   1. Redistributions of source code must retain the above copyright notice,
      *      this list of conditions and the following disclaimer.
      *   2. Redistributions in binary form must reproduce the above copyright notice,
      *      this list of conditions and the following disclaimer in the documentation
      *      and/or other materials provided with the distribution.
      *   3. Neither the name of STMicroelectronics nor the names of its contributors
      *      may be used to endorse or promote products derived from this software
      *      without specific prior written permission.
      *
      * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
      * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
      * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
      * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
      * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
      * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
      * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      *
      ******************************************************************************
      */
    	
    /* Includes ------------------------------------------------------------------*/
    #include "stm32xxx_hal.h"
    
    /* USER CODE BEGIN Includes */
    #include "main.h"
    #include "VL53L1X_API.h"
    #include "VL53l1X_calibration.h"
    #include "X-NUCLEO-53L1A1.h"
    /* USER CODE END Includes */
    /* Private variables ---------------------------------------------------------*/
    /* USER CODE BEGIN PV */
    /* Private variables ---------------------------------------------------------*/
    I2C_HandleTypeDef hi2c1;
    UART_HandleTypeDef huart2;
    VL53L1_Dev_t                   dev;
    int status = 0;
    volatile int IntCount;
    #define isInterrupt 1 /* If isInterrupt = 1 then device working in interrupt mode, else device working in polling mode */
    /* USER CODE END PV */
    
    /* Private function prototypes -----------------------------------------------*/
    /* USER CODE BEGIN PFP */
    /* Private function prototypes -----------------------------------------------*/
    int SystemClock_Config(void);
    static void MX_GPIO_Init(void);
    static int MX_USART2_UART_Init(void);
    static int MX_I2C1_Init(void);
    /* USER CODE END PFP */
    
    /* USER CODE BEGIN 0 */
    #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
    
    // People Counting defines
    #define NOBODY 0
    #define SOMEONE 1
    #define LEFT 0
    #define RIGHT 1
    
    #define DIST_THRESHOLD_MAX  1780
    
    
    PUTCHAR_PROTOTYPE
    {
    	HAL_UART_Transmit(&huart2, (uint8_t*)&ch, 1, 0xFFFF);
    	return ch;
    }
    
    void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
    {
    	if (GPIO_Pin==VL53L1X_INT_Pin)
    	{
    		IntCount++;
    	}
    }
    
    /* USER CODE END 0 */
    
    
    
    int ProcessPeopleCountingData(int16_t Distance, uint8_t zone) {
    
    	static char PeopleCountString[4];
        static int PathTrack[] = {0,0,0,0};
        static int PathTrackFillingSize = 1; // init this to 1 as we start from state where nobody is any of the zones
        static int LeftPreviousStatus = NOBODY;
        static int RightPreviousStatus = NOBODY;
        static int PeopleCount = 0;
    
        int CurrentZoneStatus = NOBODY;
        int AllZonesCurrentStatus = 0;
        int AnEventHasOccured = 0;
    
    	if (Distance < DIST_THRESHOLD_MAX) {
    		// Someone is in !
    		CurrentZoneStatus = SOMEONE;
    	}
    
    	// left zone
    	if (zone == LEFT) {
    
    		if (CurrentZoneStatus != LeftPreviousStatus) {
    			// event in left zone has occured
    			AnEventHasOccured = 1;
    
    			if (CurrentZoneStatus == SOMEONE) {
    				AllZonesCurrentStatus += 1;
    			}
    			// need to check right zone as well ...
    			if (RightPreviousStatus == SOMEONE) {
    				// event in left zone has occured
    				AllZonesCurrentStatus += 2;
    			}
    			// remember for next time
    			LeftPreviousStatus = CurrentZoneStatus;
    		}
    	}
    	// right zone
    	else {
    
    		if (CurrentZoneStatus != RightPreviousStatus) {
    
    			// event in left zone has occured
    			AnEventHasOccured = 1;
    			if (CurrentZoneStatus == SOMEONE) {
    				AllZonesCurrentStatus += 2;
    			}
    			// need to left right zone as well ...
    			if (LeftPreviousStatus == SOMEONE) {
    				// event in left zone has occured
    				AllZonesCurrentStatus += 1;
    			}
    			// remember for next time
    			RightPreviousStatus = CurrentZoneStatus;
    		}
    	}
    
    	// if an event has occured
    	if (AnEventHasOccured) {
    		if (PathTrackFillingSize < 4) {
    			PathTrackFillingSize ++;
    		}
    
    		// if nobody anywhere lets check if an exit or entry has happened
    		if ((LeftPreviousStatus == NOBODY) && (RightPreviousStatus == NOBODY)) {
    
    			// check exit or entry only if PathTrackFillingSize is 4 (for example 0 1 3 2) and last event is 0 (nobobdy anywhere)
    			if (PathTrackFillingSize == 4) {
    				// check exit or entry. no need to check PathTrack[0] == 0 , it is always the case
    
    				if ((PathTrack[1] == 1)  && (PathTrack[2] == 3) && (PathTrack[3] == 2)) {
    					// This an entry
    					PeopleCount ++;
                        sprintf(PeopleCountString, "%d", PeopleCount);
                        XNUCLEO53L1A1_SetDisplayString(PeopleCountString);
    
    				} else if ((PathTrack[1] == 2)  && (PathTrack[2] == 3) && (PathTrack[3] == 1)) {
    					// This an exit
    					PeopleCount --;
                        sprintf(PeopleCountString, "%d", PeopleCount);
                        XNUCLEO53L1A1_SetDisplayString(PeopleCountString);
    				}
    			}
    
    			PathTrackFillingSize = 1;
    		}
    		else {
    			// update PathTrack
    			// example of PathTrack update
    			// 0
    			// 0 1
    			// 0 1 3
    			// 0 1 3 1
    			// 0 1 3 3
    			// 0 1 3 2 ==> if next is 0 : check if exit
    			PathTrack[PathTrackFillingSize-1] = AllZonesCurrentStatus;
    		}
    	}
    
    	// output debug data to main host machine
    	return(PeopleCount);
    
    }
    
    int main(void)
    {
    	int8_t error;
        uint8_t byteData, sensorState=0;
        uint16_t wordData;
        uint16_t Distance;
        uint8_t RangeStatus;
        uint8_t dataReady;
        int center[2] = {167,231}; /* these are the spad center of the 2 8*16 zones */
        int Zone = 0;
        int PplCounter = 0;
        
        /* MCU Configuration----------------------------------------------------------*/
        
        /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
        HAL_Init();
        
        /* Configure the system clock */
        error = SystemClock_Config();
        
        /* Initialize all configured peripherals */
        MX_GPIO_Init();
        error += MX_USART2_UART_Init();
        error += MX_I2C1_Init();
        
        if (error != 0)
        {
            printf("Could not initialize the nucleo board\n");
            return -1;
        }
    
        XNUCLEO53L1A1_Init();
        dev.I2cHandle = &hi2c1;
        dev.I2cDevAddr = 0x52;
       
        status = XNUCLEO53L1A1_ResetId(XNUCLEO53L1A1_DEV_LEFT, 0); // Reset ToF sensor
        HAL_Delay(2);
        status = XNUCLEO53L1A1_ResetId(XNUCLEO53L1A1_DEV_CENTER, 0); // Reset ToF sensor
        HAL_Delay(2);
        status = XNUCLEO53L1A1_ResetId(XNUCLEO53L1A1_DEV_RIGHT, 0); // Reset ToF sensor
        HAL_Delay(2);
        status = XNUCLEO53L1A1_ResetId(XNUCLEO53L1A1_DEV_LEFT, 1); // Reset ToF sensor
        HAL_Delay(2);
        
        // Those basic I2C read functions can be used to check your own I2C functions */
        status = VL53L1_RdByte(&dev, 0x010F, &byteData);
        printf("VL53L1X Model_ID: %X\n", byteData);
        status = VL53L1_RdByte(&dev, 0x0110, &byteData);
        printf("VL53L1X Module_Type: %X\n", byteData);
        status = VL53L1_RdWord(&dev, 0x010F, &wordData);
        printf("VL53L1X: %X\n", wordData);
        while (sensorState == 0) {
            status = VL53L1X_BootState(dev, &sensorState);
            HAL_Delay(2);
        }
       
        printf("Chip booted\n");
        
        /* Init 4 digit display */
        XNUCLEO53L1A1_SetDisplayString("0");
    
        /* Initialize and configure the device according to people counting need */
        status = VL53L1X_SensorInit(dev);
        status += VL53L1X_SetDistanceMode(dev, 2); /* 1=short, 2=long */
        status += VL53L1X_SetTimingBudgetInMs(dev, 20); /* in ms possible values [20, 50, 100, 200, 500] */
        status += VL53L1X_SetInterMeasurementInMs(dev, 20); 
        status += VL53L1X_SetROI(dev, 8, 16); /* minimum ROI 4,4 */
        if (status != 0) {
            printf("Error in Initalisation or configuration of the device\n");
            return (-1);
        }
        
        printf("Start counting people  ...\n");
        status = VL53L1X_StartRanging(dev);   /* This function has to be called to enable the ranging */
        
        while(1) { /* read and display data */
            while (dataReady == 0) {
    			status = VL53L1X_CheckForDataReady(dev, &dataReady);
    			HAL_Delay(2);
            }
        
    		dataReady = 0;
    		status += VL53L1X_GetRangeStatus(dev, &RangeStatus);
    		status += VL53L1X_GetDistance(dev, &Distance);
    		status += VL53L1X_ClearInterrupt(dev); /* clear interrupt has to be called to enable next interrupt*/
    		if (status != 0) {
    			printf("Error in operating the device\n");
    			return (-1);
    		}
    
    		// wait a couple of milliseconds to ensure the setting of the new ROI center for the next ranging is effective
    		// otherwise there is a risk that this setting is applied to current ranging (even if timing has expired, the intermeasurement
    		// may expire immediately after.
    		HAL_Delay(10);
    		status = VL53L1X_SetROICenter(dev, center[Zone]);
    		if (status != 0) {
    			printf("Error in chaning the center of the ROI\n");
    			return (-1);
    		}
    
    		// inject the new ranged distance in the people counting algorithm
    		PplCounter = ProcessPeopleCountingData(Distance, Zone);
    
    		Zone++;
    		Zone = Zone%2;
    
    		printf("%d, %d, %d, %d\n", Zone, RangeStatus, Distance, PplCounter);
        }
    }
    
    /** System Clock Configuration
    */
    #ifdef STM32F401xE
    
    int SystemClock_Config(void)
    {
    
        RCC_OscInitTypeDef RCC_OscInitStruct;
        RCC_ClkInitTypeDef RCC_ClkInitStruct;
      
        /**Configure the main internal regulator output voltage 
        */
        __HAL_RCC_PWR_CLK_ENABLE();
      
        __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);
      
        /**Initializes the CPU, AHB and APB busses clocks 
        */
        RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
        RCC_OscInitStruct.HSIState = RCC_HSI_ON;
        RCC_OscInitStruct.HSICalibrationValue = 16;
        RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
        RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
        RCC_OscInitStruct.PLL.PLLM = 16;
        RCC_OscInitStruct.PLL.PLLN = 336;
        RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
        RCC_OscInitStruct.PLL.PLLQ = 7;
        if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
        {
            return -1;
        }
      
        /**Initializes the CPU, AHB and APB busses clocks 
        */
        RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                                    |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
        RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
        RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
        RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
        RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
      
        if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
        {
            return -1;
        }
      
        /**Configure the Systick interrupt time 
        */
        HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
      
        /**Configure the Systick 
        */
        HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
      
        /* SysTick_IRQn interrupt configuration */
        HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
      
        return 0;
    }
    #endif
    
    
    #ifdef STM32F401xE
    
    /* I2C1 init function */
    static int MX_I2C1_Init(void)
    {
        hi2c1.Instance = I2C1;
        hi2c1.Init.ClockSpeed = 100000;
        hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
        hi2c1.Init.OwnAddress1 = 0;
        hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
        hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
        hi2c1.Init.OwnAddress2 = 0;
        hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
        hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
        if (HAL_I2C_Init(&hi2c1) != HAL_OK)
        {
          return -1;
        }
        
        return 0;
    
    }
    #endif
    
    /* USART2 init function */
    int MX_USART2_UART_Init(void)
    {
    
        huart2.Instance = USART2;
        huart2.Init.BaudRate = 460800;
        huart2.Init.WordLength = UART_WORDLENGTH_8B;
        huart2.Init.StopBits = UART_STOPBITS_1;
        huart2.Init.Parity = UART_PARITY_NONE;
        huart2.Init.Mode = UART_MODE_TX_RX;
        huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
        huart2.Init.OverSampling = UART_OVERSAMPLING_16;
        if (HAL_UART_Init(&huart2) != HAL_OK)
        {
            return (-1);
        }
        return 0;
    
    }
    
    /** Configure pins as 
            * Analog 
            * Input 
            * Output
            * EVENT_OUT
            * EXTI
    */
    static void MX_GPIO_Init(void)
    {
    
        GPIO_InitTypeDef GPIO_InitStruct;
       
        /* GPIO Ports Clock Enable */
        __HAL_RCC_GPIOC_CLK_ENABLE();
        __HAL_RCC_GPIOH_CLK_ENABLE();
        __HAL_RCC_GPIOA_CLK_ENABLE();
        __HAL_RCC_GPIOB_CLK_ENABLE();
       
        /*Configure GPIO pin Output Level */
        HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);
       
        /*Configure GPIO pin : B1_Pin */
        GPIO_InitStruct.Pin = B1_Pin;
        GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
        GPIO_InitStruct.Pull = GPIO_NOPULL;
        HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
       
        /*Configure GPIO pin : VL53L1X_INT_Pin */
        GPIO_InitStruct.Pin = VL53L1X_INT_Pin;
        GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
        GPIO_InitStruct.Pull = GPIO_PULLUP;
        HAL_GPIO_Init(VL53L1X_INT_GPIO_Port, &GPIO_InitStruct);
       
        /*Configure GPIO pin : LD2_Pin */
        GPIO_InitStruct.Pin = LD2_Pin;
        GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
        GPIO_InitStruct.Pull = GPIO_NOPULL;
        GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
        HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);
       
        /* EXTI interrupt init*/
        HAL_NVIC_SetPriority(EXTI4_IRQn, 0, 0);
        HAL_NVIC_EnableIRQ(EXTI4_IRQn);
    
    }
    
    
    /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
    
    
    General Discussion

  • Help understanding why websockets does not work in arduino sketch
    Cliff KarlssonC Cliff Karlsson

    have taken som existing code which reads a sensor and outputs to a webserver using websockets (running on an ESP8266) that connects to a wifi-network. I tried to modify the code so that instead of connecting to an existing wifi it creates a AP that I can connect to login to the webserver to show the data.

    I can connect to the AP and also connect to the webserver after logging in to the AP. But ít only shows a empty table. If I look at the serial monitor the sensor outputs all data correctly.

    Have I done anything wrong modifying the code?

    
    // ESP8266 Pins
    //  4(SDA) --- AMG8833 SDA
    //  5(SCL) --- AMG8833 SCL
    //  13     --- LED (Anode) via 100ohm
    
    #include <pgmspace.h>
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <WebSocketsServer.h>
    #include <ESP8266mDNS.h>
    #include <ArduinoOTA.h>
    #include <Wire.h>
    #include <Adafruit_AMG88xx.h>
    
    Adafruit_AMG88xx amg;
    
    const char* ssid = "Jacksson";
    const char* password = "mandelvatten";
    
    const int pin_led = 13;
    
    ESP8266WebServer server(80);
    WebSocketsServer webSocket(81);
    
    void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
      switch (type) {
        case WStype_DISCONNECTED:
          Serial.printf("[%u] Disconnected!\n", num);
          break;
        case WStype_CONNECTED:
          IPAddress ip = webSocket.remoteIP(num);
          Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
          break;
      }
    }
    
    void toggle() {
      static bool last_led = false;
      last_led = !last_led;
      digitalWrite(pin_led, last_led);
    }
    
    void handleRoot() {
     auto ip = WiFi.localIP();
     String ip_str = String(ip[0]) + "." + ip[1] + "." + ip[2] + "." + ip[3];
     server.send(200, "text/html", String(ws_html_1()) +  ip_str + ws_html_2());
     // server.send(200, "text/html", "<h1>You are connected</h1>");
    }
    
    void handleNotFound() {
      String message = "File Not Found\n\n";
      message += "URI: ";
      message += server.uri();
      message += "\nMethod: ";
      message += (server.method() == HTTP_GET)?"GET":"POST";
      message += "\nArguments: ";
      message += server.args();
      message += "\n";
      for (uint8_t i = 0; i<server.args(); i++){
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
      }
      server.send(404, "text/plain", message);
    }
    
    void WiFiEvent(WiFiEvent_t event) {
        switch(event) {
          
          case WIFI_EVENT_STAMODE_DISCONNECTED:
            digitalWrite(pin_led, LOW);
            Serial.println("WiFi lost connection: reconnecting...");
            WiFi.begin();
            break;
          case WIFI_EVENT_STAMODE_CONNECTED:
            Serial.print("Connected to ");
            Serial.println(ssid);
            break;
          case WIFI_EVENT_STAMODE_GOT_IP:
            digitalWrite(pin_led, HIGH);
            Serial.print("IP address: ");
            Serial.println(WiFi.localIP());
            if (MDNS.begin("esp8266-amg8833")) {
              Serial.println("MDNS responder started");
            }
            enableOTA();
            break;
        }
    }
    
    void enableOTA() {
      // Port defaults to 8266
      // ArduinoOTA.setPort(8266);
    
      // Hostname defaults to esp8266-[ChipID]
      // ArduinoOTA.setHostname("myesp8266");
    
      // No authentication by default
      // ArduinoOTA.setPassword((const char *)"123");
    
      ArduinoOTA.onStart([]() {
        Serial.println("Start");
      });
      ArduinoOTA.onEnd([]() {
        Serial.println("\nEnd");
      });
      ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
        Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
      });
      ArduinoOTA.onError([](ota_error_t error) {
        Serial.printf("Error[%u]: ", error);
        if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
        else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
        else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
        else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
        else if (error == OTA_END_ERROR) Serial.println("End Failed");
      });
      ArduinoOTA.begin();
    }
    
    void setup(void) {
     delay(1000);
      Serial.begin(115200);
      Serial.println();
      Serial.print("Configuring access point...");
      /* You can remove the password parameter if you want the AP to be open. */
      WiFi.softAP(ssid, password);
    
      IPAddress myIP = WiFi.softAPIP();
      Serial.print("AP IP address: ");
      Serial.println(myIP);
      server.on("/", handleRoot);
      server.begin();
      Serial.println("HTTP server started");
    
      server.on("/current", [](){
        String str;
        server.send(200, "text/plain", get_current_values_str(str));
      });
    
      server.onNotFound(handleNotFound);
    
      server.begin();
    
      webSocket.begin();
      webSocket.onEvent(webSocketEvent);
    
      Serial.println("HTTP server started");
    
      amg.begin(0x69);
      delay(100); // let sensor boot up
    }
    
    void loop(void) {
      ArduinoOTA.handle();
      server.handleClient();
      webSocket.loop();
    
     
    
      static unsigned long last_read_ms = millis();
      unsigned long now = millis();
      if (now - last_read_ms > 100) {
        last_read_ms += 100;
        String str;
        get_current_values_str(str);
        Serial.println(str);
        webSocket.broadcastTXT(str);
      }
    }
    
    String& get_current_values_str(String& ret)
    {
      float pixels[AMG88xx_PIXEL_ARRAY_SIZE];
      amg.readPixels(pixels);
      ret = "[";
      for(int i = 0; i < AMG88xx_PIXEL_ARRAY_SIZE; i++) {
        if( i % 8 == 0 ) ret += "\r\n";
        ret += pixels[i];
        if (i != AMG88xx_PIXEL_ARRAY_SIZE - 1) ret += ", ";
      }
      ret += "\r\n]\r\n";
      return ret;
    }
    
    const __FlashStringHelper* ws_html_1() {
      return F("<!DOCTYPE html>\n"
        "<html>\n"
        "<head>\n"
        "<title>thermo</title>\n"
        "<style>\n"
        "body {\n"
        "    background-color: #667;\n"
        "}\n"
        "table#tbl td {\n"
        "    width: 64px;\n"
        "    height: 64px;\n"
        "    border: solid 1px grey;\n"
        "    text-align: center;\n"
        "}\n"
        "</style>\n"
        "</head>\n"
        "<body>\n"
        "<h1>Exjobbsgrejs</h1>"
        "<table border id=\"tbl\"></table>\n"
        "<script>\n"
        "function bgcolor(t) {\n"
        "    if (t < 0) t = 0;\n"
        "    if (t > 30) t = 30;\n"
        "    return \"hsl(\" + (360 - t * 12) + \", 100%, 80%)\";\n"
        "}\n"
        "\n"
        "var t = document.getElementById('tbl');\n"
        "var tds = [];\n"
        "for (var i = 0; i < 8; i++) {\n"
        "    var tr = document.createElement('tr');\n"
        "    for (var j = 0; j < 8; j++) {\n"
        "        var td = tds[i*8 + 7 - j] = document.createElement('td');\n"
        "        tr.appendChild(td);\n"
        "    }\n"
        "    t.appendChild(tr);\n"
        "}\n"
        "var connection = new WebSocket('ws://");
    }
    
    const __FlashStringHelper* ws_html_2() {
      return F(":81/');\n"
        "connection.onmessage = function(e) {\n"
        "    const data = JSON.parse(e.data);\n"
        "    for (var i = 0; i < 64; i++) {\n"
        "        tds[i].innerHTML = data[i].toFixed(2);\n"
        "        tds[i].style.backgroundColor = bgcolor(data[i]);\n"
        "    }\n"
        "};\n"
        "</script>\n"
        "</body>\n"
        "</html>\n");
    }
    
    
    Troubleshooting

  • Is this scenario possible using domoticz?
    Cliff KarlssonC Cliff Karlsson

    I have been planning to build/use a sensor with domoticz but my skills are pretty limited. But I am wondering if this is possible:

    I have a sensor whish can output four different values depending on how the sensor is triggered, how do I send four different values to domoticz and what sensor type do I chose? I want in this example be able to light up four different lightbulbs in domoticz depending on the sensoroutput.

    I would also want to be able to use a local variable and a global variable. Can I somehow "push" a variable from domoticz to the sensor everytime it changes?

    Domoticz

  • Ninja spheres for sale (Sweden)
    Cliff KarlssonC Cliff Karlsson

    Ok sorry if this is not allowed and just remove this post. But I have three Ninja spheres that I got from kickstarter a while a go. There supposed to be some super home-automation devices with zigbee/wlan/bluetooth (check the homepage for exact specs). But as alot of kickstarter campaigns this one crashed and burned and no development is done anymore.

    So the hardware is all cool and working but the software is dead i would think. It runs Ubuntu core I think and you can connect through ssh to fiddle around. I used it in the beginning to control my wemo lights directly from the sphere by swiping ontop of it. homepage
    I know I will never be able to use them for anything productive but maybee someone here can make some use of them. Give me a bid for one or all of them. I am not expecting a fortune...

    General Discussion

  • Help with sketch (motion/distance)
    Cliff KarlssonC Cliff Karlsson

    I never understod how the millis() -part worked so I just changed it to a simple countdown instead.

    Troubleshooting

  • Help with sketch (motion/distance)
    Cliff KarlssonC Cliff Karlsson

    @mfalkvidd Thanks for the help.
    I don't know why I had "INTERRUPT MOTION_A_TRIGGER_PIN-3" I think I originaly used pin2 for the motion sensor and when moving it to pin 3 I misunderstood and also changed that part from -2 to -3.

    Now most parts works as intended. But after triggering the motion sensor the distance-sensors fires for around 60s (Maybe the time it takes for the PIR to reset itself?)

    I only want the distance sensors to be active for 3s (unsigned long time = millis() + 30000;). How to I fix that?

    Troubleshooting

  • Help with sketch (motion/distance)
    Cliff KarlssonC Cliff Karlsson

    Re: Help with sketch (motion/distance)

    I had some additional wiring problems so the distance sensors seams to work ok now. But It does not look like the motion-sensor part works.

    I was thinking that the sensor should sleep until motion but it should report the status to the controller every 120s so that domoticz etc. does not think that the sensor is dead.

    Now it starts the distance sensors directly on power and runs them for a long time and then sleeps. But I cant wake it up by moving my hand in front of it. I think it wakes up every 120s and spams the distance sensor then sleeps agin.

    0 MCO:BGN:INIT NODE,CP=RNNNA--,VER=2.1.1
    3 TSM:INIT
    4 TSF:WUR:MS=0
    11 TSM:INIT:TSP OK
    13 TSF:SID:OK,ID=2
    14 TSM:FPAR
    51 TSF:MSG:SEND,2-2-255-255,s=255,c=3,t=7,pt=0,l=0,sg=0,ft=0,st=OK:
    2058 !TSM:FPAR:NO REPLY
    2060 TSM:FPAR
    2096 TSF:MSG:SEND,2-2-255-255,s=255,c=3,t=7,pt=0,l=0,sg=0,ft=0,st=OK:
    2934 TSF:MSG:READ,0-0-2,s=255,c=3,t=8,pt=1,l=1,sg=0:0
    2939 TSF:MSG:FPAR OK,ID=0,D=1
    4104 TSM:FPAR:OK
    4105 TSM:ID
    4106 TSM:ID:OK
    4108 TSM:UPL
    4113 TSF:MSG:SEND,2-2-0-0,s=255,c=3,t=24,pt=1,l=1,sg=0,ft=0,st=OK:1
    4219 TSF:MSG:READ,0-0-2,s=255,c=3,t=25,pt=1,l=1,sg=0:1
    4224 TSF:MSG:PONG RECV,HP=1
    4227 TSM:UPL:OK
    4228 TSM:READY:ID=2,PAR=0,DIS=1
    4233 TSF:MSG:SEND,2-2-0-0,s=255,c=3,t=15,pt=6,l=2,sg=0,ft=0,st=OK:0100
    4366 TSF:MSG:READ,0-0-2,s=255,c=3,t=15,pt=6,l=2,sg=0:0100
    4373 TSF:MSG:SEND,2-2-0-0,s=255,c=0,t=17,pt=0,l=5,sg=0,ft=0,st=OK:2.1.1
    4381 TSF:MSG:SEND,2-2-0-0,s=255,c=3,t=6,pt=1,l=1,sg=0,ft=0,st=OK:0
    4648 TSF:MSG:READ,0-0-2,s=255,c=3,t=6,pt=0,l=1,sg=0:M
    4656 TSF:MSG:SEND,2-2-0-0,s=255,c=3,t=11,pt=0,l=22,sg=0,ft=0,st=OK:Distance+Motion Sensor
    4666 TSF:MSG:SEND,2-2-0-0,s=255,c=3,t=12,pt=0,l=3,sg=0,ft=0,st=OK:1.0
    4674 TSF:MSG:SEND,2-2-0-0,s=1,c=0,t=15,pt=0,l=0,sg=0,ft=0,st=OK:
    4715 !TSF:MSG:SEND,2-2-0-0,s=2,c=0,t=15,pt=0,l=0,sg=0,ft=0,st=NACK:
    4727 TSF:MSG:SEND,2-2-0-0,s=3,c=0,t=1,pt=0,l=0,sg=0,ft=1,st=OK:
    4733 MCO:REG:REQ
    4770 !TSF:MSG:SEND,2-2-0-0,s=255,c=3,t=26,pt=1,l=1,sg=0,ft=0,st=NACK:2
    6779 TSF:MSG:SEND,2-2-0-0,s=255,c=3,t=26,pt=1,l=1,sg=0,ft=1,st=OK:2
    6848 TSF:MSG:READ,0-0-2,s=255,c=3,t=27,pt=1,l=1,sg=0:1
    6852 MCO:PIM:NODE REG=1
    6855 MCO:BGN:STP
    6856 MCO:BGN:INIT OK,TSP=1
    1
    6860 TSF:MSG:SEND,2-2-0-0,s=3,c=1,t=16,pt=0,l=1,sg=0,ft=0,st=OK:1
    Ping Sonar A: 0 cm
    Ping Sonar B: 15 cm
    6970 TSF:MSG:SEND,2-2-0-0,s=2,c=1,t=13,pt=2,l=2,sg=0,ft=0,st=OK:15
    Ping Sonar A: 123 cm
    6985 TSF:MSG:SEND,2-2-0-0,s=1,c=1,t=13,pt=2,l=2,sg=0,ft=0,st=OK:123
    Ping Sonar B: 15 cm
    Ping Sonar A: 126 cm
    7102 TSF:MSG:SEND,2-2-0-0,s=1,c=1,t=13,pt=2,l=2,sg=0,ft=0,st=OK:126
    Ping Sonar B: 15 cm
    Ping Sonar A: 125 cm
    7222 TSF:MSG:SEND,2-2-0-0,s=1,c=1,t=13,pt=2,l=2,sg=0,ft=0,st=OK:125
    Ping Sonar B: 15 cm
    Ping Sonar A: 125 cm
    Ping Sonar B: 15 cm
    Ping Sonar A: 126 cm
    7450 TSF:MSG:SEND,2-2-0-0,s=1,c=1,t=13,pt=2,l=2,sg=0,ft=0,st=OK:126
    Ping Sonar B: 15 cm
    Ping Sonar A: 125 cm
    7569 TSF:MSG:SEND,2-2-0-0,s=1,c=1,t=13,pt=2,l=2,sg=0,ft=0,st=OK:125
    Ping Sonar B: 15 cm
    Ping Sonar A: 125 cm
    Ping Sonar B: 15 cm
    Ping Sonar A: 125 cm
    Ping Sonar B: 15 cm
    Ping Sonar A: 124 cm
    35517 TSF:MSG:SEND,2-2-0-0,s=2,c=1,t=13,pt=2,l=2,sg=0,ft=0,st=OK:78
    Ping Sonar A: 80 cm
    35544 TSF:MSG:SEND,2-2-0-0,s=1,c=1,t=13,pt=2,l=2,sg=0,ft=0,st=OK:80
    Ping Sonar B: 74 cm
    35656 TSF:MSG:SEND,2-2-0-0,s=2,c=1,t=13,pt=2,l=2,sg=0,ft=0,st=OK:74
    Ping Sonar A: 132 cm
    35707 !TSF:MSG:SEND,2-2-0-0,s=1,c=1,t=13,pt=2,l=2,sg=0,ft=0,st=NACK:132
    Ping Sonar B: 79 cm
    ...
    35820 TSF:MSG:SEND,2-2-0-0,s=2,c=1,t=13,pt=2,l=2,sg=0,ft=1,st=OK:79
    35827 MCO:SLP:MS=200,SMS=0,I1=255,M1=255,I2=255,M2=255
    35831 MCO:SLP:TPD
    35833 MCO:SLP:WUP=-1
    35835 MCO:SLP:MS=120000,SMS=0,I1=0,M1=1,I2=255,M2=255
    35841 MCO:SLP:TPD
    
    Troubleshooting

  • Help with sketch (motion/distance)
    Cliff KarlssonC Cliff Karlsson

    Thanks, well firstly the motion-sensor almost never triggers and when it finaly does I get only 0 or a few (1-2) readings from the Ultrasonic-sensor and it seams that only one of them gives me distance.

    Troubleshooting

  • Connecting external power and FTDI adapter?
    Cliff KarlssonC Cliff Karlsson

    I have a Arduino pro mini 5v where I have attached a couple of 5v sensors. I am using an external 5v powersupply and it is powering the sensors directly and also the arduino from the Vin/Gnd.

    I tried connecting the arduino to a 3.3v usb ftdi adapter without using the power supply to upload sketches and to use the serial monitor and it worked. But how do I power all the sensors from the power supply and also connect the ftdi-adapter at the same time without frying anything?

    Troubleshooting

  • Help with sketch (motion/distance)
    Cliff KarlssonC Cliff Karlsson

    Can anyone tell me how to fix this sketch so that it woorks correctly.

    I want the sensor to wake up when motion-sensor is triggered and start sending distance data from both Ultrasonic-sensors to controller for like 5s. Then back to sleep again until Motion is detected again.

    
    // Enable debug prints
    #define MY_DEBUG
    #define MY_BAUD_RATE 115200
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    
    #include <NewPing.h>
    #include <MySensors.h>
    #include <SPI.h>
    
    #define SONAR_A_CHILD_ID 1
    #define SONAR_B_CHILD_ID 2
    #define MOTION_A_CHILD_ID 3
    
    #define MOTION_A_TRIGGER_PIN  3
    
    #define SONAR_A_TRIGGER_PIN  5  // Arduino pin tied to trigger pin on the ultrasonic sensor.
    #define SONAR_A_ECHO_PIN     4 // Arduino pin tied to echo pin on the ultrasonic sensor.
    
    
    #define SONAR_B_TRIGGER_PIN  7  // Arduino pin tied to trigger pin on the ultrasonic sensor.
    #define SONAR_B_ECHO_PIN     6  // Arduino pin tied to echo pin on the ultrasonic sensor.
    
    #define MAX_DISTANCE 300 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
    unsigned long SLEEP_TIME = 200; // Sleep time between reads (in milliseconds)
    
    unsigned long MOTION_SLEEP_TIME = 120000; // Sleep time between reports (in milliseconds)
    #define INTERRUPT MOTION_A_TRIGGER_PIN-3 // Usually the interrupt = pin -2 (on uno/nano anyway)
    
    
    NewPing sonar_A(SONAR_A_TRIGGER_PIN, SONAR_A_ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
    NewPing sonar_B(SONAR_B_TRIGGER_PIN, SONAR_B_ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
    
    
    MyMessage SONAR_A_msg(SONAR_A_CHILD_ID, V_DISTANCE);
    int SONAR_A_lastDist;
    
    MyMessage SONAR_B_msg(SONAR_B_CHILD_ID, V_DISTANCE);
    int SONAR_B_lastDist;
    
    MyMessage MOTION_A_msg(MOTION_A_CHILD_ID, V_TRIPPED);
    
    boolean metric = true; 
    
    void setup()  
    { 
      metric = getControllerConfig().isMetric; 
      pinMode(MOTION_A_TRIGGER_PIN, INPUT);      // sets the motion sensor digital pin as input
    }
    
    void presentation() {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("Distance+Motion Sensor", "1.0");
    
      // Register all sensors to gw (they will be created as child devices)
      present(SONAR_A_CHILD_ID, S_DISTANCE);
      present(SONAR_B_CHILD_ID, S_DISTANCE);
      present(MOTION_A_TRIGGER_PIN, S_MOTION);
    }
    
    void loop()      
    {     
      
      boolean tripped = digitalRead(MOTION_A_TRIGGER_PIN) == HIGH; 
      
        
      Serial.println(tripped);
      send(MOTION_A_msg.set(tripped?"1":"0"));  // Send tripped value to gw 
     
     if(tripped)  {
      unsigned long time = millis()+30000;
      while (millis() < time){
          int SONAR_A_dist = metric?sonar_A.ping_cm():sonar_A.ping_in();
          Serial.print("Ping Sonar A: ");
          Serial.print(SONAR_A_dist); // Convert ping time to distance in cm and print result (0 = outside set distance range)
          Serial.println(metric?" cm":" in");
    
      if (SONAR_A_dist != SONAR_A_lastDist) {
          send(SONAR_A_msg.set(SONAR_A_dist));
          SONAR_A_lastDist = SONAR_A_dist;
          }
      
      wait(100);
    
          int SONAR_B_dist = metric?sonar_B.ping_cm():sonar_B.ping_in();
          Serial.print("Ping Sonar B: ");
          Serial.print(SONAR_B_dist); // Convert ping time to distance in cm and print result (0 = outside set distance range)
          Serial.println(metric?" cm":" in");
    
      if (SONAR_B_dist != SONAR_B_lastDist) {
          send(SONAR_B_msg.set(SONAR_B_dist));
          SONAR_B_lastDist = SONAR_B_dist;
          }
      
      }
      sleep(SLEEP_TIME);
    }
                
    //else{
      // Sleep until interrupt comes in on motion sensor. Send update every two minute. 
      sleep(INTERRUPT,CHANGE, MOTION_SLEEP_TIME);
    //}
    }
    
    Troubleshooting

  • How to update counter using json
    Cliff KarlssonC Cliff Karlsson

    I have a device that sends a json using http post on every status change. The json looks something like this: "in:3 out :1" I want to be able to use this data to update a counter so that it shows the value from in-out. Or store the values in some variables or similar. Is this possible?

    Domoticz

  • Connecting grid-eye sensor
    Cliff KarlssonC Cliff Karlsson

    I managed to connect the sensor using the SDA and SCL and found some example code. I have only connected SDA,SCL, GND, and VCC. There where some more pins mentioned in the info but I guess they where not needed.
    I tried some software and it showed all temeratures correctly in a graphical gui but when I tried the arduino code the serial monitor wass willed with "garbage" even tho I used the the specified baudrate in the serial monitor.

    But I clearly see that the serial monitor reacts to my hand and other warm objects. Can I change anything in the code to have a clearer output?

    #include <Wire.h>       /*** including the Wire libary needed for the I2C communication ***/
    
    #include <Arduino.h>    /*** including the standard Arduino libary ***/
    
    
    #define AD_SELECT 19    /*** Define the address select pin ***/
    #define INT 18          /*** Define the interrupt pin ***/
    #define Hz10  85        /*** Define the delay time [ms] for the 10Hz mode ***/
    #define Hz1   985       /*** Define the delay time [ms] for the 1Hz mode ***/
    #define ADDR  0x68      /*** Define the I2C address for the Grid-EYE ***/
    
    
    void setup()
    {
      /*** join the I2C bus as master ***/
      Wire.begin();
      
      /*** start the serial Communication with 57600 Bauts ***/
      Serial.begin(57600);
    
    
      /*** Set the address pin as an output and set the Grid-EYE ***/
      /*** Slave address to 0x68 (0110 1000) ***/
      pinMode(AD_SELECT, OUTPUT);
      digitalWrite(AD_SELECT,LOW);
    
      /*** Set interrupt pin as an input pin ***/
      pinMode(INT, INPUT);
    
    }
    
    void loop()
    {
      /*** Variable declaration ***/
      byte pixelAddL;
      byte lowerLevel[64];
      byte upperLevel[64];
      byte lowerLevelTherm;
      byte upperLevelTherm;
      short Maindelay = Hz10;
    
      while(1)
      {
        /*** read out the Thermister tremperature ***/
        Wire.beginTransmission(ADDR);
        Wire.write(0x0E);
        Wire.endTransmission();
        Wire.requestFrom(ADDR, 2);
        lowerLevelTherm = Wire.read();
        upperLevelTherm = Wire.read();
        
        /*** set pixel address on the first Pixel (low) address ***/
        pixelAddL = 0x80;
    
        /*** read out the temperature of all 64 Pixel ***/
        for (int pixel = 0; pixel < 64; pixel++)
        {
          Wire.beginTransmission(ADDR);
          Wire.write(pixelAddL);
          Wire.endTransmission();
          Wire.requestFrom(ADDR, 2);
          lowerLevel[pixel] = Wire.read();
          upperLevel[pixel] = Wire.read();
          pixelAddL = pixelAddL + 2;
        }
        /*** end of read out ***/
    
        /*** Start Serial communication the temperature readout ***/
    
        /*** header ***/
        Serial.print('*');
        Serial.print('*');
        Serial.print('*');
        /*** send the thermistor temerature ***/
        Serial.print((char)lowerLevelTherm);
        Serial.print((char)upperLevelTherm);
    
        /*** send the temperature of the Pixel array ***/
        for (int pixel = 0; pixel < 64; pixel++)
        {
          Serial.print((char)lowerLevel[pixel]);
          Serial.print((char)upperLevel[pixel]);
        }
    
        /*** check if data was send to the EVB ***/
        if(Serial.available() > 0)
        {
          int command = Serial.read();
          int freq = Serial.read();
          
          if(freq == 10)  //Set the Grid-EYE to the 10 Hz mode
          {
            Wire.beginTransmission(ADDR);
            Wire.write(0x02);
            Wire.write(0x00);
            Wire.endTransmission();
            Maindelay = Hz10;
            
          }
          else if(freq == 1) //Set the Grid-EYE to the 1 Hz mode
          {
            Wire.beginTransmission(ADDR);
            Wire.write(0x02);
            Wire.write(0x01);
            Wire.endTransmission();
            Maindelay = Hz1;
            
          }
          else if(freq == 2) //Set the output Mode of the Grid-EYE to normal
          {
          
            Wire.beginTransmission(ADDR);
            Wire.write(0x1F);
            Wire.write(0x50);
            Wire.endTransmission();
          
            Wire.beginTransmission(ADDR);
            Wire.write(0x1F);
            Wire.write(0x45);
            Wire.endTransmission();
          
            Wire.beginTransmission(ADDR);
            Wire.write(0x1F);
            Wire.write(0x57);
            Wire.endTransmission();
          
            Wire.beginTransmission(ADDR);
            Wire.write(0x07);
            Wire.write(0x00);
            Wire.endTransmission();
          
            Wire.beginTransmission(ADDR);
            Wire.write(0x1F);
            Wire.write(0x00);
            Wire.endTransmission();
          }
          else if(freq == 3)  //Set the output Mode of the Grid-EYE to moving average
          {
          
            Wire.beginTransmission(ADDR);
            Wire.write(0x1F);
            Wire.write(0x50);
            Wire.endTransmission();
          
            Wire.beginTransmission(ADDR);
            Wire.write(0x1F);
            Wire.write(0x45);
            Wire.endTransmission();
          
            Wire.beginTransmission(ADDR);
            Wire.write(0x1F);
            Wire.write(0x57);
            Wire.endTransmission();
            
            Wire.beginTransmission(ADDR);
            Wire.write(0x07);
            Wire.write(0x20);
            Wire.endTransmission();
      
            Wire.beginTransmission(ADDR);
            Wire.write(0x1F);
            Wire.write(0x00);
            Wire.endTransmission();
          }
        }
        /*** termination of Serial ***/
        Serial.print("\r");
        Serial.print("\n");
    
        /*** delay for refresh of Grid-EYE data ***/
        delay(Maindelay);
      }
    
    }
    
    
    Troubleshooting

  • Connecting grid-eye sensor
    Cliff KarlssonC Cliff Karlsson

    I accidently ordered the wrong kind of sensor and got Grid-eye one wire instead of Grid-eye usb. The one I got have two RJ11-connectors and from what I understand uses onewire for communication. alt text
    Schematic

    Datasheet

    I tried to understand the schematic to determine if I could use the TPx connectors at the top to connect and found that TP6 is 1-wire out and TP1 looks like GND, but I do not understand where VCC should go.

    So my questions is
    1: can I connect it to arduino using onewire and the TPx connections, and how would I connect it in that case.
    2: Can I use a FTDI-adapter in some way to be able to connect it to a PC to use the windows-demo-software?

    It looks like you're supposed to use some kind of additional hardware or shield between the sensor and the arduino but is there some way to connect it directly?

    Troubleshooting

  • Help with sketch...
    Cliff KarlssonC Cliff Karlsson

    @BartE Thanks for the help but I can't get it to work. I Only get alot of radio errors:

    0 MCO:BGN:INIT NODE,CP=RNNNA--,VER=2.1.1
    3 TSM:INIT
    4 TSF:WUR:MS=0
    11 !TSM:INIT:TSP FAIL
    12 TSM:FAIL:CNT=1
    14 TSM:FAIL:PDT

    I also tried commenting out all mysensors stuff, but I got no reactions at al from leds or serial monitor.
    I am using a UNO with a separate 12v power supply attached so it can't be power related right?

    // Enable debug prints
    #define MY_DEBUG
    
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    
    #include <MySensors.h>
    #include <Bounce2.h>
    #include <SPI.h>
    #include <NewPing.h>
    
    #define DIGITAL_INPUT_SENSOR 3 
    #define CHILD_ID 1   // Id of the sensor child
    
    #define SONAR_NUM     2 // Number of sensors.
    #define MAX_DISTANCE 200 // Maximum distance (in cm) to ping.
    #define PING_INTERVAL 40 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).
    
    
    int ledPin = 4;
    
    // Initialize motion message
    MyMessage msg(CHILD_ID, V_TRIPPED);
    
    // Instantiate a Bounce object
    Bounce debouncer = Bounce(); 
    unsigned long distanceTimer = 0;
    #define DISTANCEMEASURETIME (10 * 1000)
    unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
    unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
    uint8_t currentSensor = 0;          // Keeps track of which sensor is active.
    int dirA = 0;
    int dirB = 0;
    
    int val = 0;
    #define BUTTON_PIN  1  // Arduino Digital I/O pin for button/reed switch
    int doorDistance = 65;
    
    boolean bigChange_0;  //SensorA
    boolean bigChange_1;  //SensorB
    
    NewPing sonar[SONAR_NUM] = {     // Sensor object array.
      NewPing(8, 7, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
      NewPing(6, 5, MAX_DISTANCE)
      
    };
    
    void setup()
    {
        pinMode(DIGITAL_INPUT_SENSOR, INPUT);      // sets the motion sensor digital pin as input
        // After setting up the button, setup the Bounce instance :
        debouncer.attach(DIGITAL_INPUT_SENSOR);
        debouncer.interval(5); // interval in ms
          Serial.begin(115200);
      pingTimer[0] = millis() + 75;           // First ping starts at 75ms, gives time for the Arduino to chill before starting.
      for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
        pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
    
         // Setup the button
      pinMode(BUTTON_PIN,INPUT);
      // Activate internal pull-up
      digitalWrite(BUTTON_PIN,HIGH);
    
    
    
       pinMode(ledPin, OUTPUT);  // declare LED as output
    }
    
    void presentation()
    {
        // Send the sketch version information to the gateway and Controller
        sendSketchInfo("Motion Sensor", "1.0");
    
        // Register all sensors to gw (they will be created as child devices)
        present(CHILD_ID, S_MOTION);
    }
    
    void loop()
    {
        // Check if the PIR sensor has been changed
        if (debouncer.update()) {
           // Read digital motion value
           bool tripped = (debouncer.read() == HIGH);
    
           Serial.println(tripped);
         //  send(msg.set(tripped?"1":"0"));  // Send tripped value to gw
           if (tripped) {
              distanceTimer = millis() + DISTANCEMEASURETIME;
           }
        }
    
        // Check if we need to measure distance
        if (distanceTimer > 0) {
           if (millis() > distanceTimer) {
               // No times up stop reset the timer
               distanceTimer = 0;
           }  else {
    
                 for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
        if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
          pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
          if (i == 0 && currentSensor == SONAR_NUM - 1) oneSensorCycle(); // Sensor ping cycle complete, do something with the results.
          sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
          currentSensor = i;                          // Sensor being accessed.
          cm[currentSensor] = 0;                      // Make distance zero in case there's no ping echo for this sensor.
          sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
        }
      }
      // Other code that *DOESN'T* analyze ping results can go here.
      val = digitalRead(BUTTON_PIN);  // read input value
      if (val == HIGH) {         // check if the input is HIGH (button released)
        digitalWrite(ledPin, LOW);  // turn LED OFF
      } else {
        digitalWrite(ledPin, HIGH);  // turn LED ON
        
        int measure = (int)cm[0];
        if(measure != doorDistance && measure != 0){
           Serial.print(measure);
           Serial.println();
           doorDistance = measure;
           
          }
       
      }
           
           }
        }
    }
    
    void echoCheck() { // If ping received, set the sensor distance to array.
      if (sonar[currentSensor].check_timer())
        cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
    }
    
    void oneSensorCycle() { // Sensor ping cycle complete, do something with the results.
      
      bigChange_0 = ((doorDistance-(int)cm[0]) > 10)?true:false;
      bigChange_1 = ((doorDistance-(int)cm[1]) > 10)?true:false;
    
      if(bigChange_0 && bigChange_1){
     
          if(dirA > dirB){
              Serial.print("Entering Room");
              Serial.println();
              dirA = 0;
              dirB = 0;
            }
            else if(dirA < dirB){
              Serial.print("Leaving Room");
              Serial.println();
              dirA = 0;
              dirB = 0;
              }
            else{
              dirA = 0;
              dirB = 0;
              }  
        }
      else if(bigChange_0){
          dirA=1;
      }
      else if(bigChange_1){
         dirB=1;
        }
      else {
        dirA = 0;
        dirB = 0;
        }
      }
    
    Troubleshooting

  • Help with sketch...
    Cliff KarlssonC Cliff Karlsson

    This is what I want to do:
    when motionsensor is triggered run distance-sensors for 10 seconds and then sleep.

    I think I have most of the parts working but I am struggeling with how to combine all the sketches. I have tried several times and think I managed to combine the first two at one time. But then everything just stoped working after trying to add the timer part.

    This is the distance-sensor-sketch which kind of works most of the time (And is just supposed to tell if I someone enters or leaves a room :

    #include <NewPing.h>
    #include <Bounce2.h>
    #include <SPI.h>
    
    #define SONAR_NUM     2 // Number of sensors.
    #define MAX_DISTANCE 200 // Maximum distance (in cm) to ping.
    #define PING_INTERVAL 40 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).
    
    
    int ledPin = 4;
    //Bounce debouncer = Bounce(); 
    //int oldValue=-1;
    
    unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
    unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
    uint8_t currentSensor = 0;          // Keeps track of which sensor is active.
    int dirA = 0;
    int dirB = 0;
    
    int val = 0;
    #define BUTTON_PIN  3  // Arduino Digital I/O pin for button/reed switch
    int doorDistance = 65;
    
    boolean bigChange_0;  //SensorA
    boolean bigChange_1;  //SensorB
    
    NewPing sonar[SONAR_NUM] = {     // Sensor object array.
      NewPing(8, 7, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
      NewPing(6, 5, MAX_DISTANCE)
      
    };
    
    void setup() {
      Serial.begin(115200);
      pingTimer[0] = millis() + 75;           // First ping starts at 75ms, gives time for the Arduino to chill before starting.
      for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
        pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
    
         // Setup the button
      pinMode(BUTTON_PIN,INPUT);
      // Activate internal pull-up
      digitalWrite(BUTTON_PIN,HIGH);
    
    
    
       pinMode(ledPin, OUTPUT);  // declare LED as output
    }
    
    void loop() {
      for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
        if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
          pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
          if (i == 0 && currentSensor == SONAR_NUM - 1) oneSensorCycle(); // Sensor ping cycle complete, do something with the results.
          sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
          currentSensor = i;                          // Sensor being accessed.
          cm[currentSensor] = 0;                      // Make distance zero in case there's no ping echo for this sensor.
          sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
        }
      }
      // Other code that *DOESN'T* analyze ping results can go here.
      val = digitalRead(BUTTON_PIN);  // read input value
      if (val == HIGH) {         // check if the input is HIGH (button released)
        digitalWrite(ledPin, LOW);  // turn LED OFF
      } else {
        digitalWrite(ledPin, HIGH);  // turn LED ON
        
        int measure = (int)cm[0];
        if(measure != doorDistance && measure != 0){
           Serial.print(measure);
           Serial.println();
           doorDistance = measure;
           
          }
       
      }
         
         // Send in the new value
        // send(msg.set(value==HIGH ? 1 : 0));
    }
    
    void echoCheck() { // If ping received, set the sensor distance to array.
      if (sonar[currentSensor].check_timer())
        cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
    }
    
    void oneSensorCycle() { // Sensor ping cycle complete, do something with the results.
      
      bigChange_0 = ((doorDistance-(int)cm[0]) > 10)?true:false;
      bigChange_1 = ((doorDistance-(int)cm[1]) > 10)?true:false;
    
      if(bigChange_0 && bigChange_1){
     
          if(dirA > dirB){
              Serial.print("Entering Room");
              Serial.println();
              dirA = 0;
              dirB = 0;
            }
            else if(dirA < dirB){
              Serial.print("Leaving Room");
              Serial.println();
              dirA = 0;
              dirB = 0;
              }
            else{
              dirA = 0;
              dirB = 0;
              }  
        }
      else if(bigChange_0){
          dirA=1;
      }
      else if(bigChange_1){
         dirB=1;
        }
      else {
        dirA = 0;
        dirB = 0;
        }
      }
    

    This is the standard motion-sensor-sketch:

    // Enable debug prints
    // #define MY_DEBUG
    
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    
    #include <MySensors.h>
    
    unsigned long SLEEP_TIME = 120000; // Sleep time between reports (in milliseconds)
    #define DIGITAL_INPUT_SENSOR 3   // The digital input you attached your motion sensor.  (Only 2 and 3 generates interrupt!)
    #define CHILD_ID 1   // Id of the sensor child
    
    // Initialize motion message
    MyMessage msg(CHILD_ID, V_TRIPPED);
    
    void setup()
    {
        pinMode(DIGITAL_INPUT_SENSOR, INPUT);      // sets the motion sensor digital pin as input
    }
    
    void presentation()
    {
        // Send the sketch version information to the gateway and Controller
        sendSketchInfo("Motion Sensor", "1.0");
    
        // Register all sensors to gw (they will be created as child devices)
        present(CHILD_ID, S_MOTION);
    }
    
    void loop()
    {
        // Read digital motion value
        bool tripped = digitalRead(DIGITAL_INPUT_SENSOR) == HIGH;
    
        Serial.println(tripped);
        send(msg.set(tripped?"1":"0"));  // Send tripped value to gw
    
        // Sleep until interrupt comes in on motion sensor. Send update every two minute.
        sleep(digitalPinToInterrupt(DIGITAL_INPUT_SENSOR), CHANGE, SLEEP_TIME);
    }
    

    And this is the blink_without_delay-sketch from the arduino site which uses a timer:

    // Generally, you should use "unsigned long" for variables that hold time
    // The value will quickly become too large for an int to store
    unsigned long previousMillis = 0;        // will store last time LED was updated
    
    // constants won't change :
    const long interval = 10000;           // interval at which to blink (milliseconds)
    
    void setup() {
      // set the digital pin as output:
      pinMode(ledPin, OUTPUT);
    }
    
    void loop() {
      // here is where you'd put code that needs to be running all the time.
    
      // check to see if it's time to blink the LED; that is, if the
      // difference between the current time and last time you blinked
      // the LED is bigger than the interval at which you want to
      // blink the LED.
      unsigned long currentMillis = millis();
    
      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;
    
        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }
    
        // set the LED with the ledState of the variable:
        digitalWrite(ledPin, ledState);
      }
    }
    
    Troubleshooting

  • 💬 Button size radionode with sensors swarm extension
    Cliff KarlssonC Cliff Karlsson

    If possible I would also like the option to chose 868 Mhz or be able to buy board without radio.

    OpenHardware.io atsha204a flash humidity rf69 light uv light battery mysensor temperature ota

  • 💬 Motion Sensor
    Cliff KarlssonC Cliff Karlsson

    I have never used timers but I looked at the blink without delay sketch from the arduino website. Do I replace the if -statement with a while loop?

    const int ledPin =  LED_BUILTIN;// the number of the LED pin
    
    // Variables will change :
    int ledState = LOW;             // ledState used to set the LED
    
    // Generally, you should use "unsigned long" for variables that hold time
    // The value will quickly become too large for an int to store
    unsigned long previousMillis = 0;        // will store last time LED was updated
    
    // constants won't change :
    const long interval = 1000;           // interval at which to blink (milliseconds)
    
    void setup() {
      // set the digital pin as output:
      pinMode(ledPin, OUTPUT);
    }
    
    void loop() {
      // here is where you'd put code that needs to be running all the time.
    
      // check to see if it's time to blink the LED; that is, if the
      // difference between the current time and last time you blinked
      // the LED is bigger than the interval at which you want to
      // blink the LED.
      unsigned long currentMillis = millis();
    
      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;
    
        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }
    
        // set the LED with the ledState of the variable:
        digitalWrite(ledPin, ledState);
      }
    }
    
    Announcements

  • 💬 Motion Sensor
    Cliff KarlssonC Cliff Karlsson

    If I want something to run for 10 seconds after a motion have been detected, how would I make this happend?

    Announcements

  • Troubleshooting sketch
    Cliff KarlssonC Cliff Karlsson

    I am trying to use two ultrasonic-sensors and one PIR with this sketch but I get this error:

    PIR_dual_ultrasonic_sensor:49: error: 'getConfig' was not declared in this scope
    
       metric = getConfig().isMetric;
    
                          ^
    
    exit status 1
    'getConfig' was not declared in this scope
    

    Can anyone tell me what I am doing wrong?

    
    // Enable debug prints
    #define MY_DEBUG
    #define MY_BAUD_RATE 115200
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    
    #include <NewPing.h>
    #include <MySensors.h>
    #include <SPI.h>
    
    #define SONAR_A_CHILD_ID 1
    #define SONAR_B_CHILD_ID 2
    #define MOTION_A_CHILD_ID 3
    
    
    #define SONAR_A_TRIGGER_PIN  6  // Arduino pin tied to trigger pin on the ultrasonic sensor.
    #define SONAR_A_ECHO_PIN     5  // Arduino pin tied to echo pin on the ultrasonic sensor.
    #define MOTION_A_TRIGGER_PIN  2
    
    #define SONAR_B_TRIGGER_PIN  8  // Arduino pin tied to trigger pin on the ultrasonic sensor.
    #define SONAR_B_ECHO_PIN     7  // Arduino pin tied to echo pin on the ultrasonic sensor.
    
    #define MAX_DISTANCE 300 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
    unsigned long SLEEP_TIME = 200; // Sleep time between reads (in milliseconds)
    
    unsigned long MOTION_SLEEP_TIME = 120000; // Sleep time between reports (in milliseconds)
    #define INTERRUPT MOTION_A_TRIGGER_PIN-2 // Usually the interrupt = pin -2 (on uno/nano anyway)
    
    
    
    NewPing sonar_A(SONAR_A_TRIGGER_PIN, SONAR_A_ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
    NewPing sonar_B(SONAR_B_TRIGGER_PIN, SONAR_B_ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
    
    
    MyMessage SONAR_A_msg(SONAR_A_CHILD_ID, V_DISTANCE);
    int SONAR_A_lastDist;
    
    MyMessage SONAR_B_msg(SONAR_B_CHILD_ID, V_DISTANCE);
    int SONAR_B_lastDist;
    
    MyMessage MOTION_A_msg(MOTION_A_CHILD_ID, V_TRIPPED);
    
    boolean metric = true; 
    
    void setup()  
    { 
      metric = getConfig().isMetric;
      pinMode(MOTION_A_TRIGGER_PIN, INPUT);      // sets the motion sensor digital pin as input
    }
    
    void presentation() {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("Distance+Motion Sensor", "1.0");
    
      // Register all sensors to gw (they will be created as child devices)
      present(SONAR_A_CHILD_ID, S_DISTANCE);
      present(SONAR_B_CHILD_ID, S_DISTANCE);
      present(MOTION_A_TRIGGER_PIN, S_MOTION);
    }
    
    void loop()      
    {     
      
      boolean tripped = digitalRead(MOTION_A_TRIGGER_PIN) == HIGH; 
      
        
      Serial.println(tripped);
      send(MOTION_A_msg.set(tripped?"1":"0"));  // Send tripped value to gw 
     
     if(tripped)  {
      unsigned long time = millis()+30000;
      while (millis() < time){
          int SONAR_A_dist = metric?sonar_A.ping_cm():sonar_A.ping_in();
          Serial.print("Ping Sonar A: ");
          Serial.print(SONAR_A_dist); // Convert ping time to distance in cm and print result (0 = outside set distance range)
          Serial.println(metric?" cm":" in");
    
      if (SONAR_A_dist != SONAR_A_lastDist) {
          send(SONAR_A_msg.set(SONAR_A_dist));
          SONAR_A_lastDist = SONAR_A_dist;
          }
      
      wait(100);
    
          int SONAR_B_dist = metric?sonar_B.ping_cm():sonar_B.ping_in();
          Serial.print("Ping Sonar B: ");
          Serial.print(SONAR_B_dist); // Convert ping time to distance in cm and print result (0 = outside set distance range)
          Serial.println(metric?" cm":" in");
    
      if (SONAR_B_dist != SONAR_B_lastDist) {
          send(SONAR_B_msg.set(SONAR_B_dist));
          SONAR_B_lastDist = SONAR_B_dist;
          }
      
      }
      sleep(SLEEP_TIME);
    }
                
    //else{
      // Sleep until interrupt comes in on motion sensor. Send update every two minute. 
      sleep(INTERRUPT,CHANGE, MOTION_SLEEP_TIME);
    //}
    }
    
    Troubleshooting

  • Easy arduino with 5v sensors and 3.3v radio?
    Cliff KarlssonC Cliff Karlsson

    I need to build a node which uses 5v sensors only (Ultrasonic and PIR) and want to know what the easiest way to connect a radio is.

    I know that there is a adapter for the "old" through hole NRF2401+ which can be powered using 5v. But I would like to use RFM69 or smd version of NRF2401+. Is there any existing shields or adapters that could be used with a mini pro 5v or a arduino nano.

    Or maybe any premade arduinos with the same features?

    General Discussion
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • MySensors
  • OpenHardware.io
  • Categories
  • Recent
  • Tags
  • Popular