text:
Arduino ESP8266 Wifi Shield GET request with LiteESP8266Client stops after few HTTP request
Below HTTP Get request is working but after few GET request(5-6) the code stops and once I press Arduino reset button then only it start working. Probably looks like something is causing OOM:
// This is a demo example using a public http server for testing both GET and POST requests

#include <Arduino.h>
#include <LiteESP8266Client.h>

#define PACKET_MTU 1500    // Standard network MTU is 1500 bytes

LiteESP8266 radio;

const char ssid[] PROGMEM = "abcd";    //change it to your wifi SSID
const char password[] PROGMEM = "abcd";    //change it to your wifi password
const char host[] PROGMEM = "192.168.0.156";
const int port = 8080;

const char http_get_request[] PROGMEM = "GET /getLedStatus HTTP/1.1\r\n";
const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
const char http_host[] PROGMEM = "Host: 192.168.0.156\r\n";
const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
const char http_content_length_header[] PROGMEM = "Content-Length: ";
const char success[] PROGMEM = "success";
const char failed[] PROGMEM = "failed";
const char CRLF[] PROGMEM = "\r\n";
const char error_data_null[] PROGMEM = "Error: data came back null.";
const int ledPin=11;
void setupStationMode() {
  Serial.print("Setup station mode... ");
  if (radio.set_station_mode()) {
    Serial.println("success");
  } else {
    Serial.println("failed");
  }
}

void joinAP() {
  Serial.print("Join AP ");
  Serial.print("... ");
  if (radio.connect_to_ap(ssid, password)) {
    Serial.println("Success");
  } else {
    Serial.println("Failed");
  }
}

void establishTcpConnect() {
  Serial.print("Establish TCP Connection... ");
  if (radio.connect_progmem(host, port)) {
    Serial.println( "Success");
  } else {
    Serial.println( "Failed");
  }
}

void getHttpPacket() {
  char *data;
  while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
    if (data) {
      Serial.println("Response Received...");
      Serial.println(data);
      if(strstr(data, "ON") != NULL) {
        digitalWrite(ledPin, HIGH);
      }else{
        digitalWrite(ledPin, LOW);
      }
    } else {
      Serial.println(error_data_null);
    }
  }
  free(data);
}

void httpGet() {
  Serial.println("Sending GET request... ");
  radio.send_progmem(http_get_request);
  radio.send_progmem(http_useragent);
  radio.send_progmem(http_host);
  radio.send_progmem(http_close_connection);
}
void setup() {
  delay(2000);
  pinMode(ledPin, OUTPUT);
  radio.begin(9600,2,3);
  Serial.begin(9600);
  while (!Serial) {};

  setupStationMode();
  joinAP();
}

void loop() {
  establishTcpConnect();

  httpGet();
  getHttpPacket();
  }

Complete OUTPUT(See Last TCP call when it stopped):
Setup station mode... success
Join AP ... Success
Establish TCP Connection... Success
Sending GET request...
Response Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 3
Date: Fri, 07 Aug 2020 13:47:47 GMT
Connection: close

OFF
Establish TCP Connection... Success
Sending GET request...
Response Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 3
Date: Fri, 07 Aug 2020 13:47:53 GMT
Connection: close

OFF
Establish TCP Connection... Success
Sending GET request...
Response Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 3
Date: Fri, 07 Aug 2020 13:47:58 GMT
Connection: close

OFF
Establish TCP Connection... Success
Sending GET request...
Response Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 3
Date: Fri, 07 Aug 2020 13:48:04 GMT
Connection: close

OFF
Establish TCP Connection... Success
Sending GET request...
Response Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 3
Date: Fri, 07 Aug 2020 13:48:10 GMT
Connection: close

OFF
Establish TCP Connection... Success
Sending GET request...
Response Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 2
Date: Fri, 07 Aug 2020 13:48:16 GMT
Connection: close

ON
Establish TCP Connection... Success
Sending GET request...
Response Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 2
Date: Fri, 07 Aug 2020 13:48:21 GMT
Connection: close

ON
Establish TCP Connection... Success
Sending GET request...
Response Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 2
Date: Fri, 07 Aug 2020 13:48:27 GMT
Connection: close

ON
Establish TCP Connection... Success
Sending GET request...
Response Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 2
Date: Fri, 07 Aug 2020 13:48:33 GMT
Connection: close

ON
Establish TCP Connection... Success
Sending GET request...
Establish TCP Connection...

Probably looks like memory is not getting freed. I am using Arduino UNO + ESP8266 sheild
Update 2
Tried with other REST Server and same issue is observed:
// This is a demo example using a public http server for testing both GET and POST requests

#include <Arduino.h>
#include <LiteESP8266Client.h>

#define PACKET_MTU 1500    // Standard network MTU is 1500 bytes

LiteESP8266 radio;

const char ssid[] PROGMEM = "abc";    //change it to your wifi SSID
const char password[] PROGMEM = "abc";    //change it to your wifi password
const char host[] PROGMEM = "httpbin.org";
const int port = 80;

const char http_get_request[] PROGMEM = "GET /get HTTP/1.1\r\n";
const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
const char http_host[] PROGMEM = "Host: httpbin.org\r\n";
const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
const char http_content_length_header[] PROGMEM = "Content-Length: ";
const char success[] PROGMEM = "success";
const char failed[] PROGMEM = "failed";
const char CRLF[] PROGMEM = "\r\n";
const char error_data_null[] PROGMEM = "Error: data came back null.";
const int ledPin=11;
void setupStationMode() {
  Serial.print("Setup station mode... ");
  if (radio.set_station_mode()) {
    Serial.println("success");
  } else {
    Serial.println("failed");
  }
}

void joinAP() {
  Serial.print("Join AP ");
  Serial.print("... ");
  if (radio.connect_to_ap(ssid, password)) {
    Serial.println("Success");
  } else {
    Serial.println("Failed");
  }
}

void establishTcpConnect() {
  Serial.print("Establish TCP Connection... ");
  if (radio.connect_progmem(host, port)) {
    Serial.println( "Success");
  } else {
    Serial.println( "Failed");
  }
}

void getHttpPacket() {
  char *data;
  while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
    if (data) {
      Serial.println("Response Received...");
      Serial.println(data);
      if(strstr(data, "ON") != NULL) {
        digitalWrite(ledPin, HIGH);
      }else{
        digitalWrite(ledPin, LOW);
      }
    } else {
      Serial.println(error_data_null);
    }
  }
  free(data);
}

void httpGet() {
  Serial.println("Sending GET request... ");
  radio.send_progmem(http_get_request);
  radio.send_progmem(http_useragent);
  radio.send_progmem(http_host);
  radio.send_progmem(http_close_connection);
}
void setup() {
  delay(2000);
  pinMode(ledPin, OUTPUT);
  radio.begin(9600,2,3);
  Serial.begin(9600);
  while (!Serial) {};

  setupStationMode();
  joinAP();
}

void loop() {
  establishTcpConnect();

  httpGet();
  getHttpPacket();
  }

Output:
Setup station mode... success
Join AP ... Success
Establish TCP Connection... Success
Sending GET request...
Response Received...
HTTP/1.1 200 OK
Date: Fri, 07 Aug 2020 13:57:45 GMT
Content-Type: application/json
Content-Length: 238
Connection: close
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

Response Received...
{
  "args": {},
  "headers": {
    "Host": "httpbin"origin": "106.51.29.214",
  "url": "http://httpbin.org/get"
}
CLOSED
⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮
Establish TCP Connection... Success
Sending GET request...
Response Received...
HTTP/1.1 200 OK
Date: Fri, 07 Aug 2020 13:57:57 GMT
Content-Type: application/json
Content-Length: 238
Connection: close
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

Response Received...
{
  "args": {},
  "headers": {
    "Host": "httpbin"origin": "106.51.29.214",
  "url": "http://httpbin.org/get"
}
CLOSED
⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮
Establish TCP Connection... Success
Sending GET request...
Establish TCP Connection...

Server side code
package com.test.iot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
    private String ledStatus="OFF";
    @RequestMapping("/test")
    public String index() {
        logger.info("invoked");
        return "Greetings from Spring Boot!";
    }
    @RequestMapping("/getLedStatus")
    public String getLedStatus() {
        logger.info("ledStatus");
        return ledStatus;
    }
    @RequestMapping("/toggleLedStatus")
    public String toggleLedStatus(){
        if(ledStatus.equals("ON")){
            ledStatus="OFF";
        } else {
            ledStatus="ON";
        }
        return String.format("New LED Status: %s", ledStatus);
    }
}

What is your server code? The cause could be on the server side instead of client side. Also do you run the client using a public-facing test server such as httpbin.org as in the example to see if you are facing the same problem?

Yup same issue observed in example . Response attached here

Server side code attached

If you faced the same problem on both servers, then there is something wrong with the client, I will take a look tomorrow as I need to re-flash my esp-01 to do the test.

Could you add a delay in the loop to see if there is any difference?

Will do that to check and will let you know but I doubt this will help. Kindly do flash ESP01 and help with the fix if any required. Thank you

a funny library. it uses malloc with the size of the response. it fragments the heap  5 loops fast. btw: you allow it to allocate 5000 bytes on an MCU with 2kB RAM

Is there anyway to fix, like read line by line and discard not required stuff?? Any code snippet will be helpful to me. Thanks

I can only recommend me WiFiEspAT library. but you would have to flash a newer AT firmware to esp8266 https://github.com/jandrassy/WiFiEspAT/blob/master/README.md

@Juraj, 5000 is the timeout in ms, not the memory allocation.

@hcheung any idea  if it can be fixed soon? Juraj how is this new approach different from old one? Any reason to flash new firmware?

I just want to parse the response, my response size will also be very small like 1-2 word. I have been changing approaches from quite sometime now and to get it working till this step was tough, had to adjust the baud rate to get it working. If you can provide some more information about new firmware and how that is different from the one then that will be helpful.

There is a bug on the library example webclient.ino on getHttpPacket() and getHttpResponse() that it didn't free the memory correctly, causing memory leak. I've updated the code on github repo.
Specifically on your getHttpPacket(), here is the corrected code:
void getHttpPacket() {
  char *data;
  while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
    if (data) {
      Serial.println(F("Response Received..."));
      Serial.println(data);
      if(strstr(data, "ON") != NULL) {
        digitalWrite(ledPin, HIGH);
      }else{
        digitalWrite(ledPin, LOW);
      }
      free(data);  // free the memory in every packet as Arduino does not have enough memory
    } else {
      Serial.println(error_data_null);
    }
  }
  // free(data);
}

If you have further issue regarding the library, you can raise an "issue" on the github, and I will take a look.

Awsome I will take latest code from github

BTW, as I mostly use stm32 for my works, I can afford to allocate memory that is equal to one packet MTU (i.e. 1500 bytes), if you are using Arduino, this will leave very little memory for your sketch, although LiteESP8266Client library is designed to utilise very little SRAM, if you found that you need more memory, you can redefine PACKET_MTU to smaller number. It is also better to wrap the string literal with F() macro to keep it in flash.

