Why Serial Communications from Arduino stops after some time - python-2.7

I'm building a growbox/terrarium with arduino uno as the temperature controller. Simple sketch for arduino: if DS18B20 sensor giv less than 25'C than turn on relay, which the heating cable is connected to. Loop 30s, every time Serial.print(temperature) to the PC, where I'm collecting data and make timelapse photos. ---> Here is the problem.
After some time (from 15 min up to 4 hours). Serial communication with PC stops. When I'm trying to upload a new sketch to arduino I got an error msg:
avrdude: ser_open(): can't set com-state for "\.\COM3"
I need to unplug and plug in again USB cable (or turn it off and on in Windows Device Manager), also restart Python app that is collecting data. (Very unsatisfactory fix).
So my questions are:
1. Why?
2. How to fix it?
3. Or how to make some workaround, for example reset COM port from code (desirably python2.7)
PS. Example of what I'm doing and how it works(and do not works) here: Life of pepper
PS2. My goal is to make controllable habitate for plants, where I can see behaviours differs depending on the temp, day-duration, light-intensity, humidity.
Please help me :-) .
ARDUINO UNO SKETCH
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the A
rduino
#define ONE_WIRE_BUS 2
#define PIN_HEATING 6
float temperatura = 30.0;
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
void setup(void)
{
// start serial port
Serial.begin(9600);
// Start up the library
sensors.begin();
pinMode(PIN_HEATING, OUTPUT);
}
void loop(void)
{
delay(30000);
if(temperatura<25.0){
digitalWrite(PIN_HEATING, HIGH);
}
else{
digitalWrite(PIN_HEATING, LOW);
}
sensors.requestTemperatures(); // Send the command to get temperatures
// After we got the temperatures, we can print them here.
// We use the function ByIndex, and as an example get the temperature from the first sensor only.
temperatura = sensors.getTempCByIndex(0);
Serial.print("#");
Serial.print(temperatura);
}
PYTHON2.7 RECEIVING PART
import serial #pySerial
ser = serial.Serial()
ser.port = "COM3"
ser.open()
data = ser.read_all().split("#")
datasize = len(data)
if datasize>1:
temp = data[datasize-1]
tempstr = " / " + str(temp) + "'C"
else:
tempstr=" / ----- "

I've experienced a similar problem in the past where the serial port would become unresponsive. The solution in my case wasn't very intuitive but worked nonetheless. Here's what might help you too:
Make sure the USB port you're using to connect the arduino isn't shared with other devices (for example using a USB multipoint hub). If you're using a desktop with multiple USB ports (usually found at the back of the desktop case), unplug all other USB devices (keyboard, mouse etc) and reconnect them to a different USB. Use the fastest USB port available available on your computer (USB 3.0 if present) and have it dedicated for communication with the arduino. The reason the communication port goes unresponsive sometimes is because of the momentary fluctuations in the voltage and/or current if you have several devices connected to it.
Make sure you have a stable power supply for you computer, voltage drifts due to heavy loading can sometimes cause PC peripherals to disconnect/reconnect.
If this doesn't work, try this quick software fix. Just before the delay(30000) statement in your code, add the following:
if(!Serial) { //check if Serial is available... if not,
Serial.end(); // close serial port
delay(100); //wait 100 millis
Serial.begin(9600); // reenable serial again
}
This might at least ensure continued operation operation of your application with out requiring your intervention.

So in my case the problem was solved by connecting my computer through proper surge supressor, formerly i had connectected it to wall with a simple cable, and I have old 2 wire, non-grounded, electric installation in my flat.

Related

Arduino Nano BLE 33 Sense and DS18B20 not working

My issue is related to Arduino Nano Sense BLE and DS18B20 sensor (waterproof version) are not working together.
What I tried so far. I performed a test on UNO to isolate possible powering and sensor fault. Test looked as follows:
Connection of DS18B20
Black > GDN
Red > 3V
Yellow > D2
Last two connected via 2k2 resistor (2k2 instead 4k7 as I use 3V).
Then, to exclude possible coding mistakes I used ready example:
// Include the libraries we need
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
/*
* The setup function. We only start the sensors here
*/
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
}
/*
* Main function, get and show the temperature
*/
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
// After we got the temperatures, we can print them here.
// We use the function ByIndex, and as an example get the temperature from the first sensor only.
Serial.print("Temperature for the device 1 (index 0) is: ");
Serial.println(sensors.getTempCByIndex(0));
delay(1000);
}
Result? works perfectly fine.
Then I switched to Nano Sense BLE board. without disconnecting the sensor I just switched connection on board's end and attached GDN, 3.3V and D2.
Result, -127. When trying to find DS18B20 address the result is none. I suspect board's pins order issue or Dallas/OneWire lib issue.
I also tried other libs to handle DS18B20, none works, and I tried like 3-4 of them. I noticed there is few topics around internet regarding nano series and none are resolved. I found also IoT and Every has the same problem.
The issue of getting -127 from DS18B20 is because sensor might be disconnected or didn't get 3.3V or 300mA current properly from board. So make sure your pins connected correctly. you can test it with you DMM by checking short between pin and wires. Sometime it might be a library issue. you need to install the latest version of onewire and Dallas temperature library.

