how do I connect an ethernet module to a gps module using arduino - gps

First, I apologize for my mediocre English, hello I'm doing a project for college where I need to use a GY-GPS6MV2 gps module and using this module I need to use an enc28j60 ethernet module to save the gps data on a web page and later use a api. I was using the code below but I didn't get any data. Initially I used only the code related to the ethernet module so that later I could add the gps code.
#include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <UIPEthernet.h>
EthernetServer server = EthernetServer(80);
SoftwareSerial serial1(6, 7); // RX, TX
TinyGPS gps1;
void setup() {
serial1.begin(9600);
Serial.begin(9600);
uint8_t mac[6] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
IPAddress myIP(192, 168, 0, 200);
Ethernet.begin(mac, myIP);
server.begin();
Serial.println("GPS Animal Tracker...");
}
void loop() {
bool recebido = false;
while (serial1.available()) {
char cIn = serial1.read();
recebido = gps1.encode(cIn);
}
if (recebido) {
Serial.println("----------------------------------------");
long latitude, longitude;
unsigned long idadeInfo;
gps1.get_position(&latitude, &longitude, &idadeInfo);
if (latitude != TinyGPS::GPS_INVALID_F_ANGLE) {
Serial.print("Latitude: ");
Serial.println(float(latitude) / 100000, 6);
}
if (longitude != TinyGPS::GPS_INVALID_F_ANGLE) {
Serial.print("Longitude: ");
Serial.println(float(longitude) / 100000, 6);
}
if (idadeInfo != TinyGPS::GPS_INVALID_AGE) {
Serial.print("Idade da Informacao (ms): ");
Serial.println(idadeInfo);
}
int ano;
byte mes, dia, hora, minuto, segundo, centesimo;
gps1.crack_datetime(&ano, &mes, &dia, &hora, &minuto, &segundo, &idadeInfo);
Serial.print("Data (GMT): ");
Serial.print(dia);
Serial.print("/");
Serial.print(mes);
Serial.print("/");
Serial.println(ano);
Serial.print("Horario (GMT): ");
Serial.print(hora);
Serial.print(":");
Serial.print(minuto);
Serial.print(":");
size_t size;
if (EthernetClient client = server.available())
{
while ((size = client.available()) > 0)
{
uint8_t* msg = (uint8_t*)malloc(size);
size = client.read(msg, size);
Serial.write(msg, size);
free(msg);
}
client.println("<h1>ModuloEletronica</h1>");
client.print("<h1>Latitude</h1>");
//client.print((float(latitude) / 100000, 6));
client.println();
client.print ("<h1>Longitude</h1>");
//client.print ((float(longitude) / 100000, 6));
client.println();
client.stop();
}
Serial.print(segundo);
}

Related

when i want to simulate a adhoc scene,which use 802.11a wifiphy ,i usually get an error

assert failed. cond="m_wifiPhy->m_currentEvent == 0", +23.801712798s 11 file=../src/wifi/model/phy-entity.cc, line=467
terminate called without an active exception
here is my code.I am a freshman in ns3,but i need get my simulation run correctly Eagerly.These days i am really exhausted to find the problem,and sttle it.So I really need someone to help me.
#include <fstream>
#include <iostream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/aodv-module.h"
#include "ns3/olsr-module.h"
#include "ns3/dsdv-module.h"
#include "ns3/dsr-module.h"
#include "ns3/applications-module.h"
#include "ns3/yans-wifi-helper.h"
#include "ns3/flow-monitor-module.h"
#include "ns3/animation-interface.h"
using namespace std;
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("constant-position-experiment");
void ReceivePacket (Ptr<Socket> socket)
{
NS_LOG_INFO ("Received one packet!");
Ptr<Packet> packet = socket->Recv ();
SocketIpTosTag tosTag;
NS_LOG_UNCOND (" received a packet!");
if (packet->RemovePacketTag (tosTag))
{
//NS_LOG_UNCOND (" TOS = " << (uint32_t)tosTag.GetTos ());
}
SocketIpTtlTag ttlTag;
if (packet->RemovePacketTag (ttlTag))
{
//NS_LOG_UNCOND (" TTL = " << (uint32_t)ttlTag.GetTtl ());
}
}
static void SendPacket (Ptr<Socket> socket, uint32_t pktSize,
uint128_t pktCount, Time pktInterval ,uint128_t counta)
{
if (pktCount > 0)
{
counta+=1;
socket->Send (Create<Packet> (pktSize));
Simulator::Schedule (pktInterval, &SendPacket,
socket, pktSize,pktCount - 1, pktInterval,counta);
NS_LOG_UNCOND (" send a packet!"<<(uint32_t)counta<<Simulator::Now());
}
else
{
socket->Close ();
}
}
int main(int argc,char*argv[])
{
int n=30;
double totaltime=4000000;
double settime=60;
double distance=35000;
string phyMode ("OfdmRate2_25MbpsBW5MHz");
string dataRate ("300kb/s");
uint64_t packetSize=512;
uint128_t packetCount =6530;
double packetInterval=0.05;
uint128_t counta(0);
uint32_t ipTos = 0;
bool ipRecvTos = true;
uint32_t ipTtl = 0;
bool ipRecvTtl = true;
//OfdmRate1_5MbpsBW5MHz
// OfdmRate2_25MbpsBW5MHz
// OfdmRate3MbpsBW5MHz
// OfdmRate4_5MbpsBW5MHz
// OfdmRate6MbpsBW5MHz
// OfdmRate9MbpsBW5MHz
// OfdmRate12MbpsBW5MHz
// OfdmRate13_5MbpsBW5MHz
// OfdmRate3MbpsBW10MHz
// OfdmRate4_5MbpsBW10MHz
// OfdmRate6MbpsBW10MHz
// OfdmRate9MbpsBW10MHz
// OfdmRate12MbpsBW10MHz
// OfdmRate18MbpsBW10MHz
// OfdmRate24MbpsBW10MHz
// OfdmRate27MbpsBW10MHz
// OfdmRate6Mbps
// OfdmRate9Mbps
// OfdmRate12Mbps
// OfdmRate18Mbps
// OfdmRate24Mbps
// OfdmRate36Mbps
// OfdmRate48Mbps
// OfdmRate54Mbps
CommandLine cmd (__FILE__);
cmd.AddValue ("distance", "the distance bettween nodes", distance);
cmd.AddValue ("settime", "olsr settime", settime);
cmd.AddValue ("phyMode", "olsr settime", phyMode);
cmd.AddValue ("dataRate", "olsr settime", dataRate);
cmd.Parse (argc, argv);
// LogComponentEnable("OnOffApplication",LOG_LEVEL_INFO);
NodeContainer c;
c.Create(n);
NodeContainer n0n23=NodeContainer(c.Get(0),c.Get(23));
NS_LOG_UNCOND ("distance:"<<distance<<"phymode: "<<phyMode<<"dataRate: "+dataRate);
//wifpyh wifchannel
WifiHelper wifi;
wifi.SetStandard (WIFI_STANDARD_80211a);
WifiMacHelper wifiMac;
YansWifiPhyHelper wifiPhy;
YansWifiChannelHelper wifiChannel;
wifiPhy.Set("TxGain",DoubleValue(4.5));
wifiPhy.Set("RxGain",DoubleValue(4.5));
//
wifiPhy.Set("RxSensitivity",DoubleValue(-90));
wifiPhy.Set("Antennas",UintegerValue(2));
wifiPhy.Set ("TxPowerStart",DoubleValue (37));
wifiPhy.Set ("TxPowerEnd", DoubleValue (37));
wifiPhy.Set ("RxNoiseFigure",DoubleValue (0));
wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel","Frequency",DoubleValue(1.2e+09));
wifiPhy.SetChannel (wifiChannel.Create ());
wifiMac.SetType ("ns3::AdhocWifiMac");
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
"DataMode",StringValue (phyMode),
"ControlMode",StringValue (phyMode));
NetDeviceContainer devices = wifi.Install (wifiPhy, wifiMac, c);
//mobility
MobilityHelper mobility;
mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue (0.0),
"MinY", DoubleValue (0.0),
"DeltaX", DoubleValue (distance),
"DeltaY", DoubleValue (distance),
"GridWidth", UintegerValue (5),
"LayoutType", StringValue ("RowFirst"));
mobility.SetMobilityModel ("ns3::RandomDirection2dMobilityModel",
"Bounds", RectangleValue (Rectangle (-200000, 200000, -200000, 200000)),
"Speed", StringValue ("ns3::ConstantRandomVariable[Constant=39]"),
"Pause", StringValue ("ns3::ConstantRandomVariable[Constant=2]"));
mobility.Install (c);
//internet
OlsrHelper olsr;
Ipv4ListRoutingHelper list;
list.Add (olsr, 10);
InternetStackHelper internet;
internet.SetRoutingHelper (list); // has effect on the next Install ()
internet.Install (c);
Ipv4AddressHelper addressAdhoc;
addressAdhoc.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces;
interfaces = addressAdhoc.Assign (devices);
//application
NS_LOG_INFO ("Create sockets.");
//Receiver socket on n1
TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
Ptr<Socket> recvSink = Socket::CreateSocket (c.Get (1), tid);
InetSocketAddress local = InetSocketAddress (Ipv4Address::GetAny (), 4477);
recvSink->SetIpRecvTos (ipRecvTos);
recvSink->SetIpRecvTtl (ipRecvTtl);
recvSink->Bind (local);
recvSink->SetRecvCallback (MakeCallback (&ReceivePacket));
//Sender socket on n0
Ptr<Socket> source = Socket::CreateSocket (c.Get (27), tid);
InetSocketAddress remote = InetSocketAddress (interfaces.GetAddress (1), 4477);
//Set socket options, it is also possible to set the options after the socket has been created/connected.
if (ipTos > 0)
{
source->SetIpTos (ipTos);
}
if (ipTtl > 0)
{
source->SetIpTtl (ipTtl);
}
source->Connect (remote);
//flowmonitor
string s1=phyMode.substr(8,3);
string s2=phyMode.substr(phyMode.length()-4,4);
string s3=dataRate.substr(0,dataRate.length()-2);
string filename=to_string(int(distance/1000))+"_"+s1+"_"+s2+"_"+s3;
Ptr<FlowMonitor> flowmon;
FlowMonitorHelper flowmonHelper;
flowmon = flowmonHelper.InstallAll ();
Ptr<OutputStreamWrapper> routingStream=Create<OutputStreamWrapper>(filename+"routes.tr",std::ios::out);
olsr.PrintRoutingTableAt(Seconds(40.0),c.Get(2),routingStream);
AnimationInterface anim ((filename+".xml"));
anim.SetMaxPktsPerTraceFile(99999999999999);
Time interPacketInterval = Seconds (packetInterval);
Simulator::ScheduleWithContext (source->GetNode ()->GetId (),
Seconds (1.0), &SendPacket,
source, packetSize, packetCount, interPacketInterval,counta);
Simulator::ScheduleWithContext (source->GetNode ()->GetId (),
Seconds (70.0), &SendPacket,
source, packetSize, packetCount, interPacketInterval,counta);
Simulator::ScheduleWithContext (source->GetNode ()->GetId (),
Seconds (30.0), &SendPacket,
source, packetSize, packetCount, interPacketInterval,counta);
Simulator::Stop (Seconds (totaltime));
Simulator::Run ();
Simulator::Destroy ();
flowmon->SerializeToXmlFile (filename+".flowmon", false, false);
// numPackets=0;
return 0;
}
why this problem occur ?
How to settle it?