Many thanks @hcheung. Working like a charm..so far..touch wood


text:
printing the analogRead() functions result crashes Arduino
I have created a curcuit which reads the analog pin 3 auf the arduino nano and does other things dependant on the returned value. However I have problems regarding the analogRead() function. Whenever I use a piece of wire to short the "Analog_UpDownHorn_Signal" and do it fast paced so that the arduino reads 0V and 5V repeatedly the serial communication stops. Sometimes it resumes. Sometimes it doesn't and when it does the value is always 1023.
I have managed to reduce the problem to the following 2 lines of code, which leads me to believe its my curcuit or a bug in the functions used. Before the arduino gets stuck it sometimes puts out random '?' or other wierd characters on the serial monitor.
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  Serial.println(analogRead(A3));
}

Few comments, does adding a delay in the loop of ~100ms help? Have you tried writing the value of A3 to a variable then printing the variable instead of nesting that in the print command? Can you confirm the Arduino is getting a stable 5V supply? Are other parts of a circuit connected to the Arduino still?

The delay didn't help. Writing the value to a variable and printing it didn't help. I can confirm a stable 5V supply, i checked it. Also something noteworthy: when I use a resistor for example a 1kOhm the values (~512)  are correct no glitches or anything. Only when i short the signal to ground these problems appear.

Add a Serial.println("setup") to the setup function so you see when the arduino resets

The capacitor you have is rather large on the Analogue input, normally at this position it would be for debounce. Try something in the range of 100nF. Another idea would be to increase R8 to 10k.
https://www.g7smy.co.uk/2015/09/multiple-buttons-on-one-pin-with-an-arduino/

I have fixed the issue by connecting the two grounds on the opposite site of the arduino nano with a thick solder connection on the bottom side of my perfboard. Seems like it really had to do with the big capacitance an the rapid discharge when shorting it to ground.
Maybe it had a "charge pump" like effect  with decoupling cap and the debouncing cap, because those are on the same side of the board.
To further avoid this problem i will not short the cap an discharge it through a low ohm resistor. Furthermore i could lower the capacitance as it was stated before and up the resistor values.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Detecting different objects closeness
iam currently working on a new project, where i would like to detect the existence/closeness of several objects around the arduino up to like 1 meter. I was thinking about an rfid setup, but as the objects could have different sizes like 5 centimetre tall and only 3 centimetre wide, i think this won't work for the max distance. I was also thinking about a ble beacon, but as this one has to be activley powered all the time, it wouln't be the perfect solution. As the base could be fully customized, it may have some kind of sensors/wires overall the surface, but iam a bit lacking of a good idea for this.
I hope someone might had a similar setup, or a good idea to go.
PS: When i think about it twice, it would be better, if it can be differentiate between some areas within the one meter and the different objects, entering each area. I've added some image, hope this helps to understand, what i want to archive at the end.

Thank you and greetings,
Sebastian

why would an RFID solution be dependent on object size?

hey @jsotola thanks for the feedback, yes my mistake, just had a quick view into rfid setups and thought it  have some dependency for the range, but just the reader seems to be a bit more expensive. But when i think about it twice, it would be better, if it can be differentiate between some areas within the one meter and the different objects, entering each area. I have added some image, hope this helps to understand, what i really want to archive. Thanks a lot!

The image confuses me. Why have you put the map of germany under your Arduino there? What are you trying to achieve? As you may have noticed, measuring the position (in this case with direction and distance) of multiple objects is not an easy task. A description of what you are actually trying to build might give us better information to suggest a fitting solution

@chrisl it should be a smart table top game and in this case "germany" just represents the field and in different areas should different situations recognized as soon as a object (character) enters the different areas

I want to detect specific small objects, which could be moved around in specific areas (one square meter), so not a "just detect somthing in front of xyz" and also not "depending on the range" detection. Does any has a suggestion so far? Thanks and Greetings,
Sebastian

As you might have already seen, a position sensing system can be really complex. Here I will list some possibilities, that come to my mind and might be fitting for your case or not.

Matrix based solutions: Here I mean sensors a some sort arranged in a matrix underneath the game table, which can sense the object placed on them. As you know from your wiring, where a specific sensor is located, you know from the triggered sensor, where the object was placed. The resolution directly corresponds to the numbers of sensors, that you place. You can use different sensors, which will give you different information, but are also very different in handling and costs:

Reed switches and magnets on the bottom of the objects. The magnet on the object would close the reed switch. A read switches are rather cheap (have seen 40 pieces for about 10€ on amazon; on aliexpress or others you might get them even cheaper) and can be easily placed in an electrical matrix or (depending on the number and places of object at any time) checked via shift registers, which are also not very pricey.

Hall sensors and magnets on the bottom of the objects. You would measure the magnetic field of the magnets with the hall sensors. You could use different magnet strengths to get different readings and thus directly distinguish between different object types. The hall sensors will be not that easy to read. Mostly they have an analog output, thus you would need extra ADCs and multiplexers to read them all.

RFID readers and RFID chips in each object. Very pricey and rather low resolution. Also very difficult to read from all of them with the Arduino. But you could go for the reed switch version and use a single RFID reader to first tell the Arduino, which object you are placing. In the game you would first hold the object to the reader, then place it on the board.

Lidar system: A Lidar scanner could scan over your board (it measures the distance in a circle around it). Each object would be a negative peak in the measured distance distribution. From the angle and the distance, you could calculate the position on the board. Though you would need to carefully place the sensor, as one object might hide the other behind it. You can tackle that with an additional Lidar scanner, but the processing will also be rather complex. And Lidar scanners are rather expensive.

Ultrasonic sensors out the board: If you place enough ultrasonic sensors around the board and measure with one after the other, you might also get fitting results. But I would guess, that you won't get good positioning results with them, especially for the rather small objects and distances used on a game table.

Computer Vision: Away from Arduino you could use OpenCV on a Raspberry Pi together with a small camera above your board to detect objects. General object detecting is rather easy with OpenCV and python; getting it's position in the camera image is trivial then (from where you can calculate the position on the board easily). With more work it should also be possible to detect the object themselves (meaning distinguishing between different objects). We might need to train OpenCV with top-down images of the objects for that. If you don't get good results with the normal camera mode, you could try the IR camera mode (by removing the IR filter of the Pi's camera) and put some good IR reflective stuff on the top of the objects. Then OpenCV only has to find the bright spots in the image. All that is possible, though I cannot help you with that and also it is off-topic on this site.

If you can have a board with fixed positions, you could make direct electrical connections between the objects and the board. Though that means, that you would have metal contacts all over the board. I recently used such electrical connections to distinguish between different objects, which can be put into a small number of bays. I have 7 pins on each object, one of them ground. On the object I connected some of the other pins to the ground pin to create a binary pattern. The pins of each bay get read by a shift-in register. All registers are chained together and connected to the Arduino with a total of 4 pins.

Depending on your needs you could combine some of these options. I would try the OpenCV solution, or alternatively the reed switch with one RFID reader solution.

You should use the HC-SR0 ultrasonic sensor. It has good accuracy and range. If you don't want to use that, you can use an infrared distance sensor. If these don't work, please tell me why.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Can we control other servos with common servo code Arduino
I am trying to control MG996R using code for a typical servo (SG90)
I used an external power supply, 5V,2A
I connected the servo signal line to Arduino slot 7,
servo positive to external power supply positive,
servo ground to external power supply ground,
while leaving the Arduino power supply and ground unconnected.
I tried the below code.
it works for SG90, while MG996R is not moving at all.

#include <Servo.h>
Servo myservo;

void setup()
{
  myservo.attach(7);  //pin 7 is the one control servo

}

void loop()
{

  for (int pos=0; pos<=60; pos++)
  {
    myservo.write(pos);
    delay(15);
  }

}

Is it because the different servos need different code?

the two servos use the same control signal ... if one works, then the other should work also ... recheck your power and ground connections ... make sure that servo ground is connected to arduino ground ... confirm that the power supply stays at 5 V under load ... measure the voltage while trying to move the servo ... if the voltage holds at 5 V, then the servo is suspect

there is no reason to have a for loop ... all you need is myservo.write(45); delay(1000); myservo.write(135); delay(1000); ... the servo will cycle between those two angles

They work with same control signal, so the same code should work for both of them
You need make sure the ground of servo is both connected with the Arduino ground and the power supply ground (power supply ground for power supply positive, Arduino ground for the signal line)
I think SG90 worked even not connecting the Arduino ground is because the difference in design.
But you should always connect Servo ground to the Arduino ground.

I note on the manufacturers website for the MG996R that it has an operating voltage of 4.8V to 6.6V.
Your problem could be that your voltage (at the motor) is below the minimum voltage of 4.8V.
Try driving the motor with 6V.
Also make sure you are testing the motor with no load connected to the output.

@jsotola's comment is the answer, so I'll just quote it here:

the two servos use the same control signal ... if one works, then the other should work also ... recheck your power and ground connections ... make sure that servo ground is connected to arduino ground ... confirm that the power supply stays at 5 V under load ... measure the voltage while trying to move the servo ... if the voltage holds at 5 V, then the servo is suspect

Also, make sure you're using the pin you set with myservo.attach(). Your comment says pin 9 but your code says pin 7, which is confusing. This code is using pin 7 as the servo signal:

myservo.attach(7);  //pin 9 is the one control servo

The operating current (running current for the MG996R (~650 mA) is higher than SG90 (~220 mA) but definitely well in the capacity of a 5 V, 2 A. Unless there is a mechanical load on the servo motor, the motor is not limited by the current supply.

The MG996R is a power beast. it is good idea to consider rechecking the supply voltage as well as trying with the supply greater than ~5 V.
PS: The code is definitely fine.
Here is the simulation for the code you have posted which works fine with an emulator


text:
Why does the LEDs affect Analog Input?
So I'm working for a project to control RGB Led Strip using microphone or sound sensor with Arduino Nano. I'm using 5050 RGB Led Strip around 120 LEDs, and I control them using simple transistor circuit to each channel R, G, and B, then I connect the base of the transistors to the resistors and PWM Outputs of the Arduino. And then I'm using KY-038 Sound Sensor (I'm using the Analog Output pin) and connect it to Arduino A0.
The problem is when I didn't connect the LEDs, the microphone worked correctly. I processed the analog input, put filter and threshold. When I connected the LEDs, the reading of the A0 is disturbed by the transition of the LED (for example from 0% PWM to 50% PWM or ON). As the result, my analog read detected it as a voltage swing and recognize it as a sound, and trigger the LEDs, then oscillating without any external sound. If I disconnected the LEDs, it worked correctly, for example I change it to Arduino Built-In LED, it turned on according to the external sound.
Why does this happen? I don't think they share the same timer, and I also use proper Power Supply and Capacitor to provide the enough power.
My project is similar to this project.

try using mosfets instead of bjt; they don't draw any/(ok, as much) current from the MCU.

I think it is because of power consumption.
If the LEDs consume lots of power, the LED on Arduino(typically mini red LED) will be off or faded.
So before you connect the  LEDs, check the  mini red LED which is on Arduino and after connection the LEDs, check ones again.
If the red LED is faded or off, the problem must be power consumption.
Connect 12v or 5v to vin to powering the Arduino, and also to LEDs
The important thing is you should not connect LEDs to Arduino 5v.

Which model of LED are you using? 5050 is just the form factor. However, I think the problem is related to power consumption. The well-known WS2812B (a.k.a. Neopixel from Adafruit), may consume about 50mA. Considering 120LEDs, you can reach an important level of current (circuit supporting more than 1A should be properly designed). The sudden change of current can easily change introduce noise on the entire circuit. The solution should use an external power supply dedicated for LED, sharing GND with your Arduino.

Not the WS2812B, only RGB LED 5050 with current limiting resistor, so it only has 4 pin for common anode, R, G, and B. I'm using 5v Power Supply with maximum 2A I believe, and I added Capacitor 100uF (didn't calculate this, only hope that it works, but it didn't). So the connection is from PC (for Serial Monitor) to Mini USB, and then VIN to 5V Power Supply. Does the use of breadboard also affect this?

Try removing the 5V from the power supply from the VIN pin. 5V is too low a voltage for the linear regulator anyway. And you already provide 5V via USB.

Yes Vin should be between 6-12V, otherwise, the regulator cannot work


text:
interrupt pin of attiny85 unstable
I'm trying to learn how to program a MC, so maybe I didn't know much about a MC. I tried to test interrupt pin of ATtiny85 with this simple code
#include <avr/io.h>
#include <avr/interrupt.h>

void setup()
{
  GIMSK = 0b00100000;
  PCMSK = 0b00000001;
  sei();
  DDRB = 0b00010000;
}

void loop()
{
  PORTB = 0b00010000;
  _delay_ms(500);
  PORTB = 0b00000000;
  _delay_ms(500);
}

ISR(PCINT0_vect)
{
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);

}

This is just a blink code with an interrupt to make the LED blink faster 10 times. My question is why sometimes the LED blink faster many times with the interrupt pin is not connected to anything (open)? Didn't it have internal pull up or should I use external pull up in my circuit?
Thank you

You only get an internal pullup if you actively turn that internal pullup on.

@Majenko so how to enabling internal pullup with use it as interrupt pin too? is it possible?

The interrupt functionality is completely separate to the IO functionality. Make sure the pin is an INPUT and set it HIGH will turn on the pullup. You need to know which DDR and PORT for the pin you're using as an interrupt of course.

You really shouldn’t have interrupts that take multiple seconds to finish executing. Interrupts should finish quickly so your main program can get back to its processing.

More than an answer, these are some comments and suggestions on your
program, that I hope will help you write cleaner code:

Since you seem to be avoiding using the Arduino core library, you may
as well write your own main() instead of relying on the one from
the core. This way you have a plain C program that can be compiled
either within or outside of the Arduino framework.
Instead of opaque constants, like 0b00100000, use the bit names.
These names are defined in the datasheet and are provided by the
avr-libc. They are normally used with the _BV() macro, which
expands to (1<<(x)).
For those of us who do not have the full datasheet in our head, a
comment or two stating what each bit does is helpful.
To change only one bit from a port, use the syntax PORTB |= ...;
or PORTB &= .... The compiler is smart enough to turn this into
single assembly instructions, namely sbi and cbi.
Rather than repeating ten times the same lines, use a loop.

Applying these suggestions, your program would like like;
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

ISR(PCINT0_vect)
{
    for (int i = 0; i < 10; i++) {
        PORTB |= _BV(PB4);
        _delay_ms(100);
        PORTB &= ~_BV(PB4);
        _delay_ms(100);
    }
}

int main(void)
{
    PORTB = _BV(PB0);     // internal pullup on PB0
    GIMSK = _BV(PCIE);    // enable pin change interrupt
    PCMSK = _BV(PCINT0);  // sense pin change on PCINT0 = PB0
    DDRB  = _BV(PB4);     // pin PB4 as output
    for (;;) {
        PORTB |= _BV(PB4);
        _delay_ms(500);
        PORTB &= ~_BV(PB4);
        _delay_ms(500);
    }
}

Wow thank you very much this is very helpful. This is very useful for beginners. And what's the double semicolon for? Is it like while(1)? Since there are so many tutorials with Arduino library, it's pretty difficult to find some code examples with plain C program (or not?)

The for(;;) is an infinite loop, just like while(1).

Did this code solve your problem with the double execution, that you mentioned below?

@juliussin: As stated by @chrisl, for (;;) introduces an infinite loop. I prefer it over while (true) because it feels natural to me to read it like “for (ever)”.