Setting up Serial USB communication between STM32 and PC with Mbed library

I hava an STM32 f401RE. I am using Mbed library for setting up a conexion from STM32 to PC. I want to send via serial a char sequence to the board. As an answer i expect a blinking LED. E.g: led1 results in LED ON, led2 results in LED OFF.
The problem is that i don't know how to set the port for the connection.
#include "mbed.h"
#include "USBSerial.h"
//Virtual serial port over USB
USBSerial serial;
int main(void) {
while(1)
{
serial.printf("I am a virtual serial port\r\n");
wait(1.0);
}
}
You can use the USBSerial interface to emulate a serial port over USB. You can use this serial port as an extra serial port or as a debug solution. It also communicates between Mbed and a computer.
I would like to do all the above(even thogh i don't know what does emulate a serial port over USB. What is that Virtual USB?).
I see that USBSerial constructor takes
USBSerial (bool connect_blocking=true, uint16_t vendor_id=0x1f00, uint16_t product_id=0x2012, uint16_t product_release=0x0001). And i think i need to modify some of this adresses. The problem is that on Windows the ports are represented in Device Manager with COMxx and on Linux like ttyACMxx. How would i transform this in hexa adresses - is this what i have to do?
You should not have to transform anything or mess with the USB product_id or vendor_id, an mbed serial port should show as any other serial port so if it doesn't for you it means you are having driver issues.
On most recent Linux distros the device should show something similar to the following kernel messages:
cdc_acm 5-2:1.1: ttyACM0: USB ACM device
usbcore: registered new interface driver cdc_acm
cdc_acm: v0.26:USB Abstract Control Model driver for USB modems and ISDN adapters
On Windows, you will probably need to install drivers. After you do that, the serial port should show as mbed Serial Port (COMx) on your Device Manager. There are many places you can get troubleshooting help, see here, for instance.
The fact that you are getting nothing on both Windows and Linux makes one wonder if you are using the right cable (some USB cables work only for charging and are no good for your purposes, and some others simply fail after a while). I would first make sure your cable works with other devices (obviously not for charging only). There is also the possibility your board went (or came from the factory) bad, but that's quite unlikely.
I just found this approach and it is working. The thing that i don't understand is why on my pc i get this message: b'Hello World!\n'
#include "mbed.h"
Serial pc(USBTX, USBRX); // tx, rx
int main() {
pc.baud(9600);
while(1)
{
pc.printf("Hello World!\n");
wait(0.1);
}
}
Ignore that 'b'. Your device is not seeing that 'b'. It is just being printed by serial terminal utility. Also I would like to mention what I got from your question is, you want to send some data from PC to board over Serial and if device receives that data, it should start blinking the LED. If that is correct, use the code below:
#include "mbed.h"
Serial pc(USBTX, USBRX); // tx, rx
DigitalOut led(LED1); // If blinking doesn't work with LED1, Check the pin map for your board and pass the LED pin instead of LED1
char token = 'a'; // This is the character that you should send to trigger blinking
bool startBlinking = false;
int main() {
pc.baud(9600);
while(1)
{
if (pc.getc() == token) {
startBlinking = true;
}
if (startBlinking) {
led = 1;
wait(0.2);
led = 0;
wait(0.8);
}
}
}

How to connect 2 SPI devices to Arduino MkrZero

I am having a problem where I am unable to connect 2 SPI devices to my MkrZero. One device is a CAN shield and the other is an Ethernet Shield .
Both work fine on their own without the other connected but don't seem to work when both connected at the same time. This makes me think that my wiring and code is correct but something is still missing.
The CAN section initializes no matter what, execution seems to stop at the Ethernet code. But the Ethernet code works fine when the CAN wires are disconnected.
I have tried manually setting the CS pins, this doesn't do much. Even with both pins held high CAN starts up. This implies that the libraries take control of the pins.
I have read various tutorials on how to connect multiple devices with SPI but most times the devices are duplicates. My devices are different. I have connected the SPI pins exactly as I should with different CS pins for each device but the problem persists.
Here is my code
#include <CAN.h> //https://github.com/sandeepmistry/arduino-CAN
#include <MCP2515.h> //https://github.com/sandeepmistry/arduino-CAN Changes CS and Int pins from Uno to MkrZero configuration
#include <Ethernet.h>
#include <ArduinoJson.hpp>
#include <ArduinoJson.h>
#include <PubSubClient.h>
#include <Losant.h>
#include <SPI.h>
//Ethernet setup
#define MQTT_MAX_TRANSFER_SIZE 80 //this was done as a result of troubleshooting
byte mac[] = { 0x2C, 0xF7, 0xF1, 0x08, 0x19, 0x2C };
IPAddress ip (192, 168, 0, 1);
EthernetClient client;
// ** Configure the Losant credentials to enable comms over mqtt **
const char* LOSANT_DEVICE_ID = "";
const char* LOSANT_ACCESS_KEY = "";
const char* LOSANT_ACCESS_SECRET = "";
LosantDevice device(LOSANT_DEVICE_ID);
// The setup() function runs once each time the micro-controller starts
void setup()
{
Serial.begin(9600);
while(!Serial) { }
Serial.println("started UART");
//pinMode(BUTTON_PIN, INPUT);
// disable SD SPI
pinMode(4,OUTPUT);
digitalWrite(4,HIGH);
//starting ethernet
Ethernet.init(6); //changing Ethernet shield software select pin to 6 since default is an SPI transfer pin
Serial.println("ethernet about to start");
while(!Ethernet.begin(mac)) {}
Serial.println("ethernet started");
while (!CAN.begin(200E3)) {
Serial.println("Starting CAN failed! ");
delay(250);
}
Serial.println("CAN started");
delay(100);
Does anybody have any ideas on how to troubleshoot this or what the problem is?
There have been a few answers that involve not assuming the SPI bus has been kept the same from the last transaction. I need to reset SPI parameters each time I send a transaction. After going though the libraries I have seen that SPI.begintransaction() is called before every SPI communication, which according to my knowledge, resets the parameters. This implies that I don't need to manually change the SPI bus parameters before each transaction. Am I wrong in this regard?
SPI bus is really simple, and there should be no problem in connecting multiple slaves, as long as, at any time, only one of them has CS_ asserted (low). It can be expected that a library takes control of the CS_ pin, but it also should deassert it after the job is done. If not, then the library would be a very bad one.
You should check hardware and software.
Hardware: use a scope with memory, and look at what happens during initialization. May be that the CS_ pins need a pull-up resistor (the library, if it takes control of its CS_ pin, could choose to put it in high-impedance instead of driving it high). If you don't have a scope you can perhaps monitor the pins by software.
Software: may be the libraries use interrupts? In that case, the program can do things you are unaware of, for example a library can poll a device in background and mess with your code or one from another library. You have to dive deep in the libraries documentation and code. Again, a scope would help a lot.
You didn't specify much about your setup, and your tentative to "manually deselect the CS_ pins) is really worrying. You should check twice that point - if the CS_ pin is high, there is no reason the other SPI device does not work.
Problem was with the level shifter. I connected the OE enable pin to CAN CS, which puts the chip in high impedance when it isn't being used and enables it when I want to send data.
I used my scope to connect to the SPI pins and recorded what was happening. All was working well till I got to MISO. The level shifter was messing with it and pulling it to ground. Basically silencing output from one of the shields.
The learning here is when using level shifters with SPI devices connect the CS to OE.

Is there a clean way of disabiling RX control from USBCore in leonardo?

At the moment I'm trying to use the sparkfun promicro to control the RX pin at will using this sketch https://www.sparkfun.com/tutorials/338 .
However I have run into a problem where despite having control over the RX and TX led, it is being interfered by the USBCore.cpp in arduino. I am wondering if there is a clean way to disable control by USBCore over RX and TX pins, while still leaving the USB serial alone, so that I can control these pins directly, even while receiving and sending serial data.
/* Pro Micro Test Code
by: Nathan Seidle
modified by: Jim Lindblom
SparkFun Electronics
date: January 20, 2012
license: Public Domain - please use this code however you'd like.
It's provided as a learning tool.
This code is provided to show how to control the SparkFun
ProMicro's TX and RX LEDs within a sketch. It also serves
to explain the difference between Serial.print() and
Serial1.print().
*/
int RXLED = 17; // The RX LED has a defined Arduino pin
// The TX LED was not so lucky, we'll need to use pre-defined
// macros (TXLED1, TXLED0) to control that.
void setup()
{
pinMode(RXLED, OUTPUT); // Set RX LED as an output
// TX LED is set as an output behind the scenes
Serial.begin(9600); //This pipes to the serial monitor
Serial1.begin(9600); //This is the UART, pipes to sensors attached to board
}
void loop()
{
Serial.println("Hello world"); // Print "Hello World" to the Serial Monitor
Serial1.println("Hello!"); // Print "Hello!" over hardware UART
digitalWrite(RXLED, HIGH); // set the LED on
TXLED1; //TX LED is not tied to a normally controlled pin
delay(1000); // wait for a second
digitalWrite(RXLED, LOW); // set the LED off
TXLED0;
delay(1000); // wait for a second
}
If there is no way to tackle this cleanly without modifying the arduino enviroment, then I'll shall modify USBCore.cpp . However its probbly bad practice to do so.
If its possible in your scenario, you could use pin 17 as an INPUT, hopefully freeing up another pin which you can then use as an OUTPUT.
To do this, just use pinMode() to set pin 17 to an INPUT.
That effectively disables the RXLED functionality. When USBCore write a high to that pin, it merely turns on the pullup resistor. As long as the device driving the input can sink enough current even when the pullup is on, this will have no effect. And so there is no need to modify USBCore.
Edit: The LED lights up when pin 17 is low, which means the source of the signal needs to sink current. That can be avoided if its an issue by severing the PCB track next to the LED, or by desoldering the LED or resistor.

Cannot connect Wifly to Arduino

I am just an Arduino beginner. I bought an Arduino Uno and a Wifly shield yesterday and I am not able to run the Wifly_Test example program come with WiFlySerial library.
When I look at Serial Monitor, I only saw 2 lines are printed out
1.Starting WiFly Tester.
2.Free memory:XXXX
How can I know that the Wifly Sheild that I bought is not faulty?
I soldered the heard ping to Wifly Shield and stacked it to Aurduino Uno and I can see the LEDs blinking on the Wifly Shield.
Do I need to reset the Wifly Sheild? How do I reset it?
Please point me to the most simple example on how to connect to the router.
I have also bought the shield and had trouble to start with.
If you have soldered the pins to the shield that should be fine but make sure you check they all have a connection and that they don't have solder running down the legs of the pins as this causes the shield to be temperamental.
Run the code below which is from the WiFly library (alpha 2 version) that can be found here:
http://forum.sparkfun.com/viewtopic.php?f=32&t=25216&start=30
Once you see that the shield has connected it will ask for an input, type $$$ and press enter... you have now entered the command line and CMD will be displayed.
If you do not know your network settings type scan and this will display them.
Then set your authentication by typing set wlan auth 3 (Mixed WPA1 & WPA2-PSK) or set wlan auth 4 (WPA2-PSK) this depends on the type of authentication you ise so pick the write one for your network.
Then type set wlan phrase YourPharsePhrase (Change YourPharsePhrase to whatever your WPA key is)
Then type join YourSSIDName (Change YourSSIDName to whatever your network name is)
You see something like this:
join YourSSIDName
Auto-Assoc YourSSIDName chan=1 mode=MIXED SCAN OK
Joining YourSSIDName now..
<2.15> Associated!
DHCP: Start
DHCP in 1234ms, lease=86400s
IF=UP
DHCP=ON
IP=10.0.0.116:2000
NM=255.255.255.0
GW=10.0.0.1
Listen on 2000
you are now connected to your network.
Hopefully this will get you up and running.
N.B. REMEMBER TO CAREFULLY CHECK YOUR PINS! I had great trouble with mine because only a small amount of solder is needed but enough to get a good connection, the balance of this was minute but enough that it wouldn't work. I used a magnifying to check mine in the end.
#include "WiFly.h" // We use this for the preinstantiated SpiSerial object.
void setup() {
Serial.begin(9600);
Serial.println("SPI UART on WiFly Shield terminal tool");
Serial.println("--------------------------------------");
Serial.println();
Serial.println("This is a tool to help you troubleshoot problems with the WiFly shield.");
Serial.println("For consistent results unplug & replug power to your Arduino and WiFly shield.");
Serial.println("(Ensure the serial monitor is not open when you remove power.)");
Serial.println();
Serial.println("Attempting to connect to SPI UART...");
SpiSerial.begin();
Serial.println("Connected to SPI UART.");
Serial.println();
Serial.println(" * Use $$$ (with no line ending) to enter WiFly command mode. (\"CMD\")");
Serial.println(" * Then send each command followed by a carriage return.");
Serial.println();
Serial.println("Waiting for input.");
Serial.println();
}
void loop() {
// Terminal routine
// Always display a response uninterrupted by typing
// but note that this makes the terminal unresponsive
// while a response is being received.
while(SpiSerial.available() > 0) {
Serial.write(SpiSerial.read());
}
if(Serial.available()) { // Outgoing data
//SpiSerial.print(Serial.read(), BYTE);
SpiSerial.write(Serial.read());
}
}
Sorry I forgot to mention , you reset the shield by going to the WiFly library and going to: WiFly/tools/HardwareFactoryReset
Then open the serial monitor and type in any character and this will start the reset.
Thanks everyone who tried to answer me. I finally solved my problem by using Arduino 0023 instead of 1.0.