UART sending wrong characters on pic18

I'm trying to simply send characters trough my UART Interface by calling the funktion: UART_Write_Text("hello");
this is the code executed in the the uart.c file:
void UART_Init(void)
{
//115200bps deafult value for RN4678
BRGH = 0; //Setting High Baud Rat
BRG16 = 0; //8-Bit mode
SPBRG = 8; //Writing SPBRG Register
TXSTAbits.SYNC = 0; //Setting Asynchronous Mode, ie UART
RCSTAbits.SPEN = 1; //Enables Serial Port
RCSTAbits.CREN = 1; //Enables Reception
TXSTAbits.TXEN = 1; //Enables Transmission
}
/******************************************************************************/
//-----UART write byte
/******************************************************************************/
void UART_Write(char data)
{
while(!TRMT);
TXREG = data;
}
/******************************************************************************/
//-----UART check tx queue
/******************************************************************************/
char UART_TX_Empty(void)
{
return TRMT;
}
/******************************************************************************/
//-----UART write string
/******************************************************************************/
void UART_Write_Text(char *text)
{
for(int i=0; text[i]!='\0' || text[i] !=0x00; i++){
UART_Write(text[i]);
}
UART_Write('\n');
}
/******************************************************************************/
//-----UART data ready to read
/******************************************************************************/
char UART_Data_Ready(void)
{
return RCIF;
}
/******************************************************************************/
//-----UART read byte
/******************************************************************************/
char UART_Read(void)
{
while(!RCIF);
return RCREG;
}
/******************************************************************************/
//-----UART read string
/******************************************************************************/
void UART_Read_Text(char *Output, unsigned int length)
{
unsigned int i;
for(int i=0;i<length;i++)
Output[i] = UART_Read();
}
Now when I'm debugging it, I see that it writes the wright charakters into the TXREG. At the end it sended the following characters: 'h', 'e', 'l', 'l', 'o', '\n'.
I send them to the bluetooth module RN4678 with a baud rate of 115200bps which is also the default baud rate of the BT module. However when I read the sended character on my phone with a Bluetooth terminal i get only some characters wright and the other ones are questionmarks, so it doesn't recognise them (not always the same character unrecognised).
I already experimented with the baud rate, but it looks like its the right value I writed into the SPBRG.
I'm also polling the TRMT so there shouldn't be any collisions...
Someone knows what I'm doing wrong?
#include "Configuration_bits.h"
#include <xc.h>
#include <stdio.h>
#include <p18f67k22.h>
#include <string.h>
#include <stdlib.h>
#define _XTAL_FREQ 16000000
void UART_Init_1(){
TRISCbits.TRISC6=1; // TX1 Pin-31
TRISCbits.TRISC7=1; // RX1 Pin-32
RC1IE=1;
SPBRG1=34; // Baud Rate 115200
BAUDCON1bits.BRG16=1;
TXSTA1bits.BRGH=1;
//TXSTA 1 Register
TXSTA1bits.TX9=0; // 8-bit transmission
TXSTA1bits.TXEN=0;
TXSTA1bits.TXEN=1; // Transmit is enabled
TXSTA1bits.SYNC=0; // Asynchronous mode
TXSTA1bits.TRMT=1; // Transmit Shift Register Status bit
//RXSTA 1 Register
RCSTA1bits.SPEN=1; // Serial Port Enable bit
RCSTA1bits.RX9=0; // 8-bit reception
RCSTA1bits.CREN=1; // Continuous Receive Enable bit
}
void UART_Tx_1(unsigned char z[])
{
unsigned int uart_tx1=0;
while(z[uart_tx1]!='\0')
{
while(!TX1IF);
TXREG1=z[uart_tx1];
uart_tx1++;
}
}
void UART_Rx_1()
{
string_rx1[uart_rx1]=RCREG1;
uart_rx1++;
}
void interrupt ISR(void)
{
if(RC1IF && RC1IE) // UART_1
{
}
}
void main(void)
{
System_Initialization();
UART_Init_1();
while(1)
{
UART_Tx_1("HELLO\r\n"); // Transmit Hello
}
}

