发送传感器数据时遇到困难

时间:2015-08-23 10:56:35

标签: python python-2.7 arduino

我尝试通过arduino以太网屏蔽将数据发送到客户端(PC上的python) 我遇到的问题是,当我读到例如arduino中的引脚A0时,我得到1023但是当我将此值发送到python时,我得到49152 ......

arduino代码

#include <SPI.h>         
#include <Ethernet.h>
#include <EthernetUdp.h>

byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   // Enter a MAC    address for your controller below.
IPAddress ip(192,168,0,101);
IPAddress gateway(192,168,0,254);
IPAddress subnet(255,255,255,0);
unsigned int UDPport = 5000;// local port to listen for UDP packets
IPAddress UDPServer(192,168,0,100); // destination device server

const int UDP_PACKET_SIZE= 48;
byte packetBuffer[ UDP_PACKET_SIZE]; //buffer to hold incoming and outgoing  packets 
unsigned int noChange = 0;
int UDPCount = 0;
EthernetUDP Udp;

unsigned long currentTime;
unsigned long secondTime;
unsigned long msPerSecond = 100UL;

float temperature;
float vitesse;
float charge;
float current;

void setup() 
{
Serial.begin(9600);
Ethernet.begin(mac,ip,gateway,gateway,subnet);
Udp.begin(UDPport);
delay(1500);
currentTime=millis();
secondTime = currentTime;
}



void loop()
{
currentTime = millis();
getUDPpacket();

if(currentTime - secondTime > msPerSecond) {

temperature = analogRead(0); //read analog input on pin A0
vitesse = analogRead(1); //read analog input on pin A1
charge = analogRead(2); //read analog input on pin A2
current = analogRead(3); //read analog input on pin A3
Serial.println(temperature);
sendUDPpacket(UDPServer); // send an NTP packet to a time server
secondTime += msPerSecond;
}
}

unsigned int udpCount = 0;
unsigned long sendUDPpacket(IPAddress& address)
{
udpCount++;
memset(packetBuffer, 0, UDP_PACKET_SIZE);            sprintf((char*)packetBuffer,"%u,%u,%u,%u",temperature,vitesse,charge,current);
Udp.beginPacket(address, UDPport);
Udp.write(packetBuffer,UDP_PACKET_SIZE);
Udp.endPacket(); 
}

void getUDPpacket() {
if ( Udp.parsePacket() ) {  

if(Udp.remoteIP() == UDPServer) {
  Serial.print(F("UDP IP OK  "));
}
else {
  Serial.println(F("UDP IP Bad"));
  return;
}
if(Udp.remotePort() == UDPport) {
  Serial.println(F("Port OK"));
}
else {
Serial.println(F("Port Bad"));
  return;
}

Udp.read(packetBuffer,UDP_PACKET_SIZE);  // read the packet into the buffer
Serial.print(F("Received: "));
Serial.println((char*)packetBuffer);
}
}

python代码

import socket
import time


UDP_IP = "192.168.0.100"
UDP_PORT = 5000


sock = socket.socket(socket.AF_INET, # Internet
                 socket.SOCK_DGRAM) # UDP

sock.bind((UDP_IP, UDP_PORT))

while True:
data, addr = sock.recvfrom(48)
print data
time.sleep(5)

我认为问题出在这一行

  sprintf((char*)packetBuffer,"%u,%u,%u,%u",temperature,vitesse,charge,current);

但我不知道该怎么做

1 个答案:

答案 0 :(得分:0)

编译C代码时,应该启用所有警告(例如,在gcc中使用-Wall)。这样,当您尝试使用%u无符号整数格式说明符打印浮点数时会发出警告,因为这会导致未定义的行为。

您应该a)将temperaturevitessechargecurrent转换为无符号整数,然后再将其传递给sprintf(),或者b)更改格式说明符类似于%f,以便sprintf()知道期望浮点数据。

此外,您应该包含<stdio.h>,以便您的程序具有sprintf()的原型;我假设你所包含的那些标题包含原型&amp;与以太网相关的常数和Arduino端口IO功能。