@chrisl I just tried this code, and this code didn't  solve the double ISR if I connect the interrupt pin to the ground with a jumper (I use breadboard to place my ATtiny85) and the repeated ISR if I touch the jumper pin. And unfortunately I doesn't have scope to check the signal of the interrupt pin :(

Is it because a bounce like on tactile push button? Just my opinion btw

I thought about this, but your ISR is way longer that any bounce from the button should be. During the ISR no other interrupt of the same kind can be queued, I think

The internal pullup is only activated, if you activate it in your code. To so, you have to write a 1 to the corresponding bit in the PORTB register, while the DDRB register is set for the pin to be an input.
So you the interrupt gets triggered randomly, because the pin was floating.
Since you are currently always write to the whole PORTB, you have to change the last bit to 1 on every PORTB write. Or you can write a 1 to it in setup() and only change the one output bit in PORTB by using
PORTB ^= 0b00010000;

This will toggle only your output pin.

Wow thank you, I'm using PORTB because I want to learn how register work and avoid to depend on library. So based on your suggestion I changed the last bit to 1 on every PORTB I wrote. I think this is worked pretty good. But if I touch the interrupt pin with my hand, the ISR run repeated. Is this because the trigger is unstable if I touch it?

This should not happen, if you activated the internal pullup resistor. I tried this with my ATTiny85 and it works perfectly.

I activated the internal pullup as you said by changed the last bit to 1 on every PORTB I wrote. But with the human touch, it's still unstable. And another problem, If i connect the interrupt pin to VCC, nothing happened (because it is pulled up right?) but if i connect it to GND, it run ISR twice, and then I release it, it run ISR once.

Odd behavior (that with the double execution). I couldn't reproduce that on my hardware. Maybe there is something odd with your wiring.


text:
What's wrong with my codes/
My teacher gave us a performance output about doing a dancing christmas lights in tinkercad. But I don't know what to do about the codes. He left  an instruction to us about what to do. I follow it but the tinkercad keep telling that...
Sorry, it seems like your code has some errors.
Close
 In function 'void setup()':
13:5: error: a function-definition is not allowed here before '{' token
21:7: error: a function-definition is not allowed here before '{' token
41:61: error: expected '}' at end of input
41:61: error: expected '}' at end of input
41:61: error: expected '}' at end of input
 exit status 1

And here's the code that I've entered...
int ledPins[]={3,4,5,6,7,8,9,10,11,12};
void setup()
{
  for(int i =0; i <11; i++)
  {
    pinMode(ledPins[i],OUTPUT);
}
  {
  void setup()
    {
     for (int i=0; i <11; i++)
     {
       pinMode(ledPins[i],OUTPUT);
     }
  }
    {
      void loop()
      {
        int i = 0;
        while (i<10)

        {
          {
            digitalWrite(ledPins{i],HIGH);
            delay(100);
            digitalWrite(ledPins[i],LOW);
            i++;
                                }
                         }
                         i = 10;
                         while (i >0
                                {
                                  digitalWrite(ledPins[i],HIGH;
                                               delay(100);
                                               digitalWrite(ledPins[i],LOW;
                                                            i--;
                                                            }
                                                            }

And here's the instruction of my teaher for the codes...
6. Initialize variables
Use array to initialize variables.
Set ledPin as the name of the variable and initialize the Arduino pins that you’re going to use.
Never forget to end each statement with semicolon
7. Set all pin to output
Use function void setup ()
Create a for () loop for array manipulation.
Initialize the for loop with i=0; since we will start the dancing lights with all LEDs turned off.
Initialize the condition i<11; since we need to turn on the 10 LEDs.
Set the increment to i++ because we need to iterate until it reaches the last LED.
Configure pin using pinMode().
Place a curly bracket before and after the for loop and pinMode().
8. Create a loop
Use function void loop().
Create a variable, i = 0.
Use while() for continuous looping
First while() is used to run your light from right to left.
Second while() is used to run your light from left to right.
Place a curly bracket before and after your statement block
Never forget to end each statement with semicolon

You seem to have brackets-tourettes. You really need to look at those brackets. Examine the shape of them, and the order of them. Hint: for every opening { there must be a closing }. For every opening ( there must be a closing ). For every opening [ there must be a closing ].

Are those the only codes that I need to change?

I don't know. Your code is such a mess I have no clue what it's intending to do.

You need to get the brackets right. Though that is not about Arduino, thus off topic here. You can search for C/C++ tutorials on the web to get the syntax right. Also you should use an autoformatting function (don't know, if Tinkercad has one, but the Arduino IDE has it) to get the indenting right. Otherwise you have to do it manually. Once the code is correctly indented, it is way easier to see the bracket problems.

you really need to look at the example code in the Arduino IDE ... see how the code is formatted, which means how it is indented ... indent levels are like paragraphs in writing ... your code has indentation, but it is all over the place without reason

Does this answer your question? What's wrong with my codes?

Duplicate of https://arduino.stackexchange.com/questions/77967/whats-wrong-with-my-codes

I changed it, so it at least compiles.
int ledPins[]={3,4,5,6,7,8,9,10,11,12};
void setup()
{
  for(int i=0; i < 11; i++)
  {
    pinMode(ledPins[i],OUTPUT);
  }
}

void loop()
{
  int i = 0;
  while (i < 10)
  {
    digitalWrite(ledPins[i],HIGH);
    delay(100);
    digitalWrite(ledPins[i],LOW);
    i++;
  }
  i = 10;
  while (i > 0)
  {
    digitalWrite(ledPins[i],HIGH);
    delay(100);
    digitalWrite(ledPins[i],LOW);
    i--;
  }
}


text:
ESP32-S3 Does not read BME680 Data
I build a PCB using ESP32-S3-WROOM-1-N16R2 Controller. I programmed a BME680 sensor with this MCU. My pinouts are,
BME_SCK 38
BME_MISO 19
BME_MOSI 15
BME_CS 5

This is my Arduino code,
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"

#define BME_SCK 38
#define BME_MISO 19
#define BME_MOSI 15
#define BME_CS 5

#define SEALEVELPRESSURE_HPA (1013.25)

//Adafruit_BME680 bme(&Wire); // I2C
//Adafruit_BME680 bme(&Wire1); // example of I2C on another bus
//Adafruit_BME680 bme(BME_CS); // hardware SPI
Adafruit_BME680 bme(BME_CS, BME_MOSI, BME_MISO,  BME_SCK);

void setup() {
 Serial.begin(9600);
 while (!Serial);

 SPI.begin(BME_SCK, BME_MISO, BME_MOSI, BME_CS);
 SPI.setDataMode(SPI_MODE0); // Set SPI mode (0, 1, 2, or 3)

 Serial.println(F("BME680 test"));

 if (!bme.begin()) {
   Serial.println("Could not find a valid BME680 sensor, check wiring!");
   while (1);
 } else {
   Serial.println("BME680 sensor initialized successfully.");
 }

 // Set up oversampling and filter initialization
 bme.setTemperatureOversampling(BME680_OS_8X);
 bme.setHumidityOversampling(BME680_OS_2X);
 bme.setPressureOversampling(BME680_OS_4X);
 bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
 bme.setGasHeater(320, 150); // 320*C for 150 ms
}

void loop() {
  if (! bme.performReading()) {
   Serial.println("Failed to perform reading :(");
   return;
  }
 Serial.print("Temperature = ");
 Serial.print(bme.temperature);
 Serial.println(" *C");

 Serial.print("Pressure = ");
 Serial.print(bme.pressure / 100.0);
 Serial.println(" hPa");

 Serial.print("Humidity = ");
 Serial.print(bme.humidity);
 Serial.println(" %");

 Serial.print("Gas = ");
 Serial.print(bme.gas_resistance / 1000.0);
 Serial.println(" KOhms");

 Serial.print("Approx. Altitude = ");
 Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
 Serial.println(" m");

 Serial.println();
 delay(2000);
}

I got output like,
R~�g�BME680 test
Could not find a valid BME680 sensor, check wiring!
R~R~�g�BME680 test
Could not find a valid BME680 sensor, check wiring!
R~�g�R��g�BME680 test
Could not find a valid BME680 sensor, check wiring!

I go through the ESP32-S3 datasheet,
It says Any GPIO pins, we will assign for SPI, I2C Communications.
Datasheet link for your reference,
https://www.espressif.com/sites/default/files/documentation/esp32-s3-wroom-1_wroom-1u_datasheet_en.pdf
ESP32-S3 series datasheet,
https://www.espressif.com/sites/default/files/documentation/esp32-s3_datasheet_en.pdf
and also i wired the same pins in ESP32-S3 EVK and programmed with BME680, it gives data perfectly, I don't know what's the issue. How to solve this issue?

The pin 38 of the module is GPIO2, not GPIO38. Therefore the #define BME_SCK 38 is wrong (all the pin defines are wrong). Your code uses the wrong GPIO references. Please get familiar with the Arduino ESP32 pin definition for ESP32-S3 and also the Table 3 Pin Definitions of ESP32-S3-WROOM-1 datasheet.

Thank you @hcheung ! I was wrongly updated the GPIO Numbers. Now it perfectly gives the BME680 Outputs.

I do not see anything wrong with the code. Please check for broken traces, cold joints, short circuits, etc. Use a multimeter to check the continuity of each SPI signal pin (SCK, MISO, MOSI, and CS) between the ESP32-S3 and the sensor. Here is a design that you can see for a cross-reference.
https://www.pcbway.com/project/shareproject/IoT_Indoor_system_with_ESP32_to_monitor_Temperature_Humidity_Pressure_and_Air_a1cf31ba.html


text:
Displaying multiple temperature outputs w/Thermistors
So I asked this question a couple days ago but did some more work with some of the coding, but I'm really stuck and need some help. I'm trying to display the temperature for each separate thermistor from input pins A0-A8 on the 2560 board. My current issue that it only reads the A8 input pin. Do I need to make more declarations such as "double readThermistor1, double readThermistor2..." etc. After I make those declarations, how would I go about displaying each separate thermistor?  I'll post what I have so far:

//  Constants

const int    SAMPLE_NUMBER      = 10;
const double BALANCE_RESISTOR   = 10000.0;
const double MAX_ADC            = 1023.0;
const double BETA               = 3977.0;
const double ROOM_TEMP          = 298.15;   // room temperature in Kelvin
const double RESISTOR_ROOM_TEMP = 10060.0;

// Here is where we will save the current temperature
double currentTemperature = 0;

//  Pin Declarations

//Inputs:

int thermistorPin[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8};  // Where the ADC samples the resistor divider's output

//Outputs:

void setup()
{
  // Set the port speed for serial window messages
  Serial.begin(9600);
}

double readThermistor()
{
  // variables that live in this function
  double rThermistor = 0;            // Holds thermistor resistance value
  double tKelvin     = 0;            // Holds calculated temperature
  double tCelsius    = 0;            // Hold temperature in celsius
  double adcAverage  = 0;            // Holds the average voltage measurement
  int    adcSamples[SAMPLE_NUMBER];  // Array to hold each voltage measurement

  /* Calculate thermistor's average resistance:
     As mentioned in the top of the code, we will sample the ADC pin a few times
     to get a bunch of samples. A slight delay is added to properly have the
     analogRead function sample properly */

  for (int i = 0; i < SAMPLE_NUMBER; i++)
  {
    adcSamples[i] = analogRead(thermistorPin[0]);  // read from pin and store
    delay(10);        // wait 10 milliseconds
    adcSamples[i] = analogRead(thermistorPin[1]);
    delay(10);        // wait 10 milliseconds
    adcSamples[i] = analogRead(thermistorPin[2]);  // read from pin and store
    delay(10);        // wait 10 milliseconds
    adcSamples[i] = analogRead(thermistorPin[3]);  // read from pin and store
    delay(10);        // wait 10 milliseconds
    adcSamples[i] = analogRead(thermistorPin[4]);  // read from pin and store
    delay(10);        // wait 10 milliseconds
    adcSamples[i] = analogRead(thermistorPin[5]);  // read from pin and store
    delay(10);        // wait 10 milliseconds
    adcSamples[i] = analogRead(thermistorPin[6]);  // read from pin and store
    delay(10);        // wait 10 milliseconds
    adcSamples[i] = analogRead(thermistorPin[7]);  // read from pin and store
    delay(10);        // wait 10 milliseconds
    adcSamples[i] = analogRead(thermistorPin[8]);  // read from pin and store
    delay(10);        // wait 10 milliseconds
  }

  /* Then, we will simply average all of those samples up for a "stiffer"
     measurement. */
  for (int i = 0; i < SAMPLE_NUMBER; i++)
  {
    adcAverage += adcSamples[i];      // add all samples up . . .
  }
  adcAverage /= SAMPLE_NUMBER;        // . . . average it w/ divide

  rThermistor = BALANCE_RESISTOR * ( (MAX_ADC / adcAverage) - 1);

  tKelvin = (BETA * ROOM_TEMP) /
            (BETA + (ROOM_TEMP * log(rThermistor / RESISTOR_ROOM_TEMP)));

  tCelsius = tKelvin - 273.15;  // convert kelvin to celsius

  return tCelsius;    // Return the temperature in Celsius
}

void loop()

{
  currentTemperature = readThermistor();
  delay(3000);

  /* Here is how you can act upon a temperature that is too hot,
  too cold or just right. */
  if (currentTemperature > 0.0 && currentTemperature < 60.0)
  {
    Serial.print("It is ");
    Serial.print(currentTemperature);
    Serial.println("C. Ahhh, very nice temperature.");

  }
  else if (currentTemperature >= 60.0)
  {
    Serial.print("It is ");
    Serial.print(currentTemperature);
    Serial.println("C. I feel like a hot tamale!");
  }
}

Any help is appreciated, thank you.

My current issue that it only reads the A8 ... that is what you told the Arduino to do ... see the for (int i = 0; i < SAMPLE_NUMBER loop .... think about the adcSamples[i] variable

you probably want a 2D array ... use two nested for loops to read the sensor values into the array ... multiple analogRead() lines are not necessary

I would personally consider rolling all the data and logic for one thermistor into a class, then instantiating multiple classes for each thermistor.

for(s ...) for(i ...) adcSamples[i][s] = analogRead(thermistorPin[i]); ... i is sensor number ... s is sample number

Why use eight thermistors if you only want to read one temperature? Using a single, well calibrated thermistor would be more sensible.

Here is my proposal:
Sum the readings (samples) of each sensor(thermistor) and store the sum in an array. Then divide each sum by the number of samples that were taken. Instead of computing one tCelsius, compute one tCelsius for each average values and store it in an array too. Then print each of them. Feel free to print it as you like.
BTW I did not compile and test the code. There might be errors in it. Use it as a hint/example.
const int    SAMPLE_NUMBER      =    10;
const double BALANCE_RESISTOR   = 10000.0;
const double MAX_ADC            =  1023.0;
const double BETA               =  3977.0;
const double ROOM_TEMP          =   298.15;
const double RESISTOR_ROOM_TEMP = 10060.0;

// PIN_COUNT is the length of the thermistorPin list.
const double PIN_COUNT = 9;
int thermistorPin[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8};

void setup()
{
  Serial.begin(9600);
}

double readThermistor()
{
  double rThermistor = 0.0;
  double tKelvin     = 0.0;

  // The count of the zeros below should be equal
  // to the PIN_COUNT
  double tCelsius[]
           = {0.0, 0.0, 0.0, 0.0, 0.0,
              0.0, 0.0, 0.0, 0.0};
  double adcSampleSumPerPin[]
           = {0.0, 0.0, 0.0, 0.0, 0.0,
              0.0, 0.0, 0.0, 0.0};

  for (int i = 0; i < SAMPLE_NUMBER; i++)
  {
    for (int j = 0; j < PIN_COUNT; i++)
    {
      adcSampleSumPerPin[j] +=
                   (double) analogRead(thermistorPin[j]);
      delay(10);
    }
  }

  for (int i = 0; i < PIN_COUNT; i++)
  {
    adcSampleSumPerPin[i] /= SAMPLE_NUMBER;
    rThermistor = BALANCE_RESISTOR *
                  ((MAX_ADC / adcSampleSumPerPin[i]) - 1);
    tKelvin = (BETA * ROOM_TEMP) /
              (BETA + (ROOM_TEMP * log(rThermistor /
              RESISTOR_ROOM_TEMP)));
    tCelsius[i] = tKelvin - 273.15;
  }

  return tCelsius;
}

void loop()
{
  delay(3000);
  currentTemps = readThermistor();

  for (i = 0; i < PIN_COUNT; i++)
  {
    double currentTemperature = currentTemp[i];
    if (currentTemperature > 0.0 && currentTemperature < 60.0)
    {
      Serial.print("Sensor A");
      Serial.print(i);
      Serial.println(":");

      Serial.print("It is ");
      Serial.print(currentTemperature);
      Serial.println("C. Ahhh, very nice temperature.");
    }
    else if (currentTemperature >= 60.0)
    {
      Serial.print("Sensor A");
      Serial.print(i);
      Serial.println(":");

      Serial.print("It is ");
      Serial.print(currentTemperature);
      Serial.println("C. I feel like a hot tamale!");
    }
  }
}


text:
Having trouble reading multiple thermistors w/ Arduino 2560
I'm trying to get my code to read multiple thermistors and I can't quite seem to get it correct using my arduino 2560. The first issue is it's not reading more than the first thermistor. The next issue is the for loop that displays the current temperature always reads "TURN OFF" when its below the 60C range.
Here is my code:
/* Here we have a few constants that make editing the code easier. I will go
  through them one by one.

  A reading from the ADC might give one value at one sample and then a little
  different the next time around. To eliminate noisy readings, we can sample
  the ADC pin a few times and then average the samples to get something more
  solid. This constant is utilized in the readThermistor function.
  */
const int    SAMPLE_NUMBER      = 10;

/* In order to use the Beta equation, we must know our other resistor
  within our resistor divider. If you are using something with large tolerance,
  like at 5% or even 1%, measure it and place your result here in ohms. */
const double BALANCE_RESISTOR0   = 10060.0; //
const double BALANCE_RESISTOR1   = 10000.0;
const double BALANCE_RESISTOR2   = 10000.0;
const double BALANCE_RESISTOR3   = 10000.0;
const double BALANCE_RESISTOR4   = 10000.0;
const double BALANCE_RESISTOR5   = 10000.0;
const double BALANCE_RESISTOR6   = 10000.0;
const double BALANCE_RESISTOR7   = 10000.0;
const double BALANCE_RESISTOR8   = 10000.0;
const double BALANCE_RESISTOR9   = 10000.0;

// This helps calculate the thermistor's resistance (check article for details).
const double MAX_ADC            = 1023.0;

/* This is thermistor dependent and it should be in the datasheet, or refer to the
  article for how to calculate it using the Beta equation.
  I had to do this, but I would try to get a thermistor with a known
  beta if you want to avoid empirical calculations. */
const double BETA               = 3977.0;

/* This is also needed for the conversion equation as "typical" room temperature
  is needed as an input. */
const double ROOM_TEMP          = 295.950;   // room temperature in Kelvin

/* Thermistors will have a typical resistance at room temperature so write this
  down here. Again, needed for conversion equations. */
const double RESISTOR_ROOM_TEMP = 10980.0;

//===============================================================================
//  Variables
//===============================================================================
// Here is where we will save the current temperature
double currentTemperature = 0;

//===============================================================================
//  Pin Declarations
//===============================================================================
//Inputs:
int thermistorPin0 = 0;  // Where the ADC samples the resistor divider's output
int thermistorPin1 = 1;
int thermistorPin2 = 2;
int thermistorPin3 = 3;
int thermistorPin4 = 4;
int thermistorPin5 = 5;
int thermistorPin6 = 6;
int thermistorPin7 = 7;
int thermistorPin8 = 8;

//Outputs:

//===============================================================================
//  Initialization
//===============================================================================

void setup()
{
 // Set the port speed for serial window messages
 Serial.begin(9600);
}

//===============================================================================
//  Main
//===============================================================================

//===============================================================================
//  Functions
//===============================================================================
/////////////////////////////
////// readThermistor ///////
/////////////////////////////

double readThermistor()
{
 // variables that live in this function
 double rThermistor0 = 0; // Holds thermistor resistance value
 double rThermistor1 = 0;
 double rThermistor2 = 0;
 double rThermistor3 = 0;
 double rThermistor4 = 0;
 double rThermistor5 = 0;
 double rThermistor6 = 0;
 double rThermistor7 = 0;
 double rThermistor8 = 0;

 double tKelvin0     = 0;            // Holds calculated temperature
 double tKelvin1     = 0;
 double tKelvin2     = 0;
 double tKelvin3     = 0;
 double tKelvin4     = 0;
 double tKelvin5     = 0;
 double tKelvin6     = 0;
 double tKelvin7     = 0;
 double tKelvin8     = 0;

 double tCelsius0    = 0;            // Hold temperature in celsius
 double tCelsius1    = 0;
 double tCelsius2    = 0;
 double tCelsius3    = 0;
 double tCelsius4    = 0;
 double tCelsius5    = 0;
 double tCelsius6    = 0;
 double tCelsius7    = 0;
 double tCelsius8    = 0;

 double adcAverage0  = 0;            // Holds the average voltage measurement
 double adcAverage1  = 0;
 double adcAverage2  = 0;
 double adcAverage3  = 0;
 double adcAverage4  = 0;
 double adcAverage5  = 0;
 double adcAverage6  = 0;
 double adcAverage7  = 0;
 double adcAverage8  = 0;

 int    adcSamples0[SAMPLE_NUMBER];  // Array to hold each voltage measurement
 int    adcSamples1[SAMPLE_NUMBER];
 int    adcSamples2[SAMPLE_NUMBER];
 int    adcSamples3[SAMPLE_NUMBER];
 int    adcSamples4[SAMPLE_NUMBER];
 int    adcSamples5[SAMPLE_NUMBER];
 int    adcSamples6[SAMPLE_NUMBER];
 int    adcSamples7[SAMPLE_NUMBER];
 int    adcSamples8[SAMPLE_NUMBER];

 /* Calculate thermistor's average resistance:
    As mentioned in the top of the code, we will sample the ADC pin a few times
    to get a bunch of samples. A slight delay is added to properly have the
    analogRead function sample properly */

 for (int i = 0; i < SAMPLE_NUMBER; i++)
 {
   adcSamples0[i] = analogRead(thermistorPin0);  // read from pin and store
   adcSamples1[i] = analogRead(thermistorPin1);
   adcSamples2[i] = analogRead(thermistorPin2);
   adcSamples3[i] = analogRead(thermistorPin3);
   adcSamples4[i] = analogRead(thermistorPin4);
   adcSamples5[i] = analogRead(thermistorPin5);
   adcSamples6[i] = analogRead(thermistorPin6);
   adcSamples7[i] = analogRead(thermistorPin7);
   adcSamples8[i] = analogRead(thermistorPin8);

   delay(10);        // wait 10 milliseconds
 }

 /* Then, we will simply average all of those samples up for a "stiffer"
    measurement. */
 for (int i = 0; i < SAMPLE_NUMBER; i++)
 {
   adcAverage0 += adcSamples0[i];      // add all samples up . . .
   adcAverage1 += adcSamples1[i];
   adcAverage2 += adcSamples2[i];
   adcAverage3 += adcSamples3[i];
   adcAverage4 += adcSamples4[i];
   adcAverage5 += adcSamples5[i];
   adcAverage6 += adcSamples6[i];
   adcAverage7 += adcSamples7[i];
   adcAverage8 += adcSamples8[i];

 }
 adcAverage0 /= SAMPLE_NUMBER;        // . . . average it w/ divide
 adcAverage1 /= SAMPLE_NUMBER;
 adcAverage2 /= SAMPLE_NUMBER;
 adcAverage3 /= SAMPLE_NUMBER;
 adcAverage4 /= SAMPLE_NUMBER;
 adcAverage5 /= SAMPLE_NUMBER;
 adcAverage6 /= SAMPLE_NUMBER;
 adcAverage7 /= SAMPLE_NUMBER;
 adcAverage8 /= SAMPLE_NUMBER;

 /* Here we calculate the thermistor’s resistance using the equation
    discussed in the article. */
 rThermistor0 = BALANCE_RESISTOR0 * ( (MAX_ADC / adcAverage0) - 1);
 rThermistor1 = BALANCE_RESISTOR1 * ( (MAX_ADC / adcAverage1) - 1);
 rThermistor2 = BALANCE_RESISTOR2 * ( (MAX_ADC / adcAverage2) - 1);
 rThermistor3 = BALANCE_RESISTOR3 * ( (MAX_ADC / adcAverage3) - 1);
 rThermistor4 = BALANCE_RESISTOR4 * ( (MAX_ADC / adcAverage4) - 1);
 rThermistor5 = BALANCE_RESISTOR5 * ( (MAX_ADC / adcAverage5) - 1);
 rThermistor6 = BALANCE_RESISTOR6 * ( (MAX_ADC / adcAverage6) - 1);
 rThermistor7 = BALANCE_RESISTOR7 * ( (MAX_ADC / adcAverage7) - 1);
 rThermistor8 = BALANCE_RESISTOR8 * ( (MAX_ADC / adcAverage8) - 1);

 /* Here is where the Beta equation is used, but it is different
    from what the article describes. Don't worry! It has been rearranged
    algebraically to give a "better" looking formula. I encourage you
    to try to manipulate the equation from the article yourself to get
    better at algebra. And if not, just use what is shown here and take it
    for granted or input the formula directly from the article, exactly
    as it is shown. Either way will work! */
 tKelvin0 = (BETA * ROOM_TEMP) /
           (BETA + (ROOM_TEMP * log(rThermistor0 / RESISTOR_ROOM_TEMP)));

 tKelvin1 = (BETA * ROOM_TEMP) /
           (BETA + (ROOM_TEMP * log(rThermistor1 / RESISTOR_ROOM_TEMP)));

 tKelvin2 = (BETA * ROOM_TEMP) /
           (BETA + (ROOM_TEMP * log(rThermistor2 / RESISTOR_ROOM_TEMP)));

 tKelvin3 = (BETA * ROOM_TEMP) /
           (BETA + (ROOM_TEMP * log(rThermistor3 / RESISTOR_ROOM_TEMP)));

 tKelvin4 = (BETA * ROOM_TEMP) /
           (BETA + (ROOM_TEMP * log(rThermistor4 / RESISTOR_ROOM_TEMP)));

 tKelvin5 = (BETA * ROOM_TEMP) /
           (BETA + (ROOM_TEMP * log(rThermistor5 / RESISTOR_ROOM_TEMP)));

 tKelvin6 = (BETA * ROOM_TEMP) /
           (BETA + (ROOM_TEMP * log(rThermistor6 / RESISTOR_ROOM_TEMP)));

 tKelvin7 = (BETA * ROOM_TEMP) /
           (BETA + (ROOM_TEMP * log(rThermistor7 / RESISTOR_ROOM_TEMP)));

 tKelvin8 = (BETA * ROOM_TEMP) /
           (BETA + (ROOM_TEMP * log(rThermistor8 / RESISTOR_ROOM_TEMP)));

 /* I will use the units of Celsius to indicate temperature. I did this
    just so I can see the typical room temperature, which is 25 degrees
    Celsius, when I first try the program out. I prefer Fahrenheit, but
    I leave it up to you to either change this function, or create
    another function which converts between the two units. */
 tCelsius0 = tKelvin0 - 273.15;  // convert kelvin to celsius
 tCelsius1 = tKelvin1 - 273.15;
 tCelsius2 = tKelvin2 - 273.15;
 tCelsius3 = tKelvin3 - 273.15;
 tCelsius4 = tKelvin4 - 273.15;
 tCelsius5 = tKelvin5 - 273.15;
 tCelsius6 = tKelvin6 - 273.15;
 tCelsius7 = tKelvin7 - 273.15;
 tCelsius8 = tKelvin8 - 273.15;

 return tCelsius0; // Return the temperature in
 return tCelsius1;
 return tCelsius2;
 return tCelsius3;
 return tCelsius4;
 return tCelsius5;
 return tCelsius6;
 return tCelsius7;
 return tCelsius8;

}

void loop()
{
 /* The main loop is pretty simple, it prints what the temperature is in the
    serial window. The heart of the program is within the readThermistor
    function. */
 currentTemperature = readThermistor();
 delay(3000);

 /* Here is how you can act upon a temperature that is too hot,
 too cold or just right. */
 if (currentTemperature > 0.0 && currentTemperature < 60.0)
 {
   Serial.print("It is ");
   Serial.print(currentTemperature);

 }
 else (currentTemperature >= 60.0);

 {
   Serial.print("It is ");
   Serial.print(currentTemperature);
   Serial.println("C. SHUT OFF!");
 }
}

I'm no expert in coding, so if you have any suggestions that could help, I would very much appreciate it.

your code complexity would be reduced if you used arrays for all variables, because loops could be used to simplify the code ... tKelvin[0]

Welcome to Stack Exchange!
The problem causing the first issue is your multiple return statements in the readThermistor function. return exits the function, so when the code runs return tCelsius0 it will exit the function and not run any of the later return statements.
Try storing your temperatures in an array and then returning that array. However, you also only read one of the values in the main() function anyway.
The problem causing the second issue is you have an if and an else. To properly check for your second condition currentTemperature >= 60.0, you need to have an else if instead.

Thank you very much.


text:
Serial Communication Problem Using Eclipse
Please help
I have created an Arduino program that will switch the pins when I send a char. It works fine with serial monitor, but the problems come when I send chars with Eclipse using RXTX serial communication. When I click the button to send the char, at first click it does not switch the Arduino pins; it just senses the Rx and Tx LED but the second time it switches on. But when I tried to switch the second LED it first turns off the first LED although that was not my aim, and then it switches the intended LED. Here is my Arduino code.
const int lamp=2;
const int fan=3;
const int pump=4;
const int fridge=5;
char val;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(lamp,OUTPUT);
  pinMode(fan,OUTPUT);
  pinMode(pump,OUTPUT);
  pinMode(fridge,OUTPUT);
}
void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available()) {
    val=Serial.read();
    if(val=='a') {
      digitalWrite(lamp,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='b') {
      digitalWrite(lamp,LOW);
      Serial.print(val);
      delay(100);
    } else if(val=='c') {
      digitalWrite(fan,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='d') {
      digitalWrite(fan,LOW);
      Serial.print(val);
      delay(100);
    } else if(val=='e') {
      digitalWrite(pump,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='f') {
      digitalWrite(pump,LOW);
      Serial.print(val);
      delay(100);
    } else if(val=='g') {
      digitalWrite(fridge,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='h') {
      digitalWrite(fridge,LOW);
      Serial.print(val);
      delay(100);
    }
  } else {
    int sensorValue = analogRead(A0);
    Serial.println(sensorValue/10);
    delay(100);
  }
}

Here is a part of my Java code
public boolean identifyport() throws PortInUseException, IOException, TooManyListenersException {
  this.setVisible(true);
  try {
    Enum=CommPortIdentifier.getPortIdentifiers();
    while(Enum.hasMoreElements())
      portname=(CommPortIdentifier)Enum.nextElement();
      if(portname.getPortType()==CommPortIdentifier.PORT_SERIAL)
        port=portname.open(this.getClass().getName(), 2000);
      serialport=(SerialPort)port;
      serialport.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_2,SerialPort.PARITY_NONE);
      input=((CommPort) serialport).getInputStream();
      output=((CommPort)serialport).getOutputStream();
      serialreader=new BufferedReader(new InputStreamReader(input));
      serialport.addEventListener(this);
      serialport.notifyOnDataAvailable(true);
      progressBar.setBackground(Color.GREEN);
      portlist.addItem(portname.getName());
      progressBar.setValue(i);
      slider_3.setValue(value);
      Thread.sleep(1000);
      prg();
    } catch (UnsupportedCommOperationException e1) {
      // TODO Auto-generated catch block
      JOptionPane.showMessageDialog(contentPane, "Check USB cable connection", "No port available ", 0);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      JOptionPane.showMessageDialog(null, "Port status", "Please connect the device....!!!!", day, null);
    }
    return rootPaneCheckingEnabled;
  }
  @Override public void serialEvent(SerialPortEvent e) {
    // TODO Auto-generated method stub
    if(e.getEventType()==SerialPortEvent.DATA_AVAILABLE){
      try {
        serial=  serialreader.read();
      } catch(Exception e1) {
        e1.printStackTrace();
      }
    }
  }
  public void writedata(int v1) {
    try {
      output.write(v1);
      output.hashCode();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

*And this is part of the switch button;*
Button button_1 = new Button("switch");
button_1.setFont(new Font("Tahoma", Font.BOLD, 13));
button_1.setBounds(10, 10, 117, 42);
panel_3.add(button_1);
button_1.addActionListener(new ActionListener() {
  int count=0;
  public void actionPerformed(ActionEvent e) {
    writedata(v1);
    if(count==0) {
      canvas.setBackground(Color.RED);
      canvas.setForeground(Color.GREEN);
      v1='b';
      count++;
    } else {
      canvas.setBackground(Color.YELLOW);
      canvas.setForeground(Color.GREEN);
      v1='a';
      count--;
    }
  }
});

Sorry I can not write everything because there is so much code.

use pastbin.com to give us all the java code so anyone can test it.

Thanks my friends, I had already solved the problem, the problem was this....
I made the method that ran after pressing each button, which sent the data at particular button, it seems the data interfered each other but I do not know why, but I had deleted that method and I used to send data using the object I created at each button.
Button button_1 = new Button("switch");
    button_1.setFont(new Font("Tahoma", Font.BOLD, 13));
    button_1.setBounds(10, 10, 117, 42);
    panel_3.add(button_1);
    button_1.addActionListener(new ActionListener() {
            int count=0;
        public void actionPerformed(ActionEvent e) {
            if(count==0){
                canvas.setBackground(Color.RED);
                canvas.setForeground(Color.GREEN);

                char v2 = 'a';
                try {
                    output.write(v2);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            count++;
            }
            else{
                canvas.setBackground(Color.YELLOW);
                canvas.setForeground(Color.GREEN);
                char v1 = 'b';
                try {
                    output.write(v1);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                count--;
        }

        }

Now it worked fine....!!!!.

The java code you wrote should send just 'a' and 'b' so you should see just lamp turning on and off.
Move writedata invocation just before count++ and count-- statements to solve your "first time". The problem could be the initialization of v1.
Into writedata method why do you call hashcode on the output stream? Maybe flush?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Help putting an Arduino project on the Internet
I'm working on quite a big project and I need few advices. Basically, Arduino will be receiving data (Strings) and will work with it. No problems with that, but I don't know what to do with receiving and sending data. Customers (all over the country, so the program will not run on LAN) will send the data, but the question is, via what? Application, that will make a TCP connection to Arduino, send UDP packet or maybe a website? Customers need to have access to data (it needs to be refreshed when arduino deletes it too). What would be the most efficient, easy to use and reliable system?
Next thing I want to know is how to make a connection. Open a port on router and connect arduino to that router? I currently have a python script that actually sends an UDP packet to local IP and it works great, but it is limited to LAN. Will it work if I just change the IP (to external) and send it to the port?
And the last thing (for now). I know how to programm in python and java. Which one is better for connections and GUIs?
Thank you for your help, and if you need any more info about the project, I will be happy to edit this post.

I modified title to match your question, hopefully that will interest more readers.

I am quite surprised people don't try google chart API if they really want to plot graph of sensor data. Setting up any arduino project over internet open to people just requires static ip and forwarded port, for Arduino projects I do not proffer default 80 port. I run apache on raspberry pi that manages everything.

What would be the most efficient, easy to use and reliable system?

What seems to me is that you need what is called Unified Application Routing. There are various technologies to do that but what I suggest is WAMP  (Web Applicaton messaging protocol, do not get confused with wamp server stack) but you can check this comparison table and select the one that most helps you. Based on that what I suggest is crossbar.io. Is open source with a lot of examples, runs on small devices (raspberry pi for example) and is intended for the use you propose, connect devices and let users/apps to get/give information from them. You can publish/subcribe to topics and all devices or apps connected with that topic can read it. Imagine something like an arduino is reading temperatures from a room and publish that data to topic "Temp1". All devices(other arduino, servers, esp8266)  or apps(websites, programs, what ever you clients you imagine) that also are connected at that moment to topic "Temp1" will get that update and act like you want. Wamp also provides a nice feature that is called RPC (remote procedure call). Imagine that you want some real nasty thing in your arduino but it lacks memory or is too slow for that. You can create a program that is, lets say in a raspberry, just waiting for that calculation and returns the result to arduino.
Take a look at this video as an example of what you can do with this ttype of techonologies. A lot of demos also in crossbar.io page. The beauty is that you can program in almost any language you are familiar with. They rely on websockets for the majority of things but crossbar is not restricted to it only, you can even use raw sockets.
As for the second part.
If you create your on server (crossbar lets say) inside the lan you have to forward the port he is listening in your router so other outside your network can access it( and possibly will need to get some kind of Dynamic DNS service if your internet provider do not have statics IPs). Or you can host your server outside your network (crossbar has a tutorial for Amazon EC2 and for Microsoft Azure I think). You only need to port forward server ports.
Hwo do you connect arduino? Use ethernet shields, esp8266, choose a yun or make a combo like arduino with usb + raspberry. That way you can also use your raspberry as a crossbar server.
Here is an example of my home made crossbar.io server using 2 python programs , 1 rboard and a raspberry pi has a host to manage my home heating system and the webpage is being accessed from internet, not local lan.

wow, thank you! I have standard arduino uno with ethernet shield which will handle receiving and sending data. Data will be simple: string which will contain current time (minutes and hours) and date. Time will be handled via RTC (I think this is the best and most reliable solution). I'll take a look at link that you provided and do something out of it.
I'm also not sure what would be the best for customers that are not familiar with computers. How to make app accessible to more devices (lets say android). Should I upload it to google play, so they can download it from there?

If I'm understanding you correctly, you have your application running on a LAN and now want to figure out how to make it accessible over the Internet (WAN). If you're there the next step is relatively straight forward. All you need is an IP address that is visible on the Internet.
You don't say what your connection to the Internet is, so let's look at both of the likely (IPv4) possibilities:

You have a block of publicly visible addresses (something other than an IP address starting with 10, 172.16, or 192.168 that are allocated by RFC 1918), or
You are behind a single IP address using NAT (network address translation) to provide the internal machines with access to the Internet. The internal machines (and devices) will all have an RFC 1918 address and will not be accessible from the Internet – except by traffic responding to requests made by those machines which are routed to them using NAT. For many users this is the more likely case.

In the first case it is simply a matter of connecting the Arduino to a network segment that is connected to the Internet and assigning an IP address (or configuring DHCP). Also, make sure that the UDP port you are using is not assigned to another service.
In the second case you will also need to connect the Arduino to a network segment with access to the Internet, but because of NAT users outside will not be able to get to the Arduino (yet). To solve that problem you will need to map a port and your external address (the address of your router) to a port and the internal address of your Arduino. For example:

Assume your service runs on port 3142 and your IP address on the Internet is 8.9.10.11 and the Arduino is at 192.168.0.42 on your internal network.
Then you would configure the port forwarding settings on your router to direct UDP traffic bound for port 3142 to the internal IP address of 192.168.0.42. Some routers will only allow you to forward to the same port, others will also allow you to use a different internal port as well.
You may also need to open up a "hole" in your firewall to allow traffic to the port where your service runs. The truly cautious will connect the Arduino to a network segment in the DMZ and there will be another firewall protecting your internal computers and devices.

Once you have this set up anybody on the outside will be able to use the service on the Arduino – if they know the IP address and the port number. Typically you would run the service at a well known host name and use DNS to translate the host name to an IP address. From your question I can't tell how you want to advertise the service, that would be another good question…

Thank you for long reply! I understand the basics (I'm computer science student actually), but I don't have real time practice to do that stuff. I know how to connect it to internet (port forwarding, IPs, NAT..), but I'm not sure if it is safe to work with UDP packets (or if I should make TCP connetion).
And if I make TCP connection, how should I do it etc. The point is that every person, who will buy the product, will have it mounted at their place and I don't know what to do with the App - ie. if he needs app on another phone, how will he connect to the right device?

It might be easier to discuss something like this in specifics (if you feel comfortable talking about what the service is and who you expect to be using it). But in generalities UDP is an unreliable service (you are responsible to making sure that the packet gets there and retrying or other wise handling the error if it does not) and TCP is a reliable service – your packet will be delivered correctly or you will get notified that it fails. There are some excellent examples of TCP based services on the Arduino out there. I'd start by looking at them (if you need TCP).

Yeah no problem, my project is basically bell system for churches. Basically, the guy who has to do stuff manually (get to the church, type it in...), will be able to do it via android app from his home. So, app will send it to arduino that will store the time into buffer and then loop over that buffer to check if current time is equal to the time in buffer. It is already working, but only for LAN.

I'd be inclined to do this via TCP, but since you already have it working on UDP I wouldn't change it. The important thing to keep in mind is that you will need to handle failures (the Arduino will have to acknowledge settings because otherwise you won't be sure they were received). Since you have it working on the LAN, all you need to do is the port mapping and then you can start using the external IP (or hostname) of the church – assuming that they have a web site in the building and your device will be added to their network.

Yes, I took care of that, Arduino sends back a message, that he successfully received the data, but I'll probably remake the whole thing, so it'll work via TCP connection. Hmm, they don't have a website. I'm making this project with my ISP, he will took care of internet connection (router, switch, static IP) and I have to take care of everything else.

How will you actually control the bells? I was assuming that the Arduino would be located with the bell controller. The church doesn't really need a web site, there just needs to be some way for the Arduino to communicate with the bell controller and for the "bell master" to get to the Arduino. As long as there is an Internet connection at the church and the ISP has a way to route traffic to the church I think you're good.

Yeah, arduino will be next to the controller (arduino will send the signals to it via output pins) so you got it right. I know, but I'm not sure what will happen when there will be 20 people using this service, and they will want to have it on multiple devices. I guess I'll make 2 more options at registration page on app and I'll tell them IP and port?

Yes. The usual way you would do this is to have the IP address identify the church/bell system always using the same port. So you'd have something like bells.my.church (the bell controller at the church) or my.church.bells (the church within a bell control service). It sounds like you're doing the latter one. Either way the port would typically stay the same. But I don't know of any reason why the port would have to stay the same. It kind of depends on the resources that are available to you. The scheme you suggested would certainly work.

Oh nice, so I'll just use same ports with different static IP's that my customers will type in at login/registration page. One more thing: java, python?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Disconnect Ethernet Shield
I'm trying to use the Ethernet Shield and the EasyVR (voice recognition) together.
The Ethernet shield uses the same pins that the EasyVR, but the easyVR works fine if I don't call Ethernet.begin(). Is there a way to disconnect the ethernet shield in order to be able to use the EasyVR again?
I haven't seen any method like "release" or "disconnect" in the Ethernet's class.
Thanks!

EasyVR only uses pins 0 and 1 (UART) (or 12 and 13 if SW-serial is selected). The ethernet shield doesn't seem to use those at all (only SPI and a few other digital pins). Seems more likely that the two libraries are conflicting with each other.

Oh! okay thanks!. But it works if I import all the libraries needed. The easyvr stops working when I use the Ethernet for the first time. So I wonder if I can disconnect the Ethernet shield after using it. Thanks

What happens after you call Ethernet.begin()? Also, are you sure that your board has enough memory?

You have correctly determined the root of the problem, both shields are trying to use the same pins. To work around this we need to know which pins are being used, and for what.
The Ethernet Shield documentation reveals the following:

The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.

https://www.arduino.cc/en/Reference/Ethernet
The documentation for Sparkfun's EasyVR library isn't as explicit, but one of the examples gives us another clue:
#if defined(__SAMD21G18A__)
  // Shield Jumper on HW (for Zero, use Programming Port)
  #define port SERIAL_PORT_HARDWARE
  #define pcSerial SERIAL_PORT_MONITOR
#elif defined(SERIAL_PORT_USBVIRTUAL)
  // Shield Jumper on HW (for Leonardo and Due, use Native Port)
  #define port SERIAL_PORT_HARDWARE
  #define pcSerial SERIAL_PORT_USBVIRTUAL
#else
  // Shield Jumper on SW (using pins 12/13 or 8/9 as RX/TX)
  #include "SoftwareSerial.h"
  SoftwareSerial port(12, 13);
  #define pcSerial SERIAL_PORT_MONITOR
#endif

#include "EasyVR.h"

EasyVR easyvr(port);

EasyVR-Arduino/examples/TestEasyVR/TestEasyVR.ino
This block of code is determining how to set up the serial communication. The first two if statements are for different boards, but the third one sets up the software serial connection... and it says there are two options, pins 12/13 OR 8/9! If there are two options, there must be a way to switch it on the board itself.

And sure enough! Check out that white box labeled "SW Serial Pins". Jackpot!
Here's what the manual has to say:

On the bottom side of the board there are two SMD resistors that you can move to select the two pins of
  Arduino that the EasyVR will be connected to when in Software Serial mode (Mode Jumper on SW).

RX – Software Serial Receiver pin

D12 – Use digital pin 12 as serial receiver (default)
D8 – Use digital pin 8 as serial receiver

TX – Software Serial Transmitter pin

D13 – Use digital pin 13 as serial transmitter (default)
D9 – Use digital pin 9 as serial transmitter

The choice of pins 12-13 is maintained for backward compatibility with the previous hardware revisions of
  the EasyVR Shield. However those pins may also be used for the SPI interface, so another choice of pins 8-
  9 is provided. If you want to use different pins make sure the receiver pin supports change interrupts.

the question is from 2015 when the EasyVR had only the pins 12 and 13 for SW Serial

I excited because this question popped up on "unanswered", but you're totally right. I didn't realize it was 3 years old. :-/


text:
double type sensor data is not displayed on bluetooth terminal app on phone
Hi I am working on a project in which I am supposed to tell if a person is running/standing/walking and going upstairs/downstairs or he is on straight road. The person will carry a arduino uno module to which gps,bluetooth and altitude sensor is attached. Also I am trying to send my phone his speed and current altitude he is experiencing using HC-05 bluetooth module. I am sure that there is no problem with altitude sensor. Also I must note that my gps module(GY_NE06MV2) is not acting proper when it comes to speed of the person. I believe this is because I experimented in my house and not outside. The problem is that I cannot see speed and altitude data on bluetooth terminal app"ArduTooth" on my phone. It is just like a blank space which should have been my data. I am presenting my code which is not very long and I hope you could help me get through this.
#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

TinyGPSPlus gps; //gps object to be used
SoftwareSerial BTserial(10, 11); //bluetooth serial connection
SoftwareSerial gps_serial(4,3); //gps serial connection
Adafruit_BME280 bme; //altitude measuring sensor object

#define SEALEVELPRESSURE_HPA (1011) //sea level pressure in Turkey/Eskisehir

double speed = 0; //speed of a moving body
double current_altitude = 0;
double previous_altitude = 0;

void setup() {
Serial.begin(115200); // serial connection to computer
BTserial.begin(9600);
gps_serial.begin(9600);
bme.begin(0x76);

delay(3000);

previous_altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);

}

void loop() {
//data from gps device is fed to gps object
while (gps_serial.available() > 0){
    gps.encode(gps_serial.read());
}

if(gps.speed.isValid()){
speed = gps.speed.kmph();
BTserial.write(speed); // this is where the problem-1 is, this data is not shown on mobile phone
bluetooth terminal application
BTserial.write(",");

  if(speed <= 5 && speed > 0.5){
    BTserial.write("walking");
    BTserial.write(",");
  }
  if(speed <= 0.5){
    BTserial.write("standing");
    BTserial.write(",");
  }
  if(speed > 5){
    BTserial.write("running");
    BTserial.write(",");
  }

  }else{
    BTserial.write("m.s.n.n"); //stands for "moving status not known"
    BTserial.write(",");
  }

current_altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);
BTserial.write(current_altitude); //this is where problem-2 is, this data also is not displayed
on phone
BTserial.write(",");
//this part determines either the body goes upstairs or downstairs or he is on straight road
if(current_altitude - previous_altitude >= 0.7){
  BTserial.write("going ups.");
  previous_altitude = current_altitude;
}
if(previous_altitude - current_altitude >= 0.7){
  BTserial.write("going downs.");
  previous_altitude = current_altitude;
}
if((current_altitude - previous_altitude <= 0.3) || (previous_altitude - current_altitude <=
0.3)){
  BTserial.write("on s.r");
  previous_altitude = current_altitude;
}
BTserial.write(";");

delay(1000);

}

I must note that purpose of BTserial.write(",");  is that every seperate entry sent to phone via bluetooth must be seperated by ",".

Have you verified, that your serial bluetooth connection is working? I mean without all the other code. Also you are using the write method, which is mostly used for binary data. I guess that you want to transmit ASCII encoded dara, thus you need to use print() for the altitute variable transmit

Bluetooth module is working fine I guaranteed that. I will try that thanks. Also can you tell me about gps module which makes me sad as it does not give speed. I believe it is because I am at home doing experiments. I am using tinygps++ library and its functions for that

You can convert you double data to string type.this trick may help. And you also can just sent a byte for different positions and decode them in app.

SoftwareSerial is a very badly behaved library. It blocks interrupts
while sending or receiving bytes. Using it with whatever depends on
interrupts is asking for trouble. Using two instances of
SoftwareSerial concurrently is doubly asking for trouble. It is very
likely that they are interfering with one another, as each one blocks
interrupts for an unreasonably long time, and each one relies on
interrupts for detecting incoming data.
You don't seem to be using the hardware serial interface (Serial),
which is a shame, as it is the only serial port you have that works
really well. I suggest you try to use this interface for one of your
devices (maybe the GPS), and a single software interface for the other
one.
Or, better yet, use Serial for both. The transmit and receive parts of
a serial port are fairly independent, save for the fact that they work
at the same speed. You could use the transmit part for the Bluetooth
module and the receive part for the GPS. This should ensure reliable
communication with both devices, without ever blocking interrupts for
too long.


text:
Sending data struct with 2 int fields from Arduino to Raspberry via NRF24L01
I'm trying to do wireless thermometer on max31865 arduino and nrf24l01 but I'm having problem sending whole data struct I can send int or char arrays but when I try to send whole struct I got output as
id: 131073 temperature: 0

Is there error in my code or there is some issue with differences in how arduino and raspberry store data? I don't really have experience in this so my question is how do I send struct that contain two fields of int or there is some better way? I need to transmit id and temperature in one package.
Transmitter code(Arduino)
#include <SPI.h>
#include "RF24.h"
#include <Adafruit_MAX31865.h>

#define RREF      430.0
#define RNOMINAL  100.0

typedef struct{
  int id = 100;
  int temperature = 100;
}
temp;

temp data;

bool radioNumber = 0;
int i =0;
Adafruit_MAX31865 thermo = Adafruit_MAX31865(10, 11, 12, 13);
RF24 radio(7,8);

byte addresses[][6] = {"1Node","2Node"};
bool role = 0;

void setup() {
  Serial.begin(115200);
  thermo.begin(MAX31865_3WIRE);
  radio.begin();
  radio.setChannel(125);
  radio.setPALevel(RF24_PA_MIN);
  radio.powerUp();
  radio.setDataRate(RF24_1MBPS);
  if(radioNumber){
    radio.openWritingPipe(addresses[1]);
    radio.openReadingPipe(1,addresses[0]);
  }else{
    radio.openWritingPipe(addresses[0]);
    radio.openReadingPipe(1,addresses[1]);
  }
  radio.stopListening();
}

void loop() {
      data.id = 1;
      data.temperature = 2;
    //int temp = 2; //thermo.temperature(RNOMINAL, RREF);
    Serial.println(temp);
    if (!radio.write( &data, sizeof(data) )){
        Serial.println(F("failed"));
     }
     delay(1000);
}

Receiver code(Raspberry pi b3+)
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <RF24/RF24.h>

using namespace std;

typedef struct{
        int id = 99;   // debug value
        int temperature = 99;
}
temp;

RF24 radio(22,0);
temp data;

bool radioNumber = 1;
const uint8_t pipes[][6] = {"1Node", "2Node"};

int main(int argc, char** argv)
{
    radio.begin();
    radio.setChannel(125);
    radio.setPALevel(RF24_PA_MIN);
    radio.setDataRate(RF24_1MBPS);
    radio.setRetries(15, 15);
    radio.printDetails();
    if (!radioNumber) {
        radio.openWritingPipe(pipes[0]);
        radio.openReadingPipe(1, pipes[1]);
    } else {
        radio.openWritingPipe(pipes[1]);
        radio.openReadingPipe(1, pipes[0]);
    }

    radio.startListening();

    while (1) {
            if (radio.available()) {
                int tem = 0;
                while (radio.available()) {
                    radio.read(&data, sizeof(data));
                }
                cout << tem  << "  " << "id: "<< data.id<< " temperatura: " << data.temperature << endl;
                delay(925);

            }
        }
    return 0;
}

EDIT:
Ok after running sizeof(data) on both devices, I notice that structs have different size 4 bytes for arduino and 8 for raspberry. So change on raspberry side to
typedef struct{
  uint16_t id = 100;
  uintt16_t temperature = 100;
}
temp;

And this is working but, may I ask why int have various size on arduino and raspberry?

Your problem is that you are communicating between an 8-bit and a 32-bit architecture.
On an 8-bit architecture int is 16 bits. On a 32-bit it's 32 bits. Why the difference? Because "it is". It's how it's always been since the dawn of C. The concept of int is a flexible idea with no fixed defined size - the size is largely defined by the architecture and the compiler. Although conventions now dictate that an int will be 16 bits on an 8-bit system and 32-bits on a 32-bit system.
You can think of it as the integer size being the same as the internal register width of the processor but with a lower bound of 16 bits.
This is precisely why the fixed width integer types uint16_t etc exist - so that you can enforce the same data size on different architectures.
Incidentally you should also be aware of the endianness of your systems. In your case they are both "little endian", but "big" (and even "middle") endian systems also exist.  This defines what order each byte of an integer (and other multi-byte data types) is stored in memory. If you send an integer from a little-endian to a big-endian system and don't apply any transformation to the data to reverse the bytes then the values will be completely wrong.

Thank you for such comprehensive answer, I was aware of big/little endian systems but I never thought about differences in architectures like you mentioned. Now I think I got this  next step is to somehow manage with the noise. Again thanks for the nice answer

Had the same issue between an atmega328p and an esp8266, scratched my head for a good couple of hours before stumbling upon this, wouldn't have thought about it, even though it makes perfect sense! Thank you!


text:
Connect two D1 R2 (8266) via SPI with Github SPISlave Library
Problem:
SPI Connection between two D1 (ESP8266) boards does not work properly, only master to slave transfers data correctly.
What I did:
I connected two Wemos D1 R2 via SPI and installed the library from https://github.com/esp8266/Arduino. I connected MISO, MOSI, SCK, SS and ground 1:1. On one D1 I run SPISlaveTest on the other SPIMaster from the examples. The D1 are located directly beside each other, cables are only 15 cm long.
Effect:
While the slave receives strings from the master fine the master seems to get crippeled answers from the slave, they appear as ??? and other characters. If I connect the slaves SS to +3.3V it reacts like expected: The slave receives no more, the master gets no reponses.
What I already tried:

Updated the Libraries to the latest versions
Changed delay to wait for answer
tried SafeMaster.ino
Changed D1 hardware on both sides

Everything unfortunately did not help.
Any tip is very appreciated.
Thanks!

try swapping the master and slave devices

install esp8266 arduino core in IDE board manager and the spislave library is part of that package. you do not need GitHub for that

did you connect ground between D1 R2s?

I connected ground and also opened this connection as they are both connected to the same computer via usb no difference. And yes, I installed the library through the board manager. Also I swapped devices because I have several D1.

If the corruption is unidirectional is there an issue with your MISO line?

I swapped and exchanged hardware, also the wires.


text:
PCM library - Timer0
I would need a quick help if possible because I have a project with the deadline tomorrow night.
On my Uno (atmega328p in fact), I need to communicate with a SPI flash to transfer music and then, take this music (part by part) to play with the PCM library.
But, both libraries are using pin 11 (MOSI and speakPin) to work.
That's why I tried to change the source code in PCM.c https://github.com/damellis/PCM/blob/master/PCM.c, I just changed the timer 2 in timer 0.
That works but only for one song. With the timer 2 you can use several times the startPlayback() function but with the timer 0 it will work with only song.... I guess it's because timer 2 is asynchronous but not the timer 0.
I found this website : http://www.renar.net/?p=73&lang=en, that's why I hope it's possible with a synchronous timer and several song.
I hope you'll have some clues for me !
Here below my new code in PCM.c :
int speakerPin = 6;
volatile unsigned char *sounddata_data;
int sounddata_length=0;
volatile uint16_t sample;
byte lastSample;
volatile boolean counterReady;

// This is called at 8000 Hz to load the next sample.
ISR(TIMER1_COMPA_vect) {
if (sample >= sounddata_length) {
   if (sample == sounddata_length + lastSample) {
    stopPlayback();
    counterReady = true;
   }
   else {
    // Ramp down to zero to reduce the click at the end of playback.
    OCR0A = sounddata_length + lastSample - sample;
   }
 }
 else {
    OCR0A = pgm_read_byte(&sounddata_data[sample]);
 }

 ++sample;
}

void startPlayback(unsigned char *data, int length)
{
   sounddata_data = data;
   sounddata_length = length;

   pinMode(speakerPin, OUTPUT);

   // Set up Timer 2 to do pulse width modulation on the speaker
   // pin.

  // Use internal clock (datasheet p.160)
  ASSR &= ~(_BV(EXCLK) | _BV(AS2));

  // Set fast PWM mode  (p.157)
   TCCR0A |= _BV(WGM01) | _BV(WGM00);
   TCCR0B &= ~_BV(WGM02);

   // Do non-inverting PWM on pin OC2A (p.155)
   // On the Arduino this is pin 11.
   TCCR0A = (TCCR0A | _BV(COM0A1)) & ~_BV(COM0A0);
   TCCR0A &= ~(_BV(COM0B1) | _BV(COM0B0));

   // No prescaler (p.158)
   TCCR0B = (TCCR0B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

   // Set initial pulse width to the first sample.
   OCR0A = pgm_read_byte(&sounddata_data[0]);

   // Set up Timer 1 to send a sample every interrupt.

   cli();

   // Set CTC mode (Clear Timer on Compare Match) (p.133)
   // Have to set OCR1A *after*, otherwise it gets reset to 0!
   TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
   TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

   // No prescaler (p.134)
   TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

   // Set the compare register (OCR1A).
   // OCR1A is a 16-bit register, so we have to do this with
   // interrupts disabled to be safe.
   OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

  // Enable interrupt when TCNT1 == OCR1A (p.136)
  TIMSK1 |= _BV(OCIE1A);

   lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
   sample = 0;
   sei();
}

void stopPlayback()
{
    // Disable playback per-sample interrupt.
    TIMSK1 &= ~_BV(OCIE1A);

   // Disable the per-sample timer completely.
   TCCR1B &= ~_BV(CS10);

   // Disable the PWM timer.
   TCCR0B &= ~_BV(CS10);

   digitalWrite(speakerPin, LOW);
}

Or is it maybe cause the Timer0 remapping destryys millis and delay, causing hickups in your SPI driver? If you do load the music data chunkwise via SPI (from an SD card I presume), does it play the entire song correctly or only the first chunk?

I guess it's because timer 2 is asynchronous but not the timer 0 - what do you mean by that? I don't think the timers differ in asynchronousity (if that is a word, which I gather it isn't).

@NickGammon: Unlike Timer 0, Timer 2 can be operated in asynchronous mode (independent of the main clock). But this mode is not used here, so this is not relevant.

Try keeping Timer 2, but switchin to pin OC2B (Arduino pin 3). Just replace in the original code OCR2A → OCR2B, and swap COM2A0 ↔ COM2B0, COM2A1 ↔ COM2B1.

@NickGammon synchronicity is a word. Not sure about its opposite though...  (asynchronicity ... yes, Grammarly likes it. )

@EdgarBonet Oh yeah, good point.