TinyGps No data

I'm working on a tracking project. I'm using TinyDuino Processor Bd together with TinyGPS shield. Just to test the GPS shield, I have tried all possible codes using the libraries TinyGPS and TinyGPS++. they all failed and gave me an output of 0's or uninterpretable output. here are some codes I tried with there output.
Code 1:
#include
static const int GPS_ONOFFPin = A3;
static const int GPS_SYSONPin = A2;
static const int GPS_RXPin = A1;
static const int GPS_TXPin = A0;
static const int GPSBaud = 9600;
static const int chipSelect = 10;
// The GPS connection is attached with a software serial port
SoftwareSerial Gps_serial(GPS_RXPin, GPS_TXPin);
int led = 13;
void setup()
{
// Init the GPS Module to wake mode
pinMode(GPS_SYSONPin, INPUT);
pinMode(GPS_ONOFFPin, OUTPUT);
digitalWrite( GPS_ONOFFPin, LOW );
delay(5);
if( digitalRead( GPS_SYSONPin ) == LOW )
{
// Need to wake the module
digitalWrite( GPS_ONOFFPin, HIGH );
delay(5);
digitalWrite( GPS_ONOFFPin, LOW );
}
// Open serial communications and wait for port to open:
Serial.begin(9600);
pinMode(led, OUTPUT);
Gps_serial.begin(9600);
}
void loop()
{
if (Gps_serial.available())
Serial.write(Gps_serial.read());
}
Second Code:
#include
#include
/* This sample code demonstrates the normal use of a TinyGPS object.
It requires the use of SoftwareSerial, and assumes that you have a
4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
TinyGPS gps;
SoftwareSerial ss(4, 3);
static void smartdelay(unsigned long ms);
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);
void setup()
{
Serial.begin(115200);
Serial.print("Testing TinyGPS library v. ");
Serial.println(TinyGPS::library_version());
Serial.println("by Mikal Hart");
Serial.println();
Serial.println("Sats HDOP Latitude Longitude Fix Date Time
Date Alt Course Speed Card Distance Course Card Chars Sentences
Checksum");
Serial.println(" (deg) (deg) Age
Age (m) --- from GPS ---- ---- to London ---- RX RX
Fail");
Serial.println("--------------------------------------------------------
--------------------------------------------------------------------------
---");
ss.begin(4800);
}
void loop()
{
float flat, flon;
unsigned long age, date, time, chars = 0;
unsigned short sentences = 0, failed = 0;
static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;
print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
gps.f_get_position(&flat, &flon, &age);
print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);
print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);
print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
print_date(gps);
print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);
gps.stats(&chars, &sentences, &failed);
print_int(chars, 0xFFFFFFFF, 6);
print_int(sentences, 0xFFFFFFFF, 10);
print_int(failed, 0xFFFFFFFF, 9);
Serial.println();
smartdelay(1000);
}
static void smartdelay(unsigned long ms)
{
unsigned long start = millis();
do
{
while (ss.available())
gps.encode(ss.read());
} while (millis() - start < ms);
}
static void print_float(float val, float invalid, int len, int prec)
{
if (val == invalid)
{
while (len-- > 1)
Serial.print('*');
Serial.print(' ');
}
else
{
Serial.print(val, prec);
int vi = abs((int)val);
int flen = prec + (val < 0.0 ? 2 : 1); // . and -
flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
for (int i=flen; i<len; ++i)
Serial.print(' ');
}
smartdelay(0);
}
static void print_int(unsigned long val, unsigned long invalid, int len)
{
char sz[32];
if (val == invalid)
strcpy(sz, "*******");
else
sprintf(sz, "%ld", val);
sz[len] = 0;
for (int i=strlen(sz); i<len; ++i)
sz[i] = ' ';
if (len > 0)
sz[len-1] = ' ';
Serial.print(sz);
smartdelay(0);
}
static void print_date(TinyGPS &gps)
{
int year;
byte month, day, hour, minute, second, hundredths;
unsigned long age;
gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
if (age == TinyGPS::GPS_INVALID_AGE)
Serial.print("********** ******** ");
else
{
char sz[32];
sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
month, day, year, hour, minute, second);
Serial.print(sz);
}
print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
smartdelay(0);
}
static void print_str(const char *str, int len)
{
int slen = strlen(str);
for (int i=0; i<len; ++i)
Serial.print(i<slen ? str[i] : ' ');
smartdelay(0);
}
Code 1 confirms that the GPS device is working on A0/A1 at 9600 baud. The /dev/cu.usbserial-DN00CT3C window shows good NMEA sentences being echoed. But it doesn't have good satellite reception... all the fields are zero value or empty.
Code 2 shows that the TinyGPS example is not receiving any characters. That's because it's trying to use SoftwareSerial on pins 4 & 3. Change it to
SoftwareSerial ss( A1, A0 );
You may also be interested in a more efficient library, NeoGPS. It can be configured to handle only the messages and fields that you use. Everything else is ignored, saving RAM and processing time.
The GPS TX pin goes to the Arduino RX piN and likewise, the GPS RX pin goes to the Arduino TX pin. For the Second code, the GPS Baudrate is given as 4800 in description. try with baudrate of 9600 in both serial.begin and ss.begin.
You probably have to be outside, or at least near some windows for the GPS device to receive from the satellites. It could take 15 minutes for the first fix to happen.
#include <SoftwareSerial.h>
#include <TinyGPS.h>
TinyGPS gps;
SoftwareSerial ss(3,4);
static void smartdelay(unsigned long ms);
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
void setup()
{
Serial.begin(9600);
ss.begin(9600);
}
void loop()
{
float flat, flon;
unsigned short sentences = 0, failed = 0;
gps.f_get_position(&flat, &flon);
Serial.print("LATITUDE: ");
print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);
Serial.println(" ");
Serial.print("LONGITUDE: ");
print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);
Serial.println(" ");
Serial.print("altitude: ");
print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
Serial.println(" ");
Serial.print("COURSE:");
print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
Serial.println("");
Serial.print("DIRECTION: ");
int d;
print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
d=gps.f_course();
Serial.println();
Serial.println();
smartdelay(1000);
}
static void smartdelay(unsigned long ms)
{
unsigned long start = millis();
do
{
while (ss.available())
int val = gps.encode(ss.read());
} while (millis() - start < ms);
}
static void print_float(float val, float invalid, int len, int prec)
{
if (val == invalid)
{
while (len-- > 1)
Serial.print('*');
Serial.print(' ');
}
smartdelay(0);
}
static void print_str(const char *str, int len)
{
int slen = strlen(str);
for (int i=0; i<len; ++i)
Serial.print(i<slen ? str[i] : ' ');
smartdelay(0);
}

What needs to be done in linux kernel to initialize broadcom L2 switch via PCI-E?

I have a custom board with Armada 370 SoC in which a Broadcom L2 switch is now being added via PCI-E to the Soc.
The board runs on linux. I want to just initialize the L2 switch registers.
I just want very minimal access so that I can access the registers of L2 switch(using a program which uses /dev/mem - I have the application).
Am new and I would like to know what needs to be done in PCI-E drivers and menuconfig and etc.
I would be happy if someone could point to a resource which explains all this stuff from scratch because I want to learn more.
Will I be able to access the registers if I just do the memory mapping correctly? Do I need to do anything more?
This should get you on your way. It sets up BAR0 for access. All you have to do is figure out how you want software to access the driver and implement those handlers: read/write/open/close/ioctl, etc.
#include <linux/cdev.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/ioctl.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/pci.h>
#include <linux/tty.h>
#include <linux/version.h>
void error_msg (const char *msg, ...); /* provide by calling possibly kprintf() */
static dev_t dev_num; /* major/minor device numbers */
static struct cdev c_dev, pci_dev; /* character device structure */
static const char DEVICE_NAME[] = "mydevice"; /* name for /dev/... */
static unsigned long bar0_len;
static unsigned char __iomem *bar0_mem;
static struct file_operations mydevice_fops = {
.owner = THIS_MODULE,
// .open = (function to handle open),
// .read = (function to handle read),
// .write = (function to handle write),
// .close = (function to handle close),
// .unlocked_ioctl = (function to handle ioctl),
};
static int mydevice_pci_probe (struct pci_dev *dev, const struct pci_device_id *id)
{
int ret;
char name[20];
dev_t unit_num;
struct device *dev_p;
ret = pci_enable_device (dev);
if (ret)
{
error_msg ("error %d enabling device");
return ret;
}
bar0_len = pci_resource_len (dev, 0);
bar0_mem = pci_iomap (dev, 0, bar0_len);
if (!bar0_len || !bar0_mem) /* device not there */
{
error_msg ("device bar0 missing");
return -1;
}
snprintf (name, sizeof name, "%s%d", DEVICE_NAME, 1); /* create device name */
unit_num = MKDEV(MAJOR(dev_num), 1);
dev_p = device_create (NULL, NULL, unit_num, NULL, name);
if (IS_ERR(dev_p))
{
error_msg ("error creating pci device %s", name);
return -1;
}
cdev_init (&pci_dev, &mydevice_fops);
mydevice_fops.owner = THIS_MODULE;
ret = cdev_add (&pci_dev, unit_num, 1);
if (ret < 0)
{
error_msg ("error adding pci device");
device_destroy (NULL, unit_num);
return ret;
}
pci_set_master (dev);
return 0;
}
static void mydevice_pci_remove (struct pci_dev *dev)
{
cdev_del (&c_dev);
device_destroy (NULL, dev_num);
pci_iounmap (dev, bar0_mem);
pci_disable_device (dev);
}
static struct pci_device_id mydevice_ids[] = {
{
0xabcd, /* vendor/manufacturer ID */
0x1234, /* device/vendor device ID */
PCI_ANY_ID, /* subvendor: don't care */
PCI_ANY_ID, /* subdevice: don't care */
0, /* class: don't care */
0, /* class_mask: don't care */
0, /* ulong_t driver_data: private driver data */
},
{} /* end of pci device IDs */
};
static struct pci_driver mydriver_ops = {
.name = DEVICE_NAME,
.id_table = mydevice_ids,
.probe = mydevice_pci_probe,
.remove = mydevice_pci_remove,
/*
* For pci bus error recovery, see
* https://www.kernel.org/doc/Documentation/PCI/pcieaer-howto.txt
*/
};
static struct file_operations mydriver_fops = {
.owner = THIS_MODULE,
};
static int __init mydriver_init (void)
{
struct device *mydriver_device;
int ret = alloc_chrdev_region (&dev_num, 0, 1, DEVICE_NAME);
if (ret)
{
error_msg ("unable to allocate major/minor device number");
return ret;
}
mydriver_device = device_create (NULL, NULL, dev_num, NULL, DEVICE_NAME);
if (IS_ERR(mydriver_device))
{
error_msg ("error creating device");
unregister_chrdev_region (dev_num, 1);
return -ENODEV;
}
cdev_init (&c_dev, &mydevice_fops);
c_dev.owner = THIS_MODULE;
ret = cdev_add (&c_dev, dev_num, 1);
if (ret < 0)
{
error_msg ("error adding device");
device_destroy (NULL, dev_num);
unregister_chrdev_region (dev_num, 1);
return ret;
}
ret = pci_register_driver (&mydriver_ops); // this is key to PCI devices
if (ret < 0)
{
error_msg ("error %d from pci_register_driver", ret);
cdev_del (&c_dev);
device_destroy (NULL, dev_num);
unregister_chrdev_region (dev_num, 1);
return ret;
}
return 0;
}
static void __exit mydriver_exit (void)
{
device_destroy (NULL, dev_num);
unregister_chrdev (MAJOR(dev_num), DEVICE_NAME);
unregister_chrdev_region (dev_num, 1);
}
module_init(mydriver_init);
module_exit(mydriver_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your name <youremail#example.com>");

Creating a RAW UDP connection in lwip ARP

I am currently working to create a simple transfer protocol over Ethernet. I have a SP605 Xilinx evaluation board which I am using to debug the Ethernet portion of our project. I attempted to cannibalize the example but have so far been unsuccessful. Currently, the communication needs to only be one way. Currently, I am trying to see the data being sent with netcat. I also have wireshark open and am seeing the system get stuck repeatedly asking:
2217 1323.697811000 Xilinx_00:01:02 Broadcast
ARP 60 Who has 192.168.1.11? Tell 192.168.1.10
I can see the Host computer reply with:
2217 1323.697811000 Xilinx_00:01:02 Broadcast
ARP 60 Who has 192.168.1.11? Tell 192.168.1.10
I feel like I have some issues with the configuration but cannot figure out how what it is. I think it might have something to do with a not having a recv handler set but I am not sure.
Below is the code I am using. lwip_init() is mimicking the call from the examples provided by Xilinx.
/*
* main.c
*
* Created on: Sep 24, 2013
* Author: Ian
*/
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include "lwip/init.h"
#include "xparameters.h"
#include "netif/xadapter.h"
#include "xenv_standalone.h"
#include "platform_config.h"
#include "xparameters.h"
#include "xintc.h"
#include "xil_exception.h"
#include "mb_interface.h"
#include "xtmrctr_l.h"
#include "lwip/udp.h"
#include "lwipopts.h"
#include "xil_printf.h"
struct ip_addr ipaddr, ipaddr_remote, netmask, gw;
void udp_test(void *arg, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr, u16_t port);
void print_ip(char *msg, struct ip_addr *ip)
{
print(msg);
xil_printf("%d.%d.%d.%d\r\n", ip4_addr1(ip), ip4_addr2(ip),
ip4_addr3(ip), ip4_addr4(ip));
}
void print_ip_settings(struct ip_addr *ip, struct ip_addr *mask, struct ip_addr *gw)
{
print_ip("Board IP: ", ip);
print_ip("Netmask : ", mask);
print_ip("Gateway : ", gw);
}
int main()
{
err_t error;
struct netif *netif, server_netif;
struct udp_pcb *udp_1;
struct pbuf *p;
char data[8] = "01234567";
u16_t Port;
Port = 69;
int count = 0;
int n = 0;
int buflen = 8;
/* the mac address of the board. this should be unique per board */
unsigned char mac_ethernet_address[] = { 0x00, 0x0a, 0x35, 0x00, 0x01, 0x02 };
netif = &server_netif;
xil_printf("\r\n\r\n");
xil_printf("-----lwIP RAW Application ------\r\n");
/* initliaze IP addresses to be used */
IP4_ADDR(&ipaddr_remote, 192, 168, 1, 11);
IP4_ADDR(&ipaddr, 192, 168, 1, 10);
IP4_ADDR(&netmask, 255, 255, 255, 0);
IP4_ADDR(&gw, 192, 168, 1, 1);
print_ip_settings(&ipaddr, &netmask, &gw);
lwip_init();
if (!xemac_add(netif, &ipaddr, &netmask, &gw, mac_ethernet_address, PLATFORM_EMAC_BASEADDR)) {
xil_printf("Error adding N/W interface\r\n");
return -1;
}
netif_set_default(netif);
netif_set_up(netif);
Xil_ExceptionEnable(); //Setup complete start interrupts
udp_1 = udp_new();
error = udp_bind(udp_1, IP_ADDR_ANY, Port);
if (error != 0)
{
xil_printf("Failed %d\r\n", error);
}
else if (error == 0)
{
xil_printf("Success\r\n");
}
error = udp_connect(udp_1, &ipaddr_remote, Port);
if (error != 0)
{
xil_printf("Failed %d\r\n", error);
}
else if (error == 0)
{
xil_printf("Success\r\n");
}
while(1)
{
count++;
xemacif_input(netif);
if (count == 100000)
{
p = pbuf_alloc(PBUF_TRANSPORT, buflen, PBUF_POOL);
if (!p) {
xil_printf("error allocating pbuf\r\n");
return ERR_MEM;
}
memcpy(p->payload, data, buflen);
udp_send(udp_1, p);
xil_printf("SEND\r\n");
count = 0;
pbuf_free(p);
}
}
data[1] = '2';
}
Ok, so basically here is what I found.
The Xilinx xapp1026 had issues with the sp605_AxiEth_32kb_Cache project when I used it. It was hanging at the start interrupts. I was not able to diagnose the project BUT I switched to the sp605_EthernetLite_32kb_Cache example project. I can only assume that the failure of the MicroBlaze interrupts to initialize caused the ARP to fail to get added and forced the system into the loop repeatedly. It is still unclear why the interrupt failed to initialize in the AxiEth example.
Once here I was able to get a program to work by stripping down the provided system and using the following code:
/*
* Copyright (c) 2007 Xilinx, Inc. All rights reserved.
*
* Xilinx, Inc.
* XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A
* COURTESY TO YOU. BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS
* ONE POSSIBLE IMPLEMENTATION OF THIS FEATURE, APPLICATION OR
* STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION
* IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE
* FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION.
* XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO
* THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO
* ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE
* FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#include <stdio.h>
#include <string.h>
#include "lwip/udp.h"
#include "xparameters.h"
#include "netif/xadapter.h"
#include "platform.h"
#include "platform_config.h"
#include "lwipopts.h"
#ifndef __PPC__
#include "xil_printf.h"
#endif
void print_headers();
int start_applications();
int transfer_data();
void platform_enable_interrupts();
void lwip_init(void);
void tcp_fasttmr(void);
void tcp_slowtmr(void);
#if LWIP_DHCP==1
extern volatile int dhcp_timoutcntr;
err_t dhcp_start(struct netif *netif);
#endif
extern volatile int TxPerfConnMonCntr;
extern volatile int TcpFastTmrFlag;
extern volatile int TcpSlowTmrFlag;
void print_ip(char *msg, struct ip_addr *ip)
{
print(msg);
xil_printf("%d.%d.%d.%d\r\n", ip4_addr1(ip), ip4_addr2(ip),
ip4_addr3(ip), ip4_addr4(ip));
}
void print_ip_settings(struct ip_addr *ip, struct ip_addr *mask, struct ip_addr *gw)
{
print_ip("Board IP: ", ip);
print_ip("Netmask : ", mask);
print_ip("Gateway : ", gw);
}
int main()
{
struct netif *netif, server_netif;
struct ip_addr ipaddr, netmask, gw;
// Added stuff for the creation of a basic UDP
err_t error;
struct ip_addr ip_remote;
struct udp_pcb *udp_1;
struct pbuf *p;
char data[8] = "01234567";
u16_t Port = 12;
int buflen = 8;
int count = 0;
/* the mac address of the board. this should be unique per board */
unsigned char mac_ethernet_address[] = { 0x00, 0x0a, 0x35, 0x00, 0x01, 0x02 };
netif = &server_netif;
if (init_platform() < 0) {
xil_printf("ERROR initializing platform.\r\n");
return -1;
}
xil_printf("\r\n\r\n");
xil_printf("-----lwIP RAW Mode Demo Application ------\r\n");
/* initliaze IP addresses to be used */
#if (LWIP_DHCP==0)
IP4_ADDR(&ipaddr, 192, 168, 1, 10);
IP4_ADDR(&netmask, 255, 255, 255, 0);
IP4_ADDR(&gw, 192, 168, 1, 1);
print_ip_settings(&ipaddr, &netmask, &gw);
#endif
lwip_init();
#if (LWIP_DHCP==1)
ipaddr.addr = 0;
gw.addr = 0;
netmask.addr = 0;
#endif
/* Add network interface to the netif_list, and set it as default */
if (!xemac_add(netif, &ipaddr, &netmask, &gw, mac_ethernet_address, PLATFORM_EMAC_BASEADDR)) {
xil_printf("Error adding N/W interface\r\n");
return -1;
}
netif_set_default(netif);
/* specify that the network if is up */
netif_set_up(netif);
/* now enable interrupts */
platform_enable_interrupts();
#if (LWIP_DHCP==1)
/* Create a new DHCP client for this interface.
* Note: you must call dhcp_fine_tmr() and dhcp_coarse_tmr() at
* the predefined regular intervals after starting the client.
*/
dhcp_start(netif);
dhcp_timoutcntr = 24;
TxPerfConnMonCntr = 0;
while(((netif->ip_addr.addr) == 0) && (dhcp_timoutcntr > 0)) {
xemacif_input(netif);
if (TcpFastTmrFlag) {
tcp_fasttmr();
TcpFastTmrFlag = 0;
}
if (TcpSlowTmrFlag) {
tcp_slowtmr();
TcpSlowTmrFlag = 0;
}
}
if (dhcp_timoutcntr <= 0) {
if ((netif->ip_addr.addr) == 0) {
xil_printf("DHCP Timeout\r\n");
xil_printf("Configuring default IP of 192.168.1.10\r\n");
IP4_ADDR(&(netif->ip_addr), 192, 168, 1, 10);
IP4_ADDR(&(netif->netmask), 255, 255, 255, 0);
IP4_ADDR(&(netif->gw), 192, 168, 1, 1);
}
}
/* receive and process packets */
print_ip_settings(&(netif->ip_addr), &(netif->netmask), &(netif->gw));
#endif
/* start the application (web server, rxtest, txtest, etc..) */
xil_printf("Setup Done");
IP4_ADDR(&ip_remote, 192, 168, 1, 11);
udp_1 = udp_new();
error = udp_bind(udp_1, IP_ADDR_ANY, Port);
if (error != 0)
{
xil_printf("Failed %d\r\n", error);
}
else if (error == 0)
{
xil_printf("Success\r\n");
}
error = udp_connect(udp_1, &ip_remote, Port);
if (error != 0)
{
xil_printf("Failed %d\r\n", error);
}
else if (error == 0)
{
xil_printf("Success\r\n");
}
while (1)
{
xemacif_input(netif);
count++;
if (count == 80000)
{
p = pbuf_alloc(PBUF_TRANSPORT, buflen, PBUF_POOL);
if (!p) {
xil_printf("error allocating pbuf\r\n");
return ERR_MEM;
}
memcpy(p->payload, data, buflen);
udp_send(udp_1, p);
xil_printf("SEND\r\n");
count = 0;
pbuf_free(p);
}
}
/* never reached */
cleanup_platform();
return 0;
}
----Edit ----
So you know how people figure it out then don't leave an answer. Well here was my problem with the orginal code (I think..) the line of code xemacif_input(netif); gives the Ethernet the ability to process the arp call without it the FPGA will sending out the ARP and then not receiving it will ask repeatedly.
The previous code does appear to have the correct line of code in it. So it might have been a mistake in how the interrupts were configured.
I got this example working and implemented it in my project. If you have questions about this please ask and I will try and give the best answers I can.