arduino mega + ENC28J60 ethernet module direct connection to PC to receive/send UDP - c++

I want to use my Arduino Mega (with a sensor shield) and an ENC28J60 Ethernet module (directly connected to my PC) to send and receive UDP from a flight simulator (X-Plane 11, which is capable of sending UDP via the network).
The network module: http://www.ebay.de/itm/281353516180?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
I can't manage to write the received UDP data into the serial monitor however.
I am not even sure I really do receive UDP.
The connection between Ethernet module and PC seems to be fine, as the green LED of the Ethernet module's I/O is permanently on, and the yellow one is blinking as soon as I start my flight sim and send UDP from there.
I have tried both, standard Ethernet cable and crossover.
I have have tried 2 ways of connecting the ENC28J60 Ethernet module to the Arduino Mega sensor shield, according to 2 different guides.
Standard wiring for the Arduino Uno
Enc28j60 SO to Arduino pin 12
Enc28j60 SI to Arduino pin 11
Enc28j60 SCK to Arduino pin 13
Enc28j60 CS to Arduino pin 10
Enc28j60 VCC to Arduino 3V3 pin
Enc28j60 GND to Arduino Gnd pin
Recommended wiring for the Arduino Mega
https://en.code-bude.net/2013/06/22/how-to-use-enc28j60-ethernet-shield-with-arduino-mega-2560/
GND to GND
3.3 to 3.3V
SO to Pin50
SI to Pin51
SCK to Pin52
CS to Pin53
I also tried several libs:
EtherCard: It is recommended to set the cs pin to 53 in the library files, which I did. Plus one should use this line of code in the sketch (which did not compile. Error is with the use of sizeof in combination with Ethernet::buffer)
ether.begin(sizeof Ethernet::buffer, mac, 53)
UIPEthernet (I assume I could use standard wiring here, as it is said that this lib uses standard Ethernet shield settings?)
None of the combinations made it possible to have any output in the serial monitor.
One of the sketches I have tried is the following:
#include <Dhcp.h>
#include <Dns.h>
#include <ethernet_comp.h>
#include <UIPClient.h>
#include <UIPEthernet.h>
#include <UIPServer.h>
#include <UIPUdp.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 6); // local IP - address of my Arduino
unsigned int localPort = 49001; // local port to listen - default X-Plane port
byte buf = 00; // buffer for UDP packet (BYTE, not char)
EthernetUDP Udp; // An EthernetUDP instance to send and receive packets over UDP
//-------------------------------------------------------------------------------
void setup()
{
Ethernet.begin(sizeof Ethernet::buffer, mac, 53)
Ethernet.begin(mac,ip); // start the Ethernet
Udp.begin(localPort); //..and UDP:
Serial.begin(9600); // init serial port
}
void loop() {
int packetSize = Udp.parsePacket(); // Checks for the presence of a UDP packet, and returns its size
if(packetSize) // UDP packet was received and its size defined
{
Serial.println();
Serial.print("Packet size: ");
Serial.println(packetSize); // Packet Size in bytes
// When Udp.read used without parameters, it returns next char (byte in this case) :
Serial.println("Xplane Data:");
for (int i =0; i/<packetSize; i++)
{
buf = Udp.read();
Serial.print(buf);
Serial.print("-");
}
}
delay(10);
}
So my questions are:
What is the easiest way to test both connections:
PC -> Ethernet module and
Ethernet module -> Arduino?
Do I need to set the used Arduino pins in my sketch or does the lib do that?
Is the sketch supposed to work properly?

https://github.com/jcw/ethercard download this. and compile and run udplistener example.
https://sourceforge.net/projects/sockettest/ download this program(SocketTest). SocketTest is very simple program.
And in arduino code,(ether.udpServerListenOnPort(&udpSerialPrint, 1337);)
you change port number that you want. "udpSerialPrint" is a callback function."1337" is a port number. If exist udp data , the program call this function.

Related

Duplex communication between two arduinos using NRF24L01 (WiFi module)

I am trying a two way chat between two Arduinos using serial monitor. I tried all the examples online but didn't work
Are you using wired or wireless communication interface?
Make a circuit according to the given diagram. Connect the RX and TX pins of Arduino vice versa (the first TX pin of Arduino to the RX pin of another and the first RX pin of Arduino to the TX pin of another). Also, common the ground pin of both Arduino.
Image: connection diagram
This is one way communication and for two way communication use simple data handling operation to achieve your task and i will let it to you. Just try it more and if you don't find the final solution then let me know once :)
At the sender side use this code:
char str[5] = "Arduino"; //String data
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.write(str,5); //Write the serial data
delay(1000);
}
At the receiver side use this code
char str[10]; //Initialized variable to store recieved data
void setup() {
// Begin the Serial at 9600 Baud
Serial.begin(9600);
}
void loop() {
Serial.readBytes(str,5); //Read the serial data and store in var
Serial.println(str); //Print data on Serial Monitor
delay(1000);
}

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.

Why Serial Communications from Arduino stops after some time

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.

xbee arduino communication programming

I tried testing the system and I’m not sure if the problem is with the xbee’s, the transmitting code, or the recieveing code. Before I post my code I will explain what we are doing with the signals. We have three analog signals that will be sent serially through one xbee using an arduino and xbee shield. We want to send these signals to the receiving xbee where the arduino will output these signals to be connected to a third arduino through wires to be used in a Simulink program. We are using an arduino mega for the transmitting side and an arduino uno for the receiving side. I was told I need to do serial streaming but I’m not sure how that’s done. I understand the xbee and arduinos both digitize signals but we are hoping to get a signal very similar to the analog signals we are transmitting. Any amount of help is greatly appreciated!!
This is how I have my xbees configured (series 1) both in AT mode:
Transmitting Xbee:
Channel:10
Pan id: 1234
MY: 10
DL: 11
Receiving Xbee:
Channel:10
Pan ID: 1234
MY: 11
DL: 10
transmitting Arduino code:
void setup() {
Serial.begin(9600);
}
void loop() {
// read the input on analog pins
int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);
int sensorValue3 = analogRead(A2);
// print out the value you read:
Serial.println(sensorValue1);
Serial.println(sensorValue2);
Serial.println(sensorValue3);
delay(1);
}
Receiving Arduino code:
int received1=8;
int received2=9;
int received3=10;
void setup(){
pinMode(received1, OUTPUT);
pinMode(received2, OUTPUT);
pinMode(received3, OUTPUT);
Serial.begin(9600);
}
void loop(){
if(Serial.available() )
{
byte output1 = Serial.read();
byte output2 = Serial.read();
byte output3 = Serial.read();
digitalWrite(received1, HIGH);
digitalWrite(received2, HIGH);
digitalWrite(received3, HIGH);
}
}
It sounds like you're using the XBee modules in "AT mode" or "transparent serial" mode where anything received on the serial port of module A is sent out of the serial port of module B, and vice versa.
If that's the case, it may help to do your initial development with the serial ports of your two devices connected directly to each other. Work out your serial protocol there, and then try to run it with the XBee modules in place as a serial cable replacement.
Consider the format of the data that you're sending, and how you will process it on the other end. How will you separate the readings and identify which analog input they belong to? With your current code, you print the readings on separate lines, but it won't be clear which is A0. Maybe you want to send them on a single line with a comma in between each reading?
On the receiving end, you need to convert the text back to an integer using a C function like atoi() or strtoul().
If you're trying to create an analog output on the Arduino, it might be possible with a digital output that's using PWM (pulse width modulation). This Instructable does a decent job of describing that